blob: c99480f0b80ae911cedbfde03cba03012e5e721e [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;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080066import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080068import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070069import android.os.Looper;
70import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Parcel;
72import android.os.RemoteException;
73import android.os.Environment;
74import android.os.FileObserver;
75import android.os.FileUtils;
76import android.os.Handler;
San Mehatb1043402010-02-05 08:26:50 -080077import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.os.ParcelFileDescriptor;
79import android.os.Process;
80import android.os.ServiceManager;
81import android.os.SystemClock;
82import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080083import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.util.*;
85import android.view.Display;
86import android.view.WindowManager;
87
88import java.io.File;
89import java.io.FileDescriptor;
90import java.io.FileInputStream;
91import java.io.FileNotFoundException;
92import java.io.FileOutputStream;
93import java.io.FileReader;
94import java.io.FilenameFilter;
95import java.io.IOException;
96import java.io.InputStream;
97import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -080098import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -080099import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.util.ArrayList;
101import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700102import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.Collections;
104import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800105import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.Enumeration;
107import java.util.HashMap;
108import java.util.HashSet;
109import java.util.Iterator;
110import java.util.List;
111import java.util.Map;
112import java.util.Set;
113import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800114import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import java.util.zip.ZipFile;
116import java.util.zip.ZipOutputStream;
117
118class PackageManagerService extends IPackageManager.Stub {
119 private static final String TAG = "PackageManager";
120 private static final boolean DEBUG_SETTINGS = false;
121 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800122 private static final boolean DEBUG_UPGRADE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
124 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
125 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400126 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 private static final int FIRST_APPLICATION_UID =
128 Process.FIRST_APPLICATION_UID;
129 private static final int MAX_APPLICATION_UIDS = 1000;
130
131 private static final boolean SHOW_INFO = false;
132
133 private static final boolean GET_CERTIFICATES = true;
134
Oscar Montemayora8529f62009-11-18 10:14:20 -0800135 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private static final int REMOVE_EVENTS =
138 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
139 private static final int ADD_EVENTS =
140 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
141
142 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
143
144 static final int SCAN_MONITOR = 1<<0;
145 static final int SCAN_NO_DEX = 1<<1;
146 static final int SCAN_FORCE_DEX = 1<<2;
147 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800148 static final int SCAN_NEW_INSTALL = 1<<4;
149 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
151 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
152 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700153 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Dianne Hackborn851a5412009-05-08 12:06:44 -0700155 final int mSdkVersion = Build.VERSION.SDK_INT;
156 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
157 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 final Context mContext;
160 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700161 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 final DisplayMetrics mMetrics;
163 final int mDefParseFlags;
164 final String[] mSeparateProcesses;
165
166 // This is where all application persistent data goes.
167 final File mAppDataDir;
168
Oscar Montemayora8529f62009-11-18 10:14:20 -0800169 // If Encrypted File System feature is enabled, all application persistent data
170 // should go here instead.
171 final File mSecureAppDataDir;
172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 // This is the object monitoring the framework dir.
174 final FileObserver mFrameworkInstallObserver;
175
176 // This is the object monitoring the system app dir.
177 final FileObserver mSystemInstallObserver;
178
179 // This is the object monitoring mAppInstallDir.
180 final FileObserver mAppInstallObserver;
181
182 // This is the object monitoring mDrmAppPrivateInstallDir.
183 final FileObserver mDrmAppInstallObserver;
184
185 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
186 // LOCK HELD. Can be called with mInstallLock held.
187 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 final File mFrameworkDir;
190 final File mSystemAppDir;
191 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700192 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
195 // apps.
196 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 // Lock for state used when installing and doing other long running
201 // operations. Methods that must be called with this lock held have
202 // the prefix "LI".
203 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 // These are the directories in the 3rd party applications installed dir
206 // that we have currently loaded packages from. Keys are the application's
207 // installed zip file (absolute codePath), and values are Package.
208 final HashMap<String, PackageParser.Package> mAppDirs =
209 new HashMap<String, PackageParser.Package>();
210
211 // Information for the parser to write more useful error messages.
212 File mScanningPath;
213 int mLastScanError;
214
215 final int[] mOutPermissions = new int[3];
216
217 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 // Keys are String (package name), values are Package. This also serves
220 // as the lock for the global state. Methods that must be called with
221 // this lock held have the prefix "LP".
222 final HashMap<String, PackageParser.Package> mPackages =
223 new HashMap<String, PackageParser.Package>();
224
225 final Settings mSettings;
226 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
228 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
229 int[] mGlobalGids;
230
231 // These are the built-in uid -> permission mappings that were read from the
232 // etc/permissions.xml file.
233 final SparseArray<HashSet<String>> mSystemPermissions =
234 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 // These are the built-in shared libraries that were read from the
237 // etc/permissions.xml file.
238 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800239
Dianne Hackborn49237342009-08-27 20:08:01 -0700240 // Temporary for building the final shared libraries for an .apk.
241 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800242
Dianne Hackborn49237342009-08-27 20:08:01 -0700243 // These are the features this devices supports that were read from the
244 // etc/permissions.xml file.
245 final HashMap<String, FeatureInfo> mAvailableFeatures =
246 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // All available activities, for your resolving pleasure.
249 final ActivityIntentResolver mActivities =
250 new ActivityIntentResolver();
251
252 // All available receivers, for your resolving pleasure.
253 final ActivityIntentResolver mReceivers =
254 new ActivityIntentResolver();
255
256 // All available services, for your resolving pleasure.
257 final ServiceIntentResolver mServices = new ServiceIntentResolver();
258
259 // Keys are String (provider class name), values are Provider.
260 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
261 new HashMap<ComponentName, PackageParser.Provider>();
262
263 // Mapping from provider base names (first directory in content URI codePath)
264 // to the provider information.
265 final HashMap<String, PackageParser.Provider> mProviders =
266 new HashMap<String, PackageParser.Provider>();
267
268 // Mapping from instrumentation class names to info about them.
269 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
270 new HashMap<ComponentName, PackageParser.Instrumentation>();
271
272 // Mapping from permission names to info about them.
273 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
274 new HashMap<String, PackageParser.PermissionGroup>();
275
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800276 // Packages whose data we have transfered into another package, thus
277 // should no longer exist.
278 final HashSet<String> mTransferedPackages = new HashSet<String>();
279
Dianne Hackborn854060af2009-07-09 18:14:31 -0700280 // Broadcast actions that are only available to the system.
281 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 boolean mSystemReady;
284 boolean mSafeMode;
285 boolean mHasSystemUidErrors;
286
287 ApplicationInfo mAndroidApplication;
288 final ActivityInfo mResolveActivity = new ActivityInfo();
289 final ResolveInfo mResolveInfo = new ResolveInfo();
290 ComponentName mResolveComponentName;
291 PackageParser.Package mPlatformPackage;
292
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700293 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800294 final HashMap<String, ArrayList<String>> mPendingBroadcasts
295 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700296 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800297 static final int MCS_BOUND = 3;
298 static final int END_COPY = 4;
299 static final int INIT_COPY = 5;
300 static final int MCS_UNBIND = 6;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700301 // Delay time in millisecs
302 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800303 private ServiceConnection mDefContainerConn = new ServiceConnection() {
304 public void onServiceConnected(ComponentName name, IBinder service) {
305 IMediaContainerService imcs =
306 IMediaContainerService.Stub.asInterface(service);
307 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
308 mHandler.sendMessage(msg);
309 }
310
311 public void onServiceDisconnected(ComponentName name) {
312 }
313 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700314
315 class PackageHandler extends Handler {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800316 final ArrayList<InstallArgs> mPendingInstalls =
317 new ArrayList<InstallArgs>();
318 // Service Connection to remote media container service to copy
319 // package uri's from external media onto secure containers
320 // or internal storage.
321 private IMediaContainerService mContainerService = null;
322
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700323 PackageHandler(Looper looper) {
324 super(looper);
325 }
326 public void handleMessage(Message msg) {
327 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800328 case INIT_COPY: {
329 InstallArgs args = (InstallArgs) msg.obj;
330 args.createCopyFile();
331 Intent service = new Intent().setComponent(new ComponentName(
332 "com.android.defcontainer",
333 "com.android.defcontainer.DefaultContainerService"));
334 if (mContainerService != null) {
335 // No need to add to pending list. Use remote stub directly
336 handleStartCopy(args);
337 } else {
338 if (mContext.bindService(service, mDefContainerConn,
339 Context.BIND_AUTO_CREATE)) {
340 mPendingInstalls.add(args);
341 } else {
342 Log.e(TAG, "Failed to bind to media container service");
343 // Indicate install failure TODO add new error code
344 processPendingInstall(args,
345 PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800346 }
347 }
348 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800349 }
350 case MCS_BOUND: {
351 // Initialize mContainerService if needed.
352 if (msg.obj != null) {
353 mContainerService = (IMediaContainerService) msg.obj;
354 }
355 if (mPendingInstalls.size() > 0) {
356 InstallArgs args = mPendingInstalls.remove(0);
357 if (args != null) {
358 handleStartCopy(args);
359 }
360 }
361 break;
362 }
363 case MCS_UNBIND : {
364 if (mPendingInstalls.size() == 0) {
365 mContext.unbindService(mDefContainerConn);
366 mContainerService = null;
367 }
368 break;
369 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700370 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800371 String packages[];
372 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700373 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700374 int uids[];
375 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800376 if (mPendingBroadcasts == null) {
377 return;
378 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700379 size = mPendingBroadcasts.size();
380 if (size <= 0) {
381 // Nothing to be done. Just return
382 return;
383 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800384 packages = new String[size];
385 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700386 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800387 Iterator<HashMap.Entry<String, ArrayList<String>>>
388 it = mPendingBroadcasts.entrySet().iterator();
389 int i = 0;
390 while (it.hasNext() && i < size) {
391 HashMap.Entry<String, ArrayList<String>> ent = it.next();
392 packages[i] = ent.getKey();
393 components[i] = ent.getValue();
394 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700395 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800396 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700397 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800398 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700399 mPendingBroadcasts.clear();
400 }
401 // Send broadcasts
402 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800403 sendPackageChangedBroadcast(packages[i], true,
404 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700405 }
406 break;
407 }
408 }
409 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800410
411 // Utility method to initiate copying apk via media
412 // container service.
413 private void handleStartCopy(InstallArgs args) {
414 int ret = PackageManager.INSTALL_SUCCEEDED;
415 if (mContainerService == null) {
416 // Install error
417 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
418 } else {
419 ret = args.copyApk(mContainerService);
420 }
421 mHandler.sendEmptyMessage(MCS_UNBIND);
422 processPendingInstall(args, ret);
423 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700424 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800425
426 static boolean installOnSd(int flags) {
427 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
428 ((flags & PackageManager.INSTALL_ON_SDCARD) == 0)) {
429 return false;
430 }
431 return true;
432 }
433
434 static boolean isFwdLocked(int flags) {
435 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
436 return true;
437 }
438 return false;
439 }
440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 public static final IPackageManager main(Context context, boolean factoryTest) {
442 PackageManagerService m = new PackageManagerService(context, factoryTest);
443 ServiceManager.addService("package", m);
444 return m;
445 }
446
447 static String[] splitString(String str, char sep) {
448 int count = 1;
449 int i = 0;
450 while ((i=str.indexOf(sep, i)) >= 0) {
451 count++;
452 i++;
453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 String[] res = new String[count];
456 i=0;
457 count = 0;
458 int lastI=0;
459 while ((i=str.indexOf(sep, i)) >= 0) {
460 res[count] = str.substring(lastI, i);
461 count++;
462 i++;
463 lastI = i;
464 }
465 res[count] = str.substring(lastI, str.length());
466 return res;
467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800470 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 if (mSdkVersion <= 0) {
474 Log.w(TAG, "**** ro.build.version.sdk not set!");
475 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 mContext = context;
478 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700479 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 mMetrics = new DisplayMetrics();
481 mSettings = new Settings();
482 mSettings.addSharedUserLP("android.uid.system",
483 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
484 mSettings.addSharedUserLP("android.uid.phone",
485 MULTIPLE_APPLICATION_UIDS
486 ? RADIO_UID : FIRST_APPLICATION_UID,
487 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400488 mSettings.addSharedUserLP("android.uid.log",
489 MULTIPLE_APPLICATION_UIDS
490 ? LOG_UID : FIRST_APPLICATION_UID,
491 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492
493 String separateProcesses = SystemProperties.get("debug.separate_processes");
494 if (separateProcesses != null && separateProcesses.length() > 0) {
495 if ("*".equals(separateProcesses)) {
496 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
497 mSeparateProcesses = null;
498 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
499 } else {
500 mDefParseFlags = 0;
501 mSeparateProcesses = separateProcesses.split(",");
502 Log.w(TAG, "Running with debug.separate_processes: "
503 + separateProcesses);
504 }
505 } else {
506 mDefParseFlags = 0;
507 mSeparateProcesses = null;
508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 Installer installer = new Installer();
511 // Little hacky thing to check if installd is here, to determine
512 // whether we are running on the simulator and thus need to take
513 // care of building the /data file structure ourself.
514 // (apparently the sim now has a working installer)
515 if (installer.ping() && Process.supportsProcesses()) {
516 mInstaller = installer;
517 } else {
518 mInstaller = null;
519 }
520
521 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
522 Display d = wm.getDefaultDisplay();
523 d.getMetrics(mMetrics);
524
525 synchronized (mInstallLock) {
526 synchronized (mPackages) {
527 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700528 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 File dataDir = Environment.getDataDirectory();
531 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800532 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
534
535 if (mInstaller == null) {
536 // Make sure these dirs exist, when we are running in
537 // the simulator.
538 // Make a wide-open directory for random misc stuff.
539 File miscDir = new File(dataDir, "misc");
540 miscDir.mkdirs();
541 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800542 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 mDrmAppPrivateInstallDir.mkdirs();
544 }
545
546 readPermissions();
547
548 mRestoredSettings = mSettings.readLP();
549 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800550
551 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800553
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800554 // Set flag to monitor and not change apk file paths when
555 // scanning install directories.
556 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700557 if (mNoDexOpt) {
558 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800559 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700565 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700568 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 /**
571 * Out of paranoia, ensure that everything in the boot class
572 * path has been dexed.
573 */
574 String bootClassPath = System.getProperty("java.boot.class.path");
575 if (bootClassPath != null) {
576 String[] paths = splitString(bootClassPath, ':');
577 for (int i=0; i<paths.length; i++) {
578 try {
579 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
580 libFiles.add(paths[i]);
581 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700582 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 }
584 } catch (FileNotFoundException e) {
585 Log.w(TAG, "Boot class path not found: " + paths[i]);
586 } catch (IOException e) {
587 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
588 }
589 }
590 } else {
591 Log.w(TAG, "No BOOTCLASSPATH found!");
592 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 /**
595 * Also ensure all external libraries have had dexopt run on them.
596 */
597 if (mSharedLibraries.size() > 0) {
598 Iterator<String> libs = mSharedLibraries.values().iterator();
599 while (libs.hasNext()) {
600 String lib = libs.next();
601 try {
602 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
603 libFiles.add(lib);
604 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700605 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 }
607 } catch (FileNotFoundException e) {
608 Log.w(TAG, "Library not found: " + lib);
609 } catch (IOException e) {
610 Log.w(TAG, "Exception reading library: " + lib, e);
611 }
612 }
613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 // Gross hack for now: we know this file doesn't contain any
616 // code, so don't dexopt it to avoid the resulting log spew.
617 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 /**
620 * And there are a number of commands implemented in Java, which
621 * we currently need to do the dexopt on so that they can be
622 * run from a non-root shell.
623 */
624 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700625 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 for (int i=0; i<frameworkFiles.length; i++) {
627 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
628 String path = libPath.getPath();
629 // Skip the file if we alrady did it.
630 if (libFiles.contains(path)) {
631 continue;
632 }
633 // Skip the file if it is not a type we want to dexopt.
634 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
635 continue;
636 }
637 try {
638 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
639 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700640 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 }
642 } catch (FileNotFoundException e) {
643 Log.w(TAG, "Jar not found: " + path);
644 } catch (IOException e) {
645 Log.w(TAG, "Exception reading jar: " + path, e);
646 }
647 }
648 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800649
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700650 if (didDexOpt) {
651 // If we had to do a dexopt of one of the previous
652 // things, then something on the system has changed.
653 // Consider this significant, and wipe away all other
654 // existing dexopt files to ensure we don't leave any
655 // dangling around.
656 String[] files = mDalvikCacheDir.list();
657 if (files != null) {
658 for (int i=0; i<files.length; i++) {
659 String fn = files[i];
660 if (fn.startsWith("data@app@")
661 || fn.startsWith("data@app-private@")) {
662 Log.i(TAG, "Pruning dalvik file: " + fn);
663 (new File(mDalvikCacheDir, fn)).delete();
664 }
665 }
666 }
667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800669
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800670 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 mFrameworkInstallObserver = new AppDirObserver(
672 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
673 mFrameworkInstallObserver.startWatching();
674 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800675 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800676
677 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
679 mSystemInstallObserver = new AppDirObserver(
680 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
681 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800682 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800683
684 if (mInstaller != null) {
685 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
686 mInstaller.moveFiles();
687 }
688
689 // Prune any system packages that no longer exist.
690 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
691 while (psit.hasNext()) {
692 PackageSetting ps = psit.next();
693 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
694 && !mPackages.containsKey(ps.name)) {
695 psit.remove();
696 String msg = "System package " + ps.name
697 + " no longer exists; wiping its data";
698 reportSettingsProblem(Log.WARN, msg);
699 if (mInstaller != null) {
700 // XXX how to set useEncryptedFSDir for packages that
701 // are not encrypted?
702 mInstaller.remove(ps.name, true);
703 }
704 }
705 }
706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 mAppInstallDir = new File(dataDir, "app");
708 if (mInstaller == null) {
709 // Make sure these dirs exist, when we are running in
710 // the simulator.
711 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
712 }
713 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800714 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 //clean up list
716 for(int i = 0; i < deletePkgsList.size(); i++) {
717 //clean up here
718 cleanupInstallFailedPackage(deletePkgsList.get(i));
719 }
720 //delete tmp files
721 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800722
723 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 SystemClock.uptimeMillis());
725 mAppInstallObserver = new AppDirObserver(
726 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
727 mAppInstallObserver.startWatching();
728 scanDirLI(mAppInstallDir, 0, scanMode);
729
730 mDrmAppInstallObserver = new AppDirObserver(
731 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
732 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800733 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800735 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 SystemClock.uptimeMillis());
737 Log.i(TAG, "Time to scan packages: "
738 + ((SystemClock.uptimeMillis()-startTime)/1000f)
739 + " seconds");
740
741 updatePermissionsLP();
742
743 mSettings.writeLP();
744
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800745 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 // Now after opening every single application zip, make sure they
749 // are all flushed. Not really needed, but keeps things nice and
750 // tidy.
751 Runtime.getRuntime().gc();
752 } // synchronized (mPackages)
753 } // synchronized (mInstallLock)
754 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 @Override
757 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
758 throws RemoteException {
759 try {
760 return super.onTransact(code, data, reply, flags);
761 } catch (RuntimeException e) {
762 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
763 Log.e(TAG, "Package Manager Crash", e);
764 }
765 throw e;
766 }
767 }
768
Dianne Hackborne6620b22010-01-22 14:46:21 -0800769 void cleanupInstallFailedPackage(PackageSetting ps) {
770 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800772 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
773 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 if (retCode < 0) {
775 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800776 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
778 } else {
779 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800780 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 File dataDir = new File(pkg.applicationInfo.dataDir);
782 dataDir.delete();
783 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800784 if (ps.codePath != null) {
785 if (!ps.codePath.delete()) {
786 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
787 }
788 }
789 if (ps.resourcePath != null) {
790 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
791 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
792 }
793 }
794 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 }
796
797 void readPermissions() {
798 // Read permissions from .../etc/permission directory.
799 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
800 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
801 Log.w(TAG, "No directory " + libraryDir + ", skipping");
802 return;
803 }
804 if (!libraryDir.canRead()) {
805 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
806 return;
807 }
808
809 // Iterate over the files in the directory and scan .xml files
810 for (File f : libraryDir.listFiles()) {
811 // We'll read platform.xml last
812 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
813 continue;
814 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 if (!f.getPath().endsWith(".xml")) {
817 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
818 continue;
819 }
820 if (!f.canRead()) {
821 Log.w(TAG, "Permissions library file " + f + " cannot be read");
822 continue;
823 }
824
825 readPermissionsFromXml(f);
826 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
829 final File permFile = new File(Environment.getRootDirectory(),
830 "etc/permissions/platform.xml");
831 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800832
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700833 StringBuilder sb = new StringBuilder(128);
834 sb.append("Libs:");
835 Iterator<String> it = mSharedLibraries.keySet().iterator();
836 while (it.hasNext()) {
837 sb.append(' ');
838 String name = it.next();
839 sb.append(name);
840 sb.append(':');
841 sb.append(mSharedLibraries.get(name));
842 }
843 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800844
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700845 sb.setLength(0);
846 sb.append("Features:");
847 it = mAvailableFeatures.keySet().iterator();
848 while (it.hasNext()) {
849 sb.append(' ');
850 sb.append(it.next());
851 }
852 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800854
855 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 FileReader permReader = null;
857 try {
858 permReader = new FileReader(permFile);
859 } catch (FileNotFoundException e) {
860 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
861 return;
862 }
863
864 try {
865 XmlPullParser parser = Xml.newPullParser();
866 parser.setInput(permReader);
867
868 XmlUtils.beginDocument(parser, "permissions");
869
870 while (true) {
871 XmlUtils.nextElement(parser);
872 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
873 break;
874 }
875
876 String name = parser.getName();
877 if ("group".equals(name)) {
878 String gidStr = parser.getAttributeValue(null, "gid");
879 if (gidStr != null) {
880 int gid = Integer.parseInt(gidStr);
881 mGlobalGids = appendInt(mGlobalGids, gid);
882 } else {
883 Log.w(TAG, "<group> without gid at "
884 + parser.getPositionDescription());
885 }
886
887 XmlUtils.skipCurrentTag(parser);
888 continue;
889 } else if ("permission".equals(name)) {
890 String perm = parser.getAttributeValue(null, "name");
891 if (perm == null) {
892 Log.w(TAG, "<permission> without name at "
893 + parser.getPositionDescription());
894 XmlUtils.skipCurrentTag(parser);
895 continue;
896 }
897 perm = perm.intern();
898 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 } else if ("assign-permission".equals(name)) {
901 String perm = parser.getAttributeValue(null, "name");
902 if (perm == null) {
903 Log.w(TAG, "<assign-permission> without name at "
904 + parser.getPositionDescription());
905 XmlUtils.skipCurrentTag(parser);
906 continue;
907 }
908 String uidStr = parser.getAttributeValue(null, "uid");
909 if (uidStr == null) {
910 Log.w(TAG, "<assign-permission> without uid at "
911 + parser.getPositionDescription());
912 XmlUtils.skipCurrentTag(parser);
913 continue;
914 }
915 int uid = Process.getUidForName(uidStr);
916 if (uid < 0) {
917 Log.w(TAG, "<assign-permission> with unknown uid \""
918 + uidStr + "\" at "
919 + parser.getPositionDescription());
920 XmlUtils.skipCurrentTag(parser);
921 continue;
922 }
923 perm = perm.intern();
924 HashSet<String> perms = mSystemPermissions.get(uid);
925 if (perms == null) {
926 perms = new HashSet<String>();
927 mSystemPermissions.put(uid, perms);
928 }
929 perms.add(perm);
930 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 } else if ("library".equals(name)) {
933 String lname = parser.getAttributeValue(null, "name");
934 String lfile = parser.getAttributeValue(null, "file");
935 if (lname == null) {
936 Log.w(TAG, "<library> without name at "
937 + parser.getPositionDescription());
938 } else if (lfile == null) {
939 Log.w(TAG, "<library> without file at "
940 + parser.getPositionDescription());
941 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700942 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700943 mSharedLibraries.put(lname, lfile);
944 }
945 XmlUtils.skipCurrentTag(parser);
946 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800947
Dianne Hackborn49237342009-08-27 20:08:01 -0700948 } else if ("feature".equals(name)) {
949 String fname = parser.getAttributeValue(null, "name");
950 if (fname == null) {
951 Log.w(TAG, "<feature> without name at "
952 + parser.getPositionDescription());
953 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700954 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700955 FeatureInfo fi = new FeatureInfo();
956 fi.name = fname;
957 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 }
959 XmlUtils.skipCurrentTag(parser);
960 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 } else {
963 XmlUtils.skipCurrentTag(parser);
964 continue;
965 }
966
967 }
968 } catch (XmlPullParserException e) {
969 Log.w(TAG, "Got execption parsing permissions.", e);
970 } catch (IOException e) {
971 Log.w(TAG, "Got execption parsing permissions.", e);
972 }
973 }
974
975 void readPermission(XmlPullParser parser, String name)
976 throws IOException, XmlPullParserException {
977
978 name = name.intern();
979
980 BasePermission bp = mSettings.mPermissions.get(name);
981 if (bp == null) {
982 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
983 mSettings.mPermissions.put(name, bp);
984 }
985 int outerDepth = parser.getDepth();
986 int type;
987 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
988 && (type != XmlPullParser.END_TAG
989 || parser.getDepth() > outerDepth)) {
990 if (type == XmlPullParser.END_TAG
991 || type == XmlPullParser.TEXT) {
992 continue;
993 }
994
995 String tagName = parser.getName();
996 if ("group".equals(tagName)) {
997 String gidStr = parser.getAttributeValue(null, "gid");
998 if (gidStr != null) {
999 int gid = Process.getGidForName(gidStr);
1000 bp.gids = appendInt(bp.gids, gid);
1001 } else {
1002 Log.w(TAG, "<group> without gid at "
1003 + parser.getPositionDescription());
1004 }
1005 }
1006 XmlUtils.skipCurrentTag(parser);
1007 }
1008 }
1009
1010 static int[] appendInt(int[] cur, int val) {
1011 if (cur == null) {
1012 return new int[] { val };
1013 }
1014 final int N = cur.length;
1015 for (int i=0; i<N; i++) {
1016 if (cur[i] == val) {
1017 return cur;
1018 }
1019 }
1020 int[] ret = new int[N+1];
1021 System.arraycopy(cur, 0, ret, 0, N);
1022 ret[N] = val;
1023 return ret;
1024 }
1025
1026 static int[] appendInts(int[] cur, int[] add) {
1027 if (add == null) return cur;
1028 if (cur == null) return add;
1029 final int N = add.length;
1030 for (int i=0; i<N; i++) {
1031 cur = appendInt(cur, add[i]);
1032 }
1033 return cur;
1034 }
1035
1036 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001037 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1038 // The package has been uninstalled but has retained data and resources.
1039 return PackageParser.generatePackageInfo(p, null, flags);
1040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 final PackageSetting ps = (PackageSetting)p.mExtras;
1042 if (ps == null) {
1043 return null;
1044 }
1045 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1046 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1047 }
1048
1049 public PackageInfo getPackageInfo(String packageName, int flags) {
1050 synchronized (mPackages) {
1051 PackageParser.Package p = mPackages.get(packageName);
1052 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001053 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 + ": " + p);
1055 if (p != null) {
1056 return generatePackageInfo(p, flags);
1057 }
1058 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1059 return generatePackageInfoFromSettingsLP(packageName, flags);
1060 }
1061 }
1062 return null;
1063 }
1064
1065 public int getPackageUid(String packageName) {
1066 synchronized (mPackages) {
1067 PackageParser.Package p = mPackages.get(packageName);
1068 if(p != null) {
1069 return p.applicationInfo.uid;
1070 }
1071 PackageSetting ps = mSettings.mPackages.get(packageName);
1072 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1073 return -1;
1074 }
1075 p = ps.pkg;
1076 return p != null ? p.applicationInfo.uid : -1;
1077 }
1078 }
1079
1080 public int[] getPackageGids(String packageName) {
1081 synchronized (mPackages) {
1082 PackageParser.Package p = mPackages.get(packageName);
1083 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001084 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 + ": " + p);
1086 if (p != null) {
1087 final PackageSetting ps = (PackageSetting)p.mExtras;
1088 final SharedUserSetting suid = ps.sharedUser;
1089 return suid != null ? suid.gids : ps.gids;
1090 }
1091 }
1092 // stupid thing to indicate an error.
1093 return new int[0];
1094 }
1095
1096 public PermissionInfo getPermissionInfo(String name, int flags) {
1097 synchronized (mPackages) {
1098 final BasePermission p = mSettings.mPermissions.get(name);
1099 if (p != null && p.perm != null) {
1100 return PackageParser.generatePermissionInfo(p.perm, flags);
1101 }
1102 return null;
1103 }
1104 }
1105
1106 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1107 synchronized (mPackages) {
1108 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1109 for (BasePermission p : mSettings.mPermissions.values()) {
1110 if (group == null) {
1111 if (p.perm.info.group == null) {
1112 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1113 }
1114 } else {
1115 if (group.equals(p.perm.info.group)) {
1116 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1117 }
1118 }
1119 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 if (out.size() > 0) {
1122 return out;
1123 }
1124 return mPermissionGroups.containsKey(group) ? out : null;
1125 }
1126 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1129 synchronized (mPackages) {
1130 return PackageParser.generatePermissionGroupInfo(
1131 mPermissionGroups.get(name), flags);
1132 }
1133 }
1134
1135 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1136 synchronized (mPackages) {
1137 final int N = mPermissionGroups.size();
1138 ArrayList<PermissionGroupInfo> out
1139 = new ArrayList<PermissionGroupInfo>(N);
1140 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1141 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1142 }
1143 return out;
1144 }
1145 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1148 PackageSetting ps = mSettings.mPackages.get(packageName);
1149 if(ps != null) {
1150 if(ps.pkg == null) {
1151 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1152 if(pInfo != null) {
1153 return pInfo.applicationInfo;
1154 }
1155 return null;
1156 }
1157 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1158 }
1159 return null;
1160 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1163 PackageSetting ps = mSettings.mPackages.get(packageName);
1164 if(ps != null) {
1165 if(ps.pkg == null) {
1166 ps.pkg = new PackageParser.Package(packageName);
1167 ps.pkg.applicationInfo.packageName = packageName;
1168 }
1169 return generatePackageInfo(ps.pkg, flags);
1170 }
1171 return null;
1172 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1175 synchronized (mPackages) {
1176 PackageParser.Package p = mPackages.get(packageName);
1177 if (Config.LOGV) Log.v(
1178 TAG, "getApplicationInfo " + packageName
1179 + ": " + p);
1180 if (p != null) {
1181 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001182 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
1184 if ("android".equals(packageName)||"system".equals(packageName)) {
1185 return mAndroidApplication;
1186 }
1187 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1188 return generateApplicationInfoFromSettingsLP(packageName, flags);
1189 }
1190 }
1191 return null;
1192 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001193
1194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1196 mContext.enforceCallingOrSelfPermission(
1197 android.Manifest.permission.CLEAR_APP_CACHE, null);
1198 // Queue up an async operation since clearing cache may take a little while.
1199 mHandler.post(new Runnable() {
1200 public void run() {
1201 mHandler.removeCallbacks(this);
1202 int retCode = -1;
1203 if (mInstaller != null) {
1204 retCode = mInstaller.freeCache(freeStorageSize);
1205 if (retCode < 0) {
1206 Log.w(TAG, "Couldn't clear application caches");
1207 }
1208 } //end if mInstaller
1209 if (observer != null) {
1210 try {
1211 observer.onRemoveCompleted(null, (retCode >= 0));
1212 } catch (RemoteException e) {
1213 Log.w(TAG, "RemoveException when invoking call back");
1214 }
1215 }
1216 }
1217 });
1218 }
1219
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001220 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001221 mContext.enforceCallingOrSelfPermission(
1222 android.Manifest.permission.CLEAR_APP_CACHE, null);
1223 // Queue up an async operation since clearing cache may take a little while.
1224 mHandler.post(new Runnable() {
1225 public void run() {
1226 mHandler.removeCallbacks(this);
1227 int retCode = -1;
1228 if (mInstaller != null) {
1229 retCode = mInstaller.freeCache(freeStorageSize);
1230 if (retCode < 0) {
1231 Log.w(TAG, "Couldn't clear application caches");
1232 }
1233 }
1234 if(pi != null) {
1235 try {
1236 // Callback via pending intent
1237 int code = (retCode >= 0) ? 1 : 0;
1238 pi.sendIntent(null, code, null,
1239 null, null);
1240 } catch (SendIntentException e1) {
1241 Log.i(TAG, "Failed to send pending intent");
1242 }
1243 }
1244 }
1245 });
1246 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1249 synchronized (mPackages) {
1250 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001251
1252 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001254 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
1256 if (mResolveComponentName.equals(component)) {
1257 return mResolveActivity;
1258 }
1259 }
1260 return null;
1261 }
1262
1263 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1264 synchronized (mPackages) {
1265 PackageParser.Activity a = mReceivers.mActivities.get(component);
1266 if (Config.LOGV) Log.v(
1267 TAG, "getReceiverInfo " + component + ": " + a);
1268 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1269 return PackageParser.generateActivityInfo(a, flags);
1270 }
1271 }
1272 return null;
1273 }
1274
1275 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1276 synchronized (mPackages) {
1277 PackageParser.Service s = mServices.mServices.get(component);
1278 if (Config.LOGV) Log.v(
1279 TAG, "getServiceInfo " + component + ": " + s);
1280 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1281 return PackageParser.generateServiceInfo(s, flags);
1282 }
1283 }
1284 return null;
1285 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 public String[] getSystemSharedLibraryNames() {
1288 Set<String> libSet;
1289 synchronized (mPackages) {
1290 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001291 int size = libSet.size();
1292 if (size > 0) {
1293 String[] libs = new String[size];
1294 libSet.toArray(libs);
1295 return libs;
1296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001298 return null;
1299 }
1300
1301 public FeatureInfo[] getSystemAvailableFeatures() {
1302 Collection<FeatureInfo> featSet;
1303 synchronized (mPackages) {
1304 featSet = mAvailableFeatures.values();
1305 int size = featSet.size();
1306 if (size > 0) {
1307 FeatureInfo[] features = new FeatureInfo[size+1];
1308 featSet.toArray(features);
1309 FeatureInfo fi = new FeatureInfo();
1310 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1311 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1312 features[size] = fi;
1313 return features;
1314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
1316 return null;
1317 }
1318
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001319 public boolean hasSystemFeature(String name) {
1320 synchronized (mPackages) {
1321 return mAvailableFeatures.containsKey(name);
1322 }
1323 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 public int checkPermission(String permName, String pkgName) {
1326 synchronized (mPackages) {
1327 PackageParser.Package p = mPackages.get(pkgName);
1328 if (p != null && p.mExtras != null) {
1329 PackageSetting ps = (PackageSetting)p.mExtras;
1330 if (ps.sharedUser != null) {
1331 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1332 return PackageManager.PERMISSION_GRANTED;
1333 }
1334 } else if (ps.grantedPermissions.contains(permName)) {
1335 return PackageManager.PERMISSION_GRANTED;
1336 }
1337 }
1338 }
1339 return PackageManager.PERMISSION_DENIED;
1340 }
1341
1342 public int checkUidPermission(String permName, int uid) {
1343 synchronized (mPackages) {
1344 Object obj = mSettings.getUserIdLP(uid);
1345 if (obj != null) {
1346 if (obj instanceof SharedUserSetting) {
1347 SharedUserSetting sus = (SharedUserSetting)obj;
1348 if (sus.grantedPermissions.contains(permName)) {
1349 return PackageManager.PERMISSION_GRANTED;
1350 }
1351 } else if (obj instanceof PackageSetting) {
1352 PackageSetting ps = (PackageSetting)obj;
1353 if (ps.grantedPermissions.contains(permName)) {
1354 return PackageManager.PERMISSION_GRANTED;
1355 }
1356 }
1357 } else {
1358 HashSet<String> perms = mSystemPermissions.get(uid);
1359 if (perms != null && perms.contains(permName)) {
1360 return PackageManager.PERMISSION_GRANTED;
1361 }
1362 }
1363 }
1364 return PackageManager.PERMISSION_DENIED;
1365 }
1366
1367 private BasePermission findPermissionTreeLP(String permName) {
1368 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1369 if (permName.startsWith(bp.name) &&
1370 permName.length() > bp.name.length() &&
1371 permName.charAt(bp.name.length()) == '.') {
1372 return bp;
1373 }
1374 }
1375 return null;
1376 }
1377
1378 private BasePermission checkPermissionTreeLP(String permName) {
1379 if (permName != null) {
1380 BasePermission bp = findPermissionTreeLP(permName);
1381 if (bp != null) {
1382 if (bp.uid == Binder.getCallingUid()) {
1383 return bp;
1384 }
1385 throw new SecurityException("Calling uid "
1386 + Binder.getCallingUid()
1387 + " is not allowed to add to permission tree "
1388 + bp.name + " owned by uid " + bp.uid);
1389 }
1390 }
1391 throw new SecurityException("No permission tree found for " + permName);
1392 }
1393
1394 public boolean addPermission(PermissionInfo info) {
1395 synchronized (mPackages) {
1396 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1397 throw new SecurityException("Label must be specified in permission");
1398 }
1399 BasePermission tree = checkPermissionTreeLP(info.name);
1400 BasePermission bp = mSettings.mPermissions.get(info.name);
1401 boolean added = bp == null;
1402 if (added) {
1403 bp = new BasePermission(info.name, tree.sourcePackage,
1404 BasePermission.TYPE_DYNAMIC);
1405 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1406 throw new SecurityException(
1407 "Not allowed to modify non-dynamic permission "
1408 + info.name);
1409 }
1410 bp.perm = new PackageParser.Permission(tree.perm.owner,
1411 new PermissionInfo(info));
1412 bp.perm.info.packageName = tree.perm.info.packageName;
1413 bp.uid = tree.uid;
1414 if (added) {
1415 mSettings.mPermissions.put(info.name, bp);
1416 }
1417 mSettings.writeLP();
1418 return added;
1419 }
1420 }
1421
1422 public void removePermission(String name) {
1423 synchronized (mPackages) {
1424 checkPermissionTreeLP(name);
1425 BasePermission bp = mSettings.mPermissions.get(name);
1426 if (bp != null) {
1427 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1428 throw new SecurityException(
1429 "Not allowed to modify non-dynamic permission "
1430 + name);
1431 }
1432 mSettings.mPermissions.remove(name);
1433 mSettings.writeLP();
1434 }
1435 }
1436 }
1437
Dianne Hackborn854060af2009-07-09 18:14:31 -07001438 public boolean isProtectedBroadcast(String actionName) {
1439 synchronized (mPackages) {
1440 return mProtectedBroadcasts.contains(actionName);
1441 }
1442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 public int checkSignatures(String pkg1, String pkg2) {
1445 synchronized (mPackages) {
1446 PackageParser.Package p1 = mPackages.get(pkg1);
1447 PackageParser.Package p2 = mPackages.get(pkg2);
1448 if (p1 == null || p1.mExtras == null
1449 || p2 == null || p2.mExtras == null) {
1450 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1451 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001452 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 }
1454 }
1455
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001456 public int checkUidSignatures(int uid1, int uid2) {
1457 synchronized (mPackages) {
1458 Signature[] s1;
1459 Signature[] s2;
1460 Object obj = mSettings.getUserIdLP(uid1);
1461 if (obj != null) {
1462 if (obj instanceof SharedUserSetting) {
1463 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1464 } else if (obj instanceof PackageSetting) {
1465 s1 = ((PackageSetting)obj).signatures.mSignatures;
1466 } else {
1467 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1468 }
1469 } else {
1470 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1471 }
1472 obj = mSettings.getUserIdLP(uid2);
1473 if (obj != null) {
1474 if (obj instanceof SharedUserSetting) {
1475 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1476 } else if (obj instanceof PackageSetting) {
1477 s2 = ((PackageSetting)obj).signatures.mSignatures;
1478 } else {
1479 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1480 }
1481 } else {
1482 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1483 }
1484 return checkSignaturesLP(s1, s2);
1485 }
1486 }
1487
1488 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1489 if (s1 == null) {
1490 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1492 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1493 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001494 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1496 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001497 final int N1 = s1.length;
1498 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 for (int i=0; i<N1; i++) {
1500 boolean match = false;
1501 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001502 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 match = true;
1504 break;
1505 }
1506 }
1507 if (!match) {
1508 return PackageManager.SIGNATURE_NO_MATCH;
1509 }
1510 }
1511 return PackageManager.SIGNATURE_MATCH;
1512 }
1513
1514 public String[] getPackagesForUid(int uid) {
1515 synchronized (mPackages) {
1516 Object obj = mSettings.getUserIdLP(uid);
1517 if (obj instanceof SharedUserSetting) {
1518 SharedUserSetting sus = (SharedUserSetting)obj;
1519 final int N = sus.packages.size();
1520 String[] res = new String[N];
1521 Iterator<PackageSetting> it = sus.packages.iterator();
1522 int i=0;
1523 while (it.hasNext()) {
1524 res[i++] = it.next().name;
1525 }
1526 return res;
1527 } else if (obj instanceof PackageSetting) {
1528 PackageSetting ps = (PackageSetting)obj;
1529 return new String[] { ps.name };
1530 }
1531 }
1532 return null;
1533 }
1534
1535 public String getNameForUid(int uid) {
1536 synchronized (mPackages) {
1537 Object obj = mSettings.getUserIdLP(uid);
1538 if (obj instanceof SharedUserSetting) {
1539 SharedUserSetting sus = (SharedUserSetting)obj;
1540 return sus.name + ":" + sus.userId;
1541 } else if (obj instanceof PackageSetting) {
1542 PackageSetting ps = (PackageSetting)obj;
1543 return ps.name;
1544 }
1545 }
1546 return null;
1547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 public int getUidForSharedUser(String sharedUserName) {
1550 if(sharedUserName == null) {
1551 return -1;
1552 }
1553 synchronized (mPackages) {
1554 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1555 if(suid == null) {
1556 return -1;
1557 }
1558 return suid.userId;
1559 }
1560 }
1561
1562 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1563 int flags) {
1564 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001565 return chooseBestActivity(intent, resolvedType, flags, query);
1566 }
1567
Mihai Predaeae850c2009-05-13 10:13:48 +02001568 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1569 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 if (query != null) {
1571 final int N = query.size();
1572 if (N == 1) {
1573 return query.get(0);
1574 } else if (N > 1) {
1575 // If there is more than one activity with the same priority,
1576 // then let the user decide between them.
1577 ResolveInfo r0 = query.get(0);
1578 ResolveInfo r1 = query.get(1);
1579 if (false) {
1580 System.out.println(r0.activityInfo.name +
1581 "=" + r0.priority + " vs " +
1582 r1.activityInfo.name +
1583 "=" + r1.priority);
1584 }
1585 // If the first activity has a higher priority, or a different
1586 // default, then it is always desireable to pick it.
1587 if (r0.priority != r1.priority
1588 || r0.preferredOrder != r1.preferredOrder
1589 || r0.isDefault != r1.isDefault) {
1590 return query.get(0);
1591 }
1592 // If we have saved a preference for a preferred activity for
1593 // this Intent, use that.
1594 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1595 flags, query, r0.priority);
1596 if (ri != null) {
1597 return ri;
1598 }
1599 return mResolveInfo;
1600 }
1601 }
1602 return null;
1603 }
1604
1605 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1606 int flags, List<ResolveInfo> query, int priority) {
1607 synchronized (mPackages) {
1608 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1609 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001610 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1612 if (prefs != null && prefs.size() > 0) {
1613 // First figure out how good the original match set is.
1614 // We will only allow preferred activities that came
1615 // from the same match quality.
1616 int match = 0;
1617 final int N = query.size();
1618 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1619 for (int j=0; j<N; j++) {
1620 ResolveInfo ri = query.get(j);
1621 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1622 + ": 0x" + Integer.toHexString(match));
1623 if (ri.match > match) match = ri.match;
1624 }
1625 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1626 + Integer.toHexString(match));
1627 match &= IntentFilter.MATCH_CATEGORY_MASK;
1628 final int M = prefs.size();
1629 for (int i=0; i<M; i++) {
1630 PreferredActivity pa = prefs.get(i);
1631 if (pa.mMatch != match) {
1632 continue;
1633 }
1634 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1635 if (DEBUG_PREFERRED) {
1636 Log.v(TAG, "Got preferred activity:");
1637 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1638 }
1639 if (ai != null) {
1640 for (int j=0; j<N; j++) {
1641 ResolveInfo ri = query.get(j);
1642 if (!ri.activityInfo.applicationInfo.packageName
1643 .equals(ai.applicationInfo.packageName)) {
1644 continue;
1645 }
1646 if (!ri.activityInfo.name.equals(ai.name)) {
1647 continue;
1648 }
1649
1650 // Okay we found a previously set preferred app.
1651 // If the result set is different from when this
1652 // was created, we need to clear it and re-ask the
1653 // user their preference.
1654 if (!pa.sameSet(query, priority)) {
1655 Log.i(TAG, "Result set changed, dropping preferred activity for "
1656 + intent + " type " + resolvedType);
1657 mSettings.mPreferredActivities.removeFilter(pa);
1658 return null;
1659 }
1660
1661 // Yay!
1662 return ri;
1663 }
1664 }
1665 }
1666 }
1667 }
1668 return null;
1669 }
1670
1671 public List<ResolveInfo> queryIntentActivities(Intent intent,
1672 String resolvedType, int flags) {
1673 ComponentName comp = intent.getComponent();
1674 if (comp != null) {
1675 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1676 ActivityInfo ai = getActivityInfo(comp, flags);
1677 if (ai != null) {
1678 ResolveInfo ri = new ResolveInfo();
1679 ri.activityInfo = ai;
1680 list.add(ri);
1681 }
1682 return list;
1683 }
1684
1685 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001686 String pkgName = intent.getPackage();
1687 if (pkgName == null) {
1688 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1689 resolvedType, flags);
1690 }
1691 PackageParser.Package pkg = mPackages.get(pkgName);
1692 if (pkg != null) {
1693 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1694 resolvedType, flags, pkg.activities);
1695 }
1696 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 }
1698 }
1699
1700 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1701 Intent[] specifics, String[] specificTypes, Intent intent,
1702 String resolvedType, int flags) {
1703 final String resultsAction = intent.getAction();
1704
1705 List<ResolveInfo> results = queryIntentActivities(
1706 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1707 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1708
1709 int specificsPos = 0;
1710 int N;
1711
1712 // todo: note that the algorithm used here is O(N^2). This
1713 // isn't a problem in our current environment, but if we start running
1714 // into situations where we have more than 5 or 10 matches then this
1715 // should probably be changed to something smarter...
1716
1717 // First we go through and resolve each of the specific items
1718 // that were supplied, taking care of removing any corresponding
1719 // duplicate items in the generic resolve list.
1720 if (specifics != null) {
1721 for (int i=0; i<specifics.length; i++) {
1722 final Intent sintent = specifics[i];
1723 if (sintent == null) {
1724 continue;
1725 }
1726
1727 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1728 String action = sintent.getAction();
1729 if (resultsAction != null && resultsAction.equals(action)) {
1730 // If this action was explicitly requested, then don't
1731 // remove things that have it.
1732 action = null;
1733 }
1734 ComponentName comp = sintent.getComponent();
1735 ResolveInfo ri = null;
1736 ActivityInfo ai = null;
1737 if (comp == null) {
1738 ri = resolveIntent(
1739 sintent,
1740 specificTypes != null ? specificTypes[i] : null,
1741 flags);
1742 if (ri == null) {
1743 continue;
1744 }
1745 if (ri == mResolveInfo) {
1746 // ACK! Must do something better with this.
1747 }
1748 ai = ri.activityInfo;
1749 comp = new ComponentName(ai.applicationInfo.packageName,
1750 ai.name);
1751 } else {
1752 ai = getActivityInfo(comp, flags);
1753 if (ai == null) {
1754 continue;
1755 }
1756 }
1757
1758 // Look for any generic query activities that are duplicates
1759 // of this specific one, and remove them from the results.
1760 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1761 N = results.size();
1762 int j;
1763 for (j=specificsPos; j<N; j++) {
1764 ResolveInfo sri = results.get(j);
1765 if ((sri.activityInfo.name.equals(comp.getClassName())
1766 && sri.activityInfo.applicationInfo.packageName.equals(
1767 comp.getPackageName()))
1768 || (action != null && sri.filter.matchAction(action))) {
1769 results.remove(j);
1770 if (Config.LOGV) Log.v(
1771 TAG, "Removing duplicate item from " + j
1772 + " due to specific " + specificsPos);
1773 if (ri == null) {
1774 ri = sri;
1775 }
1776 j--;
1777 N--;
1778 }
1779 }
1780
1781 // Add this specific item to its proper place.
1782 if (ri == null) {
1783 ri = new ResolveInfo();
1784 ri.activityInfo = ai;
1785 }
1786 results.add(specificsPos, ri);
1787 ri.specificIndex = i;
1788 specificsPos++;
1789 }
1790 }
1791
1792 // Now we go through the remaining generic results and remove any
1793 // duplicate actions that are found here.
1794 N = results.size();
1795 for (int i=specificsPos; i<N-1; i++) {
1796 final ResolveInfo rii = results.get(i);
1797 if (rii.filter == null) {
1798 continue;
1799 }
1800
1801 // Iterate over all of the actions of this result's intent
1802 // filter... typically this should be just one.
1803 final Iterator<String> it = rii.filter.actionsIterator();
1804 if (it == null) {
1805 continue;
1806 }
1807 while (it.hasNext()) {
1808 final String action = it.next();
1809 if (resultsAction != null && resultsAction.equals(action)) {
1810 // If this action was explicitly requested, then don't
1811 // remove things that have it.
1812 continue;
1813 }
1814 for (int j=i+1; j<N; j++) {
1815 final ResolveInfo rij = results.get(j);
1816 if (rij.filter != null && rij.filter.hasAction(action)) {
1817 results.remove(j);
1818 if (Config.LOGV) Log.v(
1819 TAG, "Removing duplicate item from " + j
1820 + " due to action " + action + " at " + i);
1821 j--;
1822 N--;
1823 }
1824 }
1825 }
1826
1827 // If the caller didn't request filter information, drop it now
1828 // so we don't have to marshall/unmarshall it.
1829 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1830 rii.filter = null;
1831 }
1832 }
1833
1834 // Filter out the caller activity if so requested.
1835 if (caller != null) {
1836 N = results.size();
1837 for (int i=0; i<N; i++) {
1838 ActivityInfo ainfo = results.get(i).activityInfo;
1839 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1840 && caller.getClassName().equals(ainfo.name)) {
1841 results.remove(i);
1842 break;
1843 }
1844 }
1845 }
1846
1847 // If the caller didn't request filter information,
1848 // drop them now so we don't have to
1849 // marshall/unmarshall it.
1850 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1851 N = results.size();
1852 for (int i=0; i<N; i++) {
1853 results.get(i).filter = null;
1854 }
1855 }
1856
1857 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1858 return results;
1859 }
1860
1861 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1862 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001863 ComponentName comp = intent.getComponent();
1864 if (comp != null) {
1865 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1866 ActivityInfo ai = getReceiverInfo(comp, flags);
1867 if (ai != null) {
1868 ResolveInfo ri = new ResolveInfo();
1869 ri.activityInfo = ai;
1870 list.add(ri);
1871 }
1872 return list;
1873 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001876 String pkgName = intent.getPackage();
1877 if (pkgName == null) {
1878 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1879 resolvedType, flags);
1880 }
1881 PackageParser.Package pkg = mPackages.get(pkgName);
1882 if (pkg != null) {
1883 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1884 resolvedType, flags, pkg.receivers);
1885 }
1886 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 }
1888 }
1889
1890 public ResolveInfo resolveService(Intent intent, String resolvedType,
1891 int flags) {
1892 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1893 flags);
1894 if (query != null) {
1895 if (query.size() >= 1) {
1896 // If there is more than one service with the same priority,
1897 // just arbitrarily pick the first one.
1898 return query.get(0);
1899 }
1900 }
1901 return null;
1902 }
1903
1904 public List<ResolveInfo> queryIntentServices(Intent intent,
1905 String resolvedType, int flags) {
1906 ComponentName comp = intent.getComponent();
1907 if (comp != null) {
1908 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1909 ServiceInfo si = getServiceInfo(comp, flags);
1910 if (si != null) {
1911 ResolveInfo ri = new ResolveInfo();
1912 ri.serviceInfo = si;
1913 list.add(ri);
1914 }
1915 return list;
1916 }
1917
1918 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001919 String pkgName = intent.getPackage();
1920 if (pkgName == null) {
1921 return (List<ResolveInfo>)mServices.queryIntent(intent,
1922 resolvedType, flags);
1923 }
1924 PackageParser.Package pkg = mPackages.get(pkgName);
1925 if (pkg != null) {
1926 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1927 resolvedType, flags, pkg.services);
1928 }
1929 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 }
1931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 public List<PackageInfo> getInstalledPackages(int flags) {
1934 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1935
1936 synchronized (mPackages) {
1937 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1938 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1939 while (i.hasNext()) {
1940 final PackageSetting ps = i.next();
1941 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1942 if(psPkg != null) {
1943 finalList.add(psPkg);
1944 }
1945 }
1946 }
1947 else {
1948 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1949 while (i.hasNext()) {
1950 final PackageParser.Package p = i.next();
1951 if (p.applicationInfo != null) {
1952 PackageInfo pi = generatePackageInfo(p, flags);
1953 if(pi != null) {
1954 finalList.add(pi);
1955 }
1956 }
1957 }
1958 }
1959 }
1960 return finalList;
1961 }
1962
1963 public List<ApplicationInfo> getInstalledApplications(int flags) {
1964 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1965 synchronized(mPackages) {
1966 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1967 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1968 while (i.hasNext()) {
1969 final PackageSetting ps = i.next();
1970 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1971 if(ai != null) {
1972 finalList.add(ai);
1973 }
1974 }
1975 }
1976 else {
1977 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1978 while (i.hasNext()) {
1979 final PackageParser.Package p = i.next();
1980 if (p.applicationInfo != null) {
1981 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1982 if(ai != null) {
1983 finalList.add(ai);
1984 }
1985 }
1986 }
1987 }
1988 }
1989 return finalList;
1990 }
1991
1992 public List<ApplicationInfo> getPersistentApplications(int flags) {
1993 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1994
1995 synchronized (mPackages) {
1996 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1997 while (i.hasNext()) {
1998 PackageParser.Package p = i.next();
1999 if (p.applicationInfo != null
2000 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2001 && (!mSafeMode || (p.applicationInfo.flags
2002 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2003 finalList.add(p.applicationInfo);
2004 }
2005 }
2006 }
2007
2008 return finalList;
2009 }
2010
2011 public ProviderInfo resolveContentProvider(String name, int flags) {
2012 synchronized (mPackages) {
2013 final PackageParser.Provider provider = mProviders.get(name);
2014 return provider != null
2015 && mSettings.isEnabledLP(provider.info, flags)
2016 && (!mSafeMode || (provider.info.applicationInfo.flags
2017 &ApplicationInfo.FLAG_SYSTEM) != 0)
2018 ? PackageParser.generateProviderInfo(provider, flags)
2019 : null;
2020 }
2021 }
2022
Fred Quintana718d8a22009-04-29 17:53:20 -07002023 /**
2024 * @deprecated
2025 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 public void querySyncProviders(List outNames, List outInfo) {
2027 synchronized (mPackages) {
2028 Iterator<Map.Entry<String, PackageParser.Provider>> i
2029 = mProviders.entrySet().iterator();
2030
2031 while (i.hasNext()) {
2032 Map.Entry<String, PackageParser.Provider> entry = i.next();
2033 PackageParser.Provider p = entry.getValue();
2034
2035 if (p.syncable
2036 && (!mSafeMode || (p.info.applicationInfo.flags
2037 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2038 outNames.add(entry.getKey());
2039 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2040 }
2041 }
2042 }
2043 }
2044
2045 public List<ProviderInfo> queryContentProviders(String processName,
2046 int uid, int flags) {
2047 ArrayList<ProviderInfo> finalList = null;
2048
2049 synchronized (mPackages) {
2050 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2051 while (i.hasNext()) {
2052 PackageParser.Provider p = i.next();
2053 if (p.info.authority != null
2054 && (processName == null ||
2055 (p.info.processName.equals(processName)
2056 && p.info.applicationInfo.uid == uid))
2057 && mSettings.isEnabledLP(p.info, flags)
2058 && (!mSafeMode || (p.info.applicationInfo.flags
2059 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2060 if (finalList == null) {
2061 finalList = new ArrayList<ProviderInfo>(3);
2062 }
2063 finalList.add(PackageParser.generateProviderInfo(p,
2064 flags));
2065 }
2066 }
2067 }
2068
2069 if (finalList != null) {
2070 Collections.sort(finalList, mProviderInitOrderSorter);
2071 }
2072
2073 return finalList;
2074 }
2075
2076 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2077 int flags) {
2078 synchronized (mPackages) {
2079 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2080 return PackageParser.generateInstrumentationInfo(i, flags);
2081 }
2082 }
2083
2084 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2085 int flags) {
2086 ArrayList<InstrumentationInfo> finalList =
2087 new ArrayList<InstrumentationInfo>();
2088
2089 synchronized (mPackages) {
2090 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2091 while (i.hasNext()) {
2092 PackageParser.Instrumentation p = i.next();
2093 if (targetPackage == null
2094 || targetPackage.equals(p.info.targetPackage)) {
2095 finalList.add(PackageParser.generateInstrumentationInfo(p,
2096 flags));
2097 }
2098 }
2099 }
2100
2101 return finalList;
2102 }
2103
2104 private void scanDirLI(File dir, int flags, int scanMode) {
2105 Log.d(TAG, "Scanning app dir " + dir);
2106
2107 String[] files = dir.list();
2108
2109 int i;
2110 for (i=0; i<files.length; i++) {
2111 File file = new File(dir, files[i]);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002112 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002114 // Don't mess around with apps in system partition.
2115 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0) {
2116 // Delete the apk
2117 Log.w(TAG, "Cleaning up failed install of " + file);
2118 file.delete();
2119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
2121 }
2122
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002123 private static File getSettingsProblemFile() {
2124 File dataDir = Environment.getDataDirectory();
2125 File systemDir = new File(dataDir, "system");
2126 File fname = new File(systemDir, "uiderrors.txt");
2127 return fname;
2128 }
2129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 private static void reportSettingsProblem(int priority, String msg) {
2131 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002132 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 FileOutputStream out = new FileOutputStream(fname, true);
2134 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002135 SimpleDateFormat formatter = new SimpleDateFormat();
2136 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2137 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 pw.close();
2139 FileUtils.setPermissions(
2140 fname.toString(),
2141 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2142 -1, -1);
2143 } catch (java.io.IOException e) {
2144 }
2145 Log.println(priority, TAG, msg);
2146 }
2147
2148 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2149 PackageParser.Package pkg, File srcFile, int parseFlags) {
2150 if (GET_CERTIFICATES) {
2151 if (ps == null || !ps.codePath.equals(srcFile)
2152 || ps.getTimeStamp() != srcFile.lastModified()) {
2153 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2154 if (!pp.collectCertificates(pkg, parseFlags)) {
2155 mLastScanError = pp.getParseError();
2156 return false;
2157 }
2158 }
2159 }
2160 return true;
2161 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 /*
2164 * Scan a package and return the newly parsed package.
2165 * Returns null in case of errors and the error code is stored in mLastScanError
2166 */
2167 private PackageParser.Package scanPackageLI(File scanFile,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002168 int parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 int scanMode) {
2170 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002171 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002173 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002176 scanPath,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002177 mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 if (pkg == null) {
2179 mLastScanError = pp.getParseError();
2180 return null;
2181 }
2182 PackageSetting ps;
2183 PackageSetting updatedPkg;
2184 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002185 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
2187 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002188 // Verify certificates first
2189 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2190 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2191 return null;
2192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 if (updatedPkg != null) {
2194 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2195 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2196 }
2197 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2198 // Check for updated system applications here
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002199 if ((ps != null) && (!ps.codePath.equals(scanFile))) {
2200 if (pkg.mVersionCode < ps.versionCode) {
2201 // The system package has been updated and the code path does not match
2202 // Ignore entry. Just return
2203 Log.w(TAG, "Package:" + pkg.packageName +
2204 " has been updated. Ignoring the one from path:"+scanFile);
2205 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2206 return null;
2207 } else {
2208 // Delete the older apk pointed to by ps
2209 // At this point, its safely assumed that package installation for
2210 // apps in system partition will go through. If not there won't be a working
2211 // version of the app
2212 synchronized (mPackages) {
2213 // Just remove the loaded entries from package lists.
2214 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002215 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002216 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2217 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002218 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 }
2221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002222 // The apk is forward locked (not public) if its code and resources
2223 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002224 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002225 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002226 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002227 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002228
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002229 String codePath = null;
2230 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002231 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2232 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002233 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002234 } else {
2235 // Should not happen at all. Just log an error.
2236 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2237 }
2238 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002239 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002240 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002241 codePath = pkg.mScanPath;
2242 // Set application objects path explicitly.
2243 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002245 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 }
2247
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002248 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2249 String destCodePath, String destResPath) {
2250 pkg.mPath = pkg.mScanPath = destCodePath;
2251 pkg.applicationInfo.sourceDir = destCodePath;
2252 pkg.applicationInfo.publicSourceDir = destResPath;
2253 }
2254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 private static String fixProcessName(String defProcessName,
2256 String processName, int uid) {
2257 if (processName == null) {
2258 return defProcessName;
2259 }
2260 return processName;
2261 }
2262
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002263 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2265 if (pkg.mSignatures != null) {
2266 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2267 updateSignature)) {
2268 Log.e(TAG, "Package " + pkg.packageName
2269 + " signatures do not match the previously installed version; ignoring!");
2270 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2271 return false;
2272 }
2273
2274 if (pkgSetting.sharedUser != null) {
2275 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2276 pkg.mSignatures, updateSignature)) {
2277 Log.e(TAG, "Package " + pkg.packageName
2278 + " has no signatures that match those in shared user "
2279 + pkgSetting.sharedUser.name + "; ignoring!");
2280 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2281 return false;
2282 }
2283 }
2284 } else {
2285 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2286 }
2287 return true;
2288 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002289
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002290 public boolean performDexOpt(String packageName) {
2291 if (!mNoDexOpt) {
2292 return false;
2293 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002294
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002295 PackageParser.Package p;
2296 synchronized (mPackages) {
2297 p = mPackages.get(packageName);
2298 if (p == null || p.mDidDexOpt) {
2299 return false;
2300 }
2301 }
2302 synchronized (mInstallLock) {
2303 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2304 }
2305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002306
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002307 static final int DEX_OPT_SKIPPED = 0;
2308 static final int DEX_OPT_PERFORMED = 1;
2309 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002310
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002311 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2312 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002313 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002314 String path = pkg.mScanPath;
2315 int ret = 0;
2316 try {
2317 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002318 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002319 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002320 pkg.mDidDexOpt = true;
2321 performed = true;
2322 }
2323 } catch (FileNotFoundException e) {
2324 Log.w(TAG, "Apk not found for dexopt: " + path);
2325 ret = -1;
2326 } catch (IOException e) {
2327 Log.w(TAG, "Exception reading apk: " + path, e);
2328 ret = -1;
2329 }
2330 if (ret < 0) {
2331 //error from installer
2332 return DEX_OPT_FAILED;
2333 }
2334 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002335
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002336 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2337 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002338
2339 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2340 return Environment.isEncryptedFilesystemEnabled() &&
2341 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2342 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002343
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002344 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2345 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2346 Log.w(TAG, "Unable to update from " + oldPkg.name
2347 + " to " + newPkg.packageName
2348 + ": old package not in system partition");
2349 return false;
2350 } else if (mPackages.get(oldPkg.name) != null) {
2351 Log.w(TAG, "Unable to update from " + oldPkg.name
2352 + " to " + newPkg.packageName
2353 + ": old package still exists");
2354 return false;
2355 }
2356 return true;
2357 }
2358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 private PackageParser.Package scanPackageLI(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 PackageParser.Package pkg, int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002361 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002362 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2363 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002364 // Bail out. The resource and code paths haven't been set.
2365 Log.w(TAG, " Code and resource paths haven't been set correctly");
2366 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2367 return null;
2368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 mScanningPath = scanFile;
2370 if (pkg == null) {
2371 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2372 return null;
2373 }
2374
2375 final String pkgName = pkg.applicationInfo.packageName;
2376 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2377 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2378 }
2379
2380 if (pkgName.equals("android")) {
2381 synchronized (mPackages) {
2382 if (mAndroidApplication != null) {
2383 Log.w(TAG, "*************************************************");
2384 Log.w(TAG, "Core android package being redefined. Skipping.");
2385 Log.w(TAG, " file=" + mScanningPath);
2386 Log.w(TAG, "*************************************************");
2387 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2388 return null;
2389 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 // Set up information for our fall-back user intent resolution
2392 // activity.
2393 mPlatformPackage = pkg;
2394 pkg.mVersionCode = mSdkVersion;
2395 mAndroidApplication = pkg.applicationInfo;
2396 mResolveActivity.applicationInfo = mAndroidApplication;
2397 mResolveActivity.name = ResolverActivity.class.getName();
2398 mResolveActivity.packageName = mAndroidApplication.packageName;
2399 mResolveActivity.processName = mAndroidApplication.processName;
2400 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2401 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2402 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2403 mResolveActivity.exported = true;
2404 mResolveActivity.enabled = true;
2405 mResolveInfo.activityInfo = mResolveActivity;
2406 mResolveInfo.priority = 0;
2407 mResolveInfo.preferredOrder = 0;
2408 mResolveInfo.match = 0;
2409 mResolveComponentName = new ComponentName(
2410 mAndroidApplication.packageName, mResolveActivity.name);
2411 }
2412 }
2413
2414 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2415 TAG, "Scanning package " + pkgName);
2416 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2417 Log.w(TAG, "*************************************************");
2418 Log.w(TAG, "Application package " + pkgName
2419 + " already installed. Skipping duplicate.");
2420 Log.w(TAG, "*************************************************");
2421 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2422 return null;
2423 }
2424
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002425 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002426 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2427 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 SharedUserSetting suid = null;
2430 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 synchronized (mPackages) {
2435 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002436 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2437 if (mTmpSharedLibraries == null ||
2438 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2439 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2440 }
2441 int num = 0;
2442 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2443 for (int i=0; i<N; i++) {
2444 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 if (file == null) {
2446 Log.e(TAG, "Package " + pkg.packageName
2447 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002448 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2450 return null;
2451 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002452 mTmpSharedLibraries[num] = file;
2453 num++;
2454 }
2455 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2456 for (int i=0; i<N; i++) {
2457 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2458 if (file == null) {
2459 Log.w(TAG, "Package " + pkg.packageName
2460 + " desires unavailable shared library "
2461 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2462 } else {
2463 mTmpSharedLibraries[num] = file;
2464 num++;
2465 }
2466 }
2467 if (num > 0) {
2468 pkg.usesLibraryFiles = new String[num];
2469 System.arraycopy(mTmpSharedLibraries, 0,
2470 pkg.usesLibraryFiles, 0, num);
2471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002472
Dianne Hackborn49237342009-08-27 20:08:01 -07002473 if (pkg.reqFeatures != null) {
2474 N = pkg.reqFeatures.size();
2475 for (int i=0; i<N; i++) {
2476 FeatureInfo fi = pkg.reqFeatures.get(i);
2477 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2478 // Don't care.
2479 continue;
2480 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002481
Dianne Hackborn49237342009-08-27 20:08:01 -07002482 if (fi.name != null) {
2483 if (mAvailableFeatures.get(fi.name) == null) {
2484 Log.e(TAG, "Package " + pkg.packageName
2485 + " requires unavailable feature "
2486 + fi.name + "; failing!");
2487 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2488 return null;
2489 }
2490 }
2491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 }
2493 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 if (pkg.mSharedUserId != null) {
2496 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2497 pkg.applicationInfo.flags, true);
2498 if (suid == null) {
2499 Log.w(TAG, "Creating application package " + pkgName
2500 + " for shared user failed");
2501 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2502 return null;
2503 }
2504 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2505 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2506 + suid.userId + "): packages=" + suid.packages);
2507 }
2508 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002509
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002510 // Check if we are renaming from an original package name.
2511 PackageSetting origPackage = null;
2512 if (pkg.mOriginalPackage != null) {
2513 // We will only retrieve the setting for it if it already
2514 // exists; otherwise we need to make a new one later.
2515 origPackage = mSettings.peekPackageLP(pkg.mOriginalPackage);
2516 if (origPackage != null) {
2517 if (!verifyPackageUpdate(origPackage, pkg)) {
2518 origPackage = null;
2519 } else if (origPackage.sharedUser != null) {
2520 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2521 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2522 + " to " + pkg.packageName + ": old uid "
2523 + origPackage.sharedUser.name
2524 + " differs from " + pkg.mSharedUserId);
2525 origPackage = null;
2526 }
2527 } else {
2528 if (DEBUG_UPGRADE) Log.v(TAG, "Migrating data from "
2529 + origPackage.name + " to " + pkg.packageName);
2530 }
2531 }
2532 }
2533
2534 if (mTransferedPackages.contains(pkg.packageName)) {
2535 Log.w(TAG, "Package " + pkg.packageName
2536 + " was transferred to another, but its .apk remains");
2537 }
2538
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002539 // Just create the setting, don't add it yet. For already existing packages
2540 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002541 pkgSetting = mSettings.getPackageLP(pkg, origPackage, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 destResourceFile, pkg.applicationInfo.flags, true, false);
2543 if (pkgSetting == null) {
2544 Log.w(TAG, "Creating application package " + pkgName + " failed");
2545 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2546 return null;
2547 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002548 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2550 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 pkg.applicationInfo.uid = pkgSetting.userId;
2553 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002554
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002555 if (pkg.mAdoptPermissions != null) {
2556 // This package wants to adopt ownership of permissions from
2557 // another package.
2558 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2559 String origName = pkg.mAdoptPermissions.get(i);
2560 PackageSetting orig = mSettings.peekPackageLP(origName);
2561 if (orig != null) {
2562 if (verifyPackageUpdate(orig, pkg)) {
2563 if (DEBUG_UPGRADE) Log.v(TAG, "Adopting permissions from "
2564 + origName + " to " + pkg.packageName);
2565 mSettings.transferPermissions(origName, pkg.packageName);
2566 }
2567 }
2568 }
2569 }
2570
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002571 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2573 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2574 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2575 return null;
2576 }
2577 // The signature has changed, but this package is in the system
2578 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002579 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 // However... if this package is part of a shared user, but it
2581 // doesn't match the signature of the shared user, let's fail.
2582 // What this means is that you can't change the signatures
2583 // associated with an overall shared user, which doesn't seem all
2584 // that unreasonable.
2585 if (pkgSetting.sharedUser != null) {
2586 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2587 pkg.mSignatures, false)) {
2588 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2589 return null;
2590 }
2591 }
2592 removeExisting = true;
2593 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002594
The Android Open Source Project10592532009-03-18 17:39:46 -07002595 // Verify that this new package doesn't have any content providers
2596 // that conflict with existing packages. Only do this if the
2597 // package isn't already installed, since we don't want to break
2598 // things that are installed.
2599 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2600 int N = pkg.providers.size();
2601 int i;
2602 for (i=0; i<N; i++) {
2603 PackageParser.Provider p = pkg.providers.get(i);
2604 String names[] = p.info.authority.split(";");
2605 for (int j = 0; j < names.length; j++) {
2606 if (mProviders.containsKey(names[j])) {
2607 PackageParser.Provider other = mProviders.get(names[j]);
2608 Log.w(TAG, "Can't install because provider name " + names[j] +
2609 " (in package " + pkg.applicationInfo.packageName +
2610 ") is already used by "
2611 + ((other != null && other.component != null)
2612 ? other.component.getPackageName() : "?"));
2613 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2614 return null;
2615 }
2616 }
2617 }
2618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 }
2620
2621 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002622 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002624 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 if (ret != 0) {
2626 String msg = "System package " + pkg.packageName
2627 + " could not have data directory erased after signature change.";
2628 reportSettingsProblem(Log.WARN, msg);
2629 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2630 return null;
2631 }
2632 }
2633 Log.w(TAG, "System package " + pkg.packageName
2634 + " signature changed: existing data removed.");
2635 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2636 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 long scanFileTime = scanFile.lastModified();
2639 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2640 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2641 pkg.applicationInfo.processName = fixProcessName(
2642 pkg.applicationInfo.packageName,
2643 pkg.applicationInfo.processName,
2644 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645
2646 File dataPath;
2647 if (mPlatformPackage == pkg) {
2648 // The system package is special.
2649 dataPath = new File (Environment.getDataDirectory(), "system");
2650 pkg.applicationInfo.dataDir = dataPath.getPath();
2651 } else {
2652 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002653 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2654 if (useEncryptedFSDir) {
2655 dataPath = new File(mSecureAppDataDir, pkgName);
2656 } else {
2657 dataPath = new File(mAppDataDir, pkgName);
2658 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002659
2660 boolean uidError = false;
2661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 if (dataPath.exists()) {
2663 mOutPermissions[1] = 0;
2664 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2665 if (mOutPermissions[1] == pkg.applicationInfo.uid
2666 || !Process.supportsProcesses()) {
2667 pkg.applicationInfo.dataDir = dataPath.getPath();
2668 } else {
2669 boolean recovered = false;
2670 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2671 // If this is a system app, we can at least delete its
2672 // current data so the application will still work.
2673 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002674 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002675 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 // Old data gone!
2677 String msg = "System package " + pkg.packageName
2678 + " has changed from uid: "
2679 + mOutPermissions[1] + " to "
2680 + pkg.applicationInfo.uid + "; old data erased";
2681 reportSettingsProblem(Log.WARN, msg);
2682 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002685 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 pkg.applicationInfo.uid);
2687 if (ret == -1) {
2688 // Ack should not happen!
2689 msg = "System package " + pkg.packageName
2690 + " could not have data directory re-created after delete.";
2691 reportSettingsProblem(Log.WARN, msg);
2692 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2693 return null;
2694 }
2695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 if (!recovered) {
2698 mHasSystemUidErrors = true;
2699 }
2700 }
2701 if (!recovered) {
2702 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2703 + pkg.applicationInfo.uid + "/fs_"
2704 + mOutPermissions[1];
2705 String msg = "Package " + pkg.packageName
2706 + " has mismatched uid: "
2707 + mOutPermissions[1] + " on disk, "
2708 + pkg.applicationInfo.uid + " in settings";
2709 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002710 mSettings.mReadMessages.append(msg);
2711 mSettings.mReadMessages.append('\n');
2712 uidError = true;
2713 if (!pkgSetting.uidError) {
2714 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717 }
2718 }
2719 pkg.applicationInfo.dataDir = dataPath.getPath();
2720 } else {
2721 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2722 Log.v(TAG, "Want this data dir: " + dataPath);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002723 if (pkgSetting.origPackage != null) {
2724 synchronized (mPackages) {
2725 // This package is being update from another; rename the
2726 // old one's data dir.
2727 String msg = "Transfering data from old package "
2728 + pkgSetting.origPackage.name + " to new package "
2729 + pkgSetting.name;
2730 reportSettingsProblem(Log.WARN, msg);
2731 if (mInstaller != null) {
2732 int ret = mInstaller.rename(pkgSetting.origPackage.name,
2733 pkgName, useEncryptedFSDir);
2734 if(ret < 0) {
2735 msg = "Error transfering data from old package "
2736 + pkgSetting.origPackage.name + " to new package "
2737 + pkgSetting.name;
2738 reportSettingsProblem(Log.WARN, msg);
2739 }
2740 }
2741 // And now uninstall the old package.
2742 mInstaller.remove(pkgSetting.origPackage.name, useEncryptedFSDir);
2743 mSettings.removePackageLP(pkgSetting.origPackage.name);
2744 }
2745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 //invoke installer to do the actual installation
2747 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002748 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 pkg.applicationInfo.uid);
2750 if(ret < 0) {
2751 // Error from installer
2752 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2753 return null;
2754 }
2755 } else {
2756 dataPath.mkdirs();
2757 if (dataPath.exists()) {
2758 FileUtils.setPermissions(
2759 dataPath.toString(),
2760 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2761 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2762 }
2763 }
2764 if (dataPath.exists()) {
2765 pkg.applicationInfo.dataDir = dataPath.getPath();
2766 } else {
2767 Log.w(TAG, "Unable to create data directory: " + dataPath);
2768 pkg.applicationInfo.dataDir = null;
2769 }
2770 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002771
2772 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 }
2774
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002775 // No longer need to retain this.
2776 if (pkgSetting.origPackage != null) {
2777 mTransferedPackages.add(pkgSetting.origPackage.name);
2778 pkgSetting.origPackage = null;
2779 }
2780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 // Perform shared library installation and dex validation and
2782 // optimization, if this is not a system app.
2783 if (mInstaller != null) {
2784 String path = scanFile.getPath();
2785 if (scanFileNewer) {
2786 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002787 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2788 if (err != PackageManager.INSTALL_SUCCEEDED) {
2789 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 return null;
2791 }
2792 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002793 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002794
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002795 if ((scanMode&SCAN_NO_DEX) == 0) {
2796 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2798 return null;
2799 }
2800 }
2801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 if (mFactoryTest && pkg.requestedPermissions.contains(
2804 android.Manifest.permission.FACTORY_TEST)) {
2805 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2806 }
2807
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002808 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 if ((scanMode&SCAN_MONITOR) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 mAppDirs.put(pkg.mPath, pkg);
2811 }
2812
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002813 // Request the ActivityManager to kill the process(only for existing packages)
2814 // so that we do not end up in a confused state while the user is still using the older
2815 // version of the application while the new one gets installed.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002816 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0) {
2817 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002818 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002819 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002823 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002825 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 int N = pkg.providers.size();
2827 StringBuilder r = null;
2828 int i;
2829 for (i=0; i<N; i++) {
2830 PackageParser.Provider p = pkg.providers.get(i);
2831 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2832 p.info.processName, pkg.applicationInfo.uid);
2833 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2834 p.info.name), p);
2835 p.syncable = p.info.isSyncable;
2836 String names[] = p.info.authority.split(";");
2837 p.info.authority = null;
2838 for (int j = 0; j < names.length; j++) {
2839 if (j == 1 && p.syncable) {
2840 // We only want the first authority for a provider to possibly be
2841 // syncable, so if we already added this provider using a different
2842 // authority clear the syncable flag. We copy the provider before
2843 // changing it because the mProviders object contains a reference
2844 // to a provider that we don't want to change.
2845 // Only do this for the second authority since the resulting provider
2846 // object can be the same for all future authorities for this provider.
2847 p = new PackageParser.Provider(p);
2848 p.syncable = false;
2849 }
2850 if (!mProviders.containsKey(names[j])) {
2851 mProviders.put(names[j], p);
2852 if (p.info.authority == null) {
2853 p.info.authority = names[j];
2854 } else {
2855 p.info.authority = p.info.authority + ";" + names[j];
2856 }
2857 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2858 Log.d(TAG, "Registered content provider: " + names[j] +
2859 ", className = " + p.info.name +
2860 ", isSyncable = " + p.info.isSyncable);
2861 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002862 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 Log.w(TAG, "Skipping provider name " + names[j] +
2864 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002865 "): name already used by "
2866 + ((other != null && other.component != null)
2867 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 }
2869 }
2870 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2871 if (r == null) {
2872 r = new StringBuilder(256);
2873 } else {
2874 r.append(' ');
2875 }
2876 r.append(p.info.name);
2877 }
2878 }
2879 if (r != null) {
2880 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2881 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 N = pkg.services.size();
2884 r = null;
2885 for (i=0; i<N; i++) {
2886 PackageParser.Service s = pkg.services.get(i);
2887 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2888 s.info.processName, pkg.applicationInfo.uid);
2889 mServices.addService(s);
2890 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2891 if (r == null) {
2892 r = new StringBuilder(256);
2893 } else {
2894 r.append(' ');
2895 }
2896 r.append(s.info.name);
2897 }
2898 }
2899 if (r != null) {
2900 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2901 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 N = pkg.receivers.size();
2904 r = null;
2905 for (i=0; i<N; i++) {
2906 PackageParser.Activity a = pkg.receivers.get(i);
2907 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2908 a.info.processName, pkg.applicationInfo.uid);
2909 mReceivers.addActivity(a, "receiver");
2910 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2911 if (r == null) {
2912 r = new StringBuilder(256);
2913 } else {
2914 r.append(' ');
2915 }
2916 r.append(a.info.name);
2917 }
2918 }
2919 if (r != null) {
2920 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 N = pkg.activities.size();
2924 r = null;
2925 for (i=0; i<N; i++) {
2926 PackageParser.Activity a = pkg.activities.get(i);
2927 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2928 a.info.processName, pkg.applicationInfo.uid);
2929 mActivities.addActivity(a, "activity");
2930 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2931 if (r == null) {
2932 r = new StringBuilder(256);
2933 } else {
2934 r.append(' ');
2935 }
2936 r.append(a.info.name);
2937 }
2938 }
2939 if (r != null) {
2940 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 N = pkg.permissionGroups.size();
2944 r = null;
2945 for (i=0; i<N; i++) {
2946 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2947 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2948 if (cur == null) {
2949 mPermissionGroups.put(pg.info.name, pg);
2950 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2951 if (r == null) {
2952 r = new StringBuilder(256);
2953 } else {
2954 r.append(' ');
2955 }
2956 r.append(pg.info.name);
2957 }
2958 } else {
2959 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2960 + pg.info.packageName + " ignored: original from "
2961 + cur.info.packageName);
2962 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2963 if (r == null) {
2964 r = new StringBuilder(256);
2965 } else {
2966 r.append(' ');
2967 }
2968 r.append("DUP:");
2969 r.append(pg.info.name);
2970 }
2971 }
2972 }
2973 if (r != null) {
2974 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2975 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 N = pkg.permissions.size();
2978 r = null;
2979 for (i=0; i<N; i++) {
2980 PackageParser.Permission p = pkg.permissions.get(i);
2981 HashMap<String, BasePermission> permissionMap =
2982 p.tree ? mSettings.mPermissionTrees
2983 : mSettings.mPermissions;
2984 p.group = mPermissionGroups.get(p.info.group);
2985 if (p.info.group == null || p.group != null) {
2986 BasePermission bp = permissionMap.get(p.info.name);
2987 if (bp == null) {
2988 bp = new BasePermission(p.info.name, p.info.packageName,
2989 BasePermission.TYPE_NORMAL);
2990 permissionMap.put(p.info.name, bp);
2991 }
2992 if (bp.perm == null) {
2993 if (bp.sourcePackage == null
2994 || bp.sourcePackage.equals(p.info.packageName)) {
2995 BasePermission tree = findPermissionTreeLP(p.info.name);
2996 if (tree == null
2997 || tree.sourcePackage.equals(p.info.packageName)) {
2998 bp.perm = p;
2999 bp.uid = pkg.applicationInfo.uid;
3000 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3001 if (r == null) {
3002 r = new StringBuilder(256);
3003 } else {
3004 r.append(' ');
3005 }
3006 r.append(p.info.name);
3007 }
3008 } else {
3009 Log.w(TAG, "Permission " + p.info.name + " from package "
3010 + p.info.packageName + " ignored: base tree "
3011 + tree.name + " is from package "
3012 + tree.sourcePackage);
3013 }
3014 } else {
3015 Log.w(TAG, "Permission " + p.info.name + " from package "
3016 + p.info.packageName + " ignored: original from "
3017 + bp.sourcePackage);
3018 }
3019 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3020 if (r == null) {
3021 r = new StringBuilder(256);
3022 } else {
3023 r.append(' ');
3024 }
3025 r.append("DUP:");
3026 r.append(p.info.name);
3027 }
3028 } else {
3029 Log.w(TAG, "Permission " + p.info.name + " from package "
3030 + p.info.packageName + " ignored: no group "
3031 + p.group);
3032 }
3033 }
3034 if (r != null) {
3035 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3036 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 N = pkg.instrumentation.size();
3039 r = null;
3040 for (i=0; i<N; i++) {
3041 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3042 a.info.packageName = pkg.applicationInfo.packageName;
3043 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3044 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3045 a.info.dataDir = pkg.applicationInfo.dataDir;
3046 mInstrumentation.put(a.component, a);
3047 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3048 if (r == null) {
3049 r = new StringBuilder(256);
3050 } else {
3051 r.append(' ');
3052 }
3053 r.append(a.info.name);
3054 }
3055 }
3056 if (r != null) {
3057 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3058 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003059
Dianne Hackborn854060af2009-07-09 18:14:31 -07003060 if (pkg.protectedBroadcasts != null) {
3061 N = pkg.protectedBroadcasts.size();
3062 for (i=0; i<N; i++) {
3063 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3064 }
3065 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 pkgSetting.setTimeStamp(scanFileTime);
3068 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 return pkg;
3071 }
3072
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003073 private void killApplication(String pkgName, int uid) {
3074 // Request the ActivityManager to kill the process(only for existing packages)
3075 // so that we do not end up in a confused state while the user is still using the older
3076 // version of the application while the new one gets installed.
3077 IActivityManager am = ActivityManagerNative.getDefault();
3078 if (am != null) {
3079 try {
3080 am.killApplicationWithUid(pkgName, uid);
3081 } catch (RemoteException e) {
3082 }
3083 }
3084 }
3085
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003086 // The following constants are returned by cachePackageSharedLibsForAbiLI
3087 // to indicate if native shared libraries were found in the package.
3088 // Values are:
3089 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3090 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3091 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3092 // in package (and not installed)
3093 //
3094 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3095 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3096 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003098 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3099 // and automatically copy them to /data/data/<appname>/lib if present.
3100 //
3101 // NOTE: this method may throw an IOException if the library cannot
3102 // be copied to its final destination, e.g. if there isn't enough
3103 // room left on the data partition, or a ZipException if the package
3104 // file is malformed.
3105 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003106 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3107 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003108 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3109 final String apkLib = "lib/";
3110 final int apkLibLen = apkLib.length();
3111 final int cpuAbiLen = cpuAbi.length();
3112 final String libPrefix = "lib";
3113 final int libPrefixLen = libPrefix.length();
3114 final String libSuffix = ".so";
3115 final int libSuffixLen = libSuffix.length();
3116 boolean hasNativeLibraries = false;
3117 boolean installedNativeLibraries = false;
3118
3119 // the minimum length of a valid native shared library of the form
3120 // lib/<something>/lib<name>.so.
3121 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3122
3123 ZipFile zipFile = new ZipFile(scanFile);
3124 Enumeration<ZipEntry> entries =
3125 (Enumeration<ZipEntry>) zipFile.entries();
3126
3127 while (entries.hasMoreElements()) {
3128 ZipEntry entry = entries.nextElement();
3129 // skip directories
3130 if (entry.isDirectory()) {
3131 continue;
3132 }
3133 String entryName = entry.getName();
3134
3135 // check that the entry looks like lib/<something>/lib<name>.so
3136 // here, but don't check the ABI just yet.
3137 //
3138 // - must be sufficiently long
3139 // - must end with libSuffix, i.e. ".so"
3140 // - must start with apkLib, i.e. "lib/"
3141 if (entryName.length() < minEntryLen ||
3142 !entryName.endsWith(libSuffix) ||
3143 !entryName.startsWith(apkLib) ) {
3144 continue;
3145 }
3146
3147 // file name must start with libPrefix, i.e. "lib"
3148 int lastSlash = entryName.lastIndexOf('/');
3149
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003150 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003151 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3152 continue;
3153 }
3154
3155 hasNativeLibraries = true;
3156
3157 // check the cpuAbi now, between lib/ and /lib<name>.so
3158 //
3159 if (lastSlash != apkLibLen + cpuAbiLen ||
3160 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3161 continue;
3162
3163 // extract the library file name, ensure it doesn't contain
3164 // weird characters. we're guaranteed here that it doesn't contain
3165 // a directory separator though.
3166 String libFileName = entryName.substring(lastSlash+1);
3167 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3168 continue;
3169 }
3170
3171 installedNativeLibraries = true;
3172
3173 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3174 File.separator + libFileName;
3175 File sharedLibraryFile = new File(sharedLibraryFilePath);
3176 if (! sharedLibraryFile.exists() ||
3177 sharedLibraryFile.length() != entry.getSize() ||
3178 sharedLibraryFile.lastModified() != entry.getTime()) {
3179 if (Config.LOGD) {
3180 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003182 if (mInstaller == null) {
3183 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003184 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003185 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003186 sharedLibraryFile);
3187 }
3188 }
3189 if (!hasNativeLibraries)
3190 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3191
3192 if (!installedNativeLibraries)
3193 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3194
3195 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3196 }
3197
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003198 // Find the gdbserver executable program in a package at
3199 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3200 //
3201 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3202 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3203 //
3204 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3205 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3206 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3207 final String GDBSERVER = "gdbserver";
3208 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3209
3210 ZipFile zipFile = new ZipFile(scanFile);
3211 Enumeration<ZipEntry> entries =
3212 (Enumeration<ZipEntry>) zipFile.entries();
3213
3214 while (entries.hasMoreElements()) {
3215 ZipEntry entry = entries.nextElement();
3216 // skip directories
3217 if (entry.isDirectory()) {
3218 continue;
3219 }
3220 String entryName = entry.getName();
3221
3222 if (!entryName.equals(apkGdbServerPath)) {
3223 continue;
3224 }
3225
3226 String installGdbServerPath = installGdbServerDir.getPath() +
3227 "/" + GDBSERVER;
3228 File installGdbServerFile = new File(installGdbServerPath);
3229 if (! installGdbServerFile.exists() ||
3230 installGdbServerFile.length() != entry.getSize() ||
3231 installGdbServerFile.lastModified() != entry.getTime()) {
3232 if (Config.LOGD) {
3233 Log.d(TAG, "Caching gdbserver " + entry.getName());
3234 }
3235 if (mInstaller == null) {
3236 installGdbServerDir.mkdir();
3237 }
3238 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3239 installGdbServerFile);
3240 }
3241 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3242 }
3243 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3244 }
3245
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003246 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3247 // and copy them to /data/data/<appname>/lib.
3248 //
3249 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3250 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3251 // one if ro.product.cpu.abi2 is defined.
3252 //
3253 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3254 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003255 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003256 try {
3257 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3258
3259 // some architectures are capable of supporting several CPU ABIs
3260 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3261 // this is indicated by the definition of the ro.product.cpu.abi2
3262 // system property.
3263 //
3264 // only scan the package twice in case of ABI mismatch
3265 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003266 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003267 if (cpuAbi2 != null) {
3268 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003270
3271 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3272 Log.w(TAG,"Native ABI mismatch from package file");
3273 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003275
3276 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3277 cpuAbi = cpuAbi2;
3278 }
3279 }
3280
3281 // for debuggable packages, also extract gdbserver from lib/<abi>
3282 // into /data/data/<appname>/lib too.
3283 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3284 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3285 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3286 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3287 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003290 } catch (ZipException e) {
3291 Log.w(TAG, "Failed to extract data from package file", e);
3292 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003294 Log.w(TAG, "Failed to cache package shared libs", e);
3295 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003297 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 }
3299
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003300 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003302 File binaryDir,
3303 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 InputStream inputStream = zipFile.getInputStream(entry);
3305 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003306 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003308 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 // now need to be left as world readable and owned by the system.
3310 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3311 ! tempFile.setLastModified(entry.getTime()) ||
3312 FileUtils.setPermissions(tempFilePath,
3313 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003314 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003316 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 // Failed to properly write file.
3318 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003319 throw new IOException("Couldn't create cached binary "
3320 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 }
3322 } finally {
3323 inputStream.close();
3324 }
3325 }
3326
3327 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3328 if (chatty && Config.LOGD) Log.d(
3329 TAG, "Removing package " + pkg.applicationInfo.packageName );
3330
3331 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 mPackages.remove(pkg.applicationInfo.packageName);
3335 if (pkg.mPath != null) {
3336 mAppDirs.remove(pkg.mPath);
3337 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 PackageSetting ps = (PackageSetting)pkg.mExtras;
3340 if (ps != null && ps.sharedUser != null) {
3341 // XXX don't do this until the data is removed.
3342 if (false) {
3343 ps.sharedUser.packages.remove(ps);
3344 if (ps.sharedUser.packages.size() == 0) {
3345 // Remove.
3346 }
3347 }
3348 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 int N = pkg.providers.size();
3351 StringBuilder r = null;
3352 int i;
3353 for (i=0; i<N; i++) {
3354 PackageParser.Provider p = pkg.providers.get(i);
3355 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3356 p.info.name));
3357 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 /* The is another ContentProvider with this authority when
3360 * this app was installed so this authority is null,
3361 * Ignore it as we don't have to unregister the provider.
3362 */
3363 continue;
3364 }
3365 String names[] = p.info.authority.split(";");
3366 for (int j = 0; j < names.length; j++) {
3367 if (mProviders.get(names[j]) == p) {
3368 mProviders.remove(names[j]);
3369 if (chatty && Config.LOGD) Log.d(
3370 TAG, "Unregistered content provider: " + names[j] +
3371 ", className = " + p.info.name +
3372 ", isSyncable = " + p.info.isSyncable);
3373 }
3374 }
3375 if (chatty) {
3376 if (r == null) {
3377 r = new StringBuilder(256);
3378 } else {
3379 r.append(' ');
3380 }
3381 r.append(p.info.name);
3382 }
3383 }
3384 if (r != null) {
3385 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3386 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 N = pkg.services.size();
3389 r = null;
3390 for (i=0; i<N; i++) {
3391 PackageParser.Service s = pkg.services.get(i);
3392 mServices.removeService(s);
3393 if (chatty) {
3394 if (r == null) {
3395 r = new StringBuilder(256);
3396 } else {
3397 r.append(' ');
3398 }
3399 r.append(s.info.name);
3400 }
3401 }
3402 if (r != null) {
3403 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3404 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 N = pkg.receivers.size();
3407 r = null;
3408 for (i=0; i<N; i++) {
3409 PackageParser.Activity a = pkg.receivers.get(i);
3410 mReceivers.removeActivity(a, "receiver");
3411 if (chatty) {
3412 if (r == null) {
3413 r = new StringBuilder(256);
3414 } else {
3415 r.append(' ');
3416 }
3417 r.append(a.info.name);
3418 }
3419 }
3420 if (r != null) {
3421 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3422 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 N = pkg.activities.size();
3425 r = null;
3426 for (i=0; i<N; i++) {
3427 PackageParser.Activity a = pkg.activities.get(i);
3428 mActivities.removeActivity(a, "activity");
3429 if (chatty) {
3430 if (r == null) {
3431 r = new StringBuilder(256);
3432 } else {
3433 r.append(' ');
3434 }
3435 r.append(a.info.name);
3436 }
3437 }
3438 if (r != null) {
3439 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 N = pkg.permissions.size();
3443 r = null;
3444 for (i=0; i<N; i++) {
3445 PackageParser.Permission p = pkg.permissions.get(i);
3446 boolean tree = false;
3447 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3448 if (bp == null) {
3449 tree = true;
3450 bp = mSettings.mPermissionTrees.get(p.info.name);
3451 }
3452 if (bp != null && bp.perm == p) {
3453 if (bp.type != BasePermission.TYPE_BUILTIN) {
3454 if (tree) {
3455 mSettings.mPermissionTrees.remove(p.info.name);
3456 } else {
3457 mSettings.mPermissions.remove(p.info.name);
3458 }
3459 } else {
3460 bp.perm = null;
3461 }
3462 if (chatty) {
3463 if (r == null) {
3464 r = new StringBuilder(256);
3465 } else {
3466 r.append(' ');
3467 }
3468 r.append(p.info.name);
3469 }
3470 }
3471 }
3472 if (r != null) {
3473 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3474 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 N = pkg.instrumentation.size();
3477 r = null;
3478 for (i=0; i<N; i++) {
3479 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3480 mInstrumentation.remove(a.component);
3481 if (chatty) {
3482 if (r == null) {
3483 r = new StringBuilder(256);
3484 } else {
3485 r.append(' ');
3486 }
3487 r.append(a.info.name);
3488 }
3489 }
3490 if (r != null) {
3491 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3492 }
3493 }
3494 }
3495
3496 private static final boolean isPackageFilename(String name) {
3497 return name != null && name.endsWith(".apk");
3498 }
3499
3500 private void updatePermissionsLP() {
3501 // Make sure there are no dangling permission trees.
3502 Iterator<BasePermission> it = mSettings.mPermissionTrees
3503 .values().iterator();
3504 while (it.hasNext()) {
3505 BasePermission bp = it.next();
3506 if (bp.perm == null) {
3507 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3508 + " from package " + bp.sourcePackage);
3509 it.remove();
3510 }
3511 }
3512
3513 // Make sure all dynamic permissions have been assigned to a package,
3514 // and make sure there are no dangling permissions.
3515 it = mSettings.mPermissions.values().iterator();
3516 while (it.hasNext()) {
3517 BasePermission bp = it.next();
3518 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3519 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3520 + bp.name + " pkg=" + bp.sourcePackage
3521 + " info=" + bp.pendingInfo);
3522 if (bp.perm == null && bp.pendingInfo != null) {
3523 BasePermission tree = findPermissionTreeLP(bp.name);
3524 if (tree != null) {
3525 bp.perm = new PackageParser.Permission(tree.perm.owner,
3526 new PermissionInfo(bp.pendingInfo));
3527 bp.perm.info.packageName = tree.perm.info.packageName;
3528 bp.perm.info.name = bp.name;
3529 bp.uid = tree.uid;
3530 }
3531 }
3532 }
3533 if (bp.perm == null) {
3534 Log.w(TAG, "Removing dangling permission: " + bp.name
3535 + " from package " + bp.sourcePackage);
3536 it.remove();
3537 }
3538 }
3539
3540 // Now update the permissions for all packages, in particular
3541 // replace the granted permissions of the system packages.
3542 for (PackageParser.Package pkg : mPackages.values()) {
3543 grantPermissionsLP(pkg, false);
3544 }
3545 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3548 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3549 if (ps == null) {
3550 return;
3551 }
3552 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3553 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555 if (replace) {
3556 ps.permissionsFixed = false;
3557 if (gp == ps) {
3558 gp.grantedPermissions.clear();
3559 gp.gids = mGlobalGids;
3560 }
3561 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 if (gp.gids == null) {
3564 gp.gids = mGlobalGids;
3565 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 final int N = pkg.requestedPermissions.size();
3568 for (int i=0; i<N; i++) {
3569 String name = pkg.requestedPermissions.get(i);
3570 BasePermission bp = mSettings.mPermissions.get(name);
3571 PackageParser.Permission p = bp != null ? bp.perm : null;
3572 if (false) {
3573 if (gp != ps) {
3574 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3575 + ": " + p);
3576 }
3577 }
3578 if (p != null) {
3579 final String perm = p.info.name;
3580 boolean allowed;
3581 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3582 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3583 allowed = true;
3584 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3585 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003586 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003588 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 == PackageManager.SIGNATURE_MATCH);
3590 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3591 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3592 // For updated system applications, the signatureOrSystem permission
3593 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003594 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3596 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3597 if(sysPs.grantedPermissions.contains(perm)) {
3598 allowed = true;
3599 } else {
3600 allowed = false;
3601 }
3602 } else {
3603 allowed = true;
3604 }
3605 }
3606 }
3607 } else {
3608 allowed = false;
3609 }
3610 if (false) {
3611 if (gp != ps) {
3612 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3613 }
3614 }
3615 if (allowed) {
3616 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3617 && ps.permissionsFixed) {
3618 // If this is an existing, non-system package, then
3619 // we can't add any new permissions to it.
3620 if (!gp.loadedPermissions.contains(perm)) {
3621 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003622 // Except... if this is a permission that was added
3623 // to the platform (note: need to only do this when
3624 // updating the platform).
3625 final int NP = PackageParser.NEW_PERMISSIONS.length;
3626 for (int ip=0; ip<NP; ip++) {
3627 final PackageParser.NewPermissionInfo npi
3628 = PackageParser.NEW_PERMISSIONS[ip];
3629 if (npi.name.equals(perm)
3630 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3631 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003632 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003633 + pkg.packageName);
3634 break;
3635 }
3636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 }
3638 }
3639 if (allowed) {
3640 if (!gp.grantedPermissions.contains(perm)) {
3641 addedPermission = true;
3642 gp.grantedPermissions.add(perm);
3643 gp.gids = appendInts(gp.gids, bp.gids);
3644 }
3645 } else {
3646 Log.w(TAG, "Not granting permission " + perm
3647 + " to package " + pkg.packageName
3648 + " because it was previously installed without");
3649 }
3650 } else {
3651 Log.w(TAG, "Not granting permission " + perm
3652 + " to package " + pkg.packageName
3653 + " (protectionLevel=" + p.info.protectionLevel
3654 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3655 + ")");
3656 }
3657 } else {
3658 Log.w(TAG, "Unknown permission " + name
3659 + " in package " + pkg.packageName);
3660 }
3661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003664 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3665 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 // This is the first that we have heard about this package, so the
3667 // permissions we have now selected are fixed until explicitly
3668 // changed.
3669 ps.permissionsFixed = true;
3670 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3671 }
3672 }
3673
3674 private final class ActivityIntentResolver
3675 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003676 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003678 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 }
3680
Mihai Preda074edef2009-05-18 17:13:31 +02003681 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003682 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003683 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3685 }
3686
Mihai Predaeae850c2009-05-13 10:13:48 +02003687 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3688 ArrayList<PackageParser.Activity> packageActivities) {
3689 if (packageActivities == null) {
3690 return null;
3691 }
3692 mFlags = flags;
3693 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3694 int N = packageActivities.size();
3695 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3696 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003697
3698 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003699 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003700 intentFilters = packageActivities.get(i).intents;
3701 if (intentFilters != null && intentFilters.size() > 0) {
3702 listCut.add(intentFilters);
3703 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003704 }
3705 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3706 }
3707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 public final void addActivity(PackageParser.Activity a, String type) {
3709 mActivities.put(a.component, a);
3710 if (SHOW_INFO || Config.LOGV) Log.v(
3711 TAG, " " + type + " " +
3712 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3713 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3714 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003715 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3717 if (SHOW_INFO || Config.LOGV) {
3718 Log.v(TAG, " IntentFilter:");
3719 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3720 }
3721 if (!intent.debugCheck()) {
3722 Log.w(TAG, "==> For Activity " + a.info.name);
3723 }
3724 addFilter(intent);
3725 }
3726 }
3727
3728 public final void removeActivity(PackageParser.Activity a, String type) {
3729 mActivities.remove(a.component);
3730 if (SHOW_INFO || Config.LOGV) Log.v(
3731 TAG, " " + type + " " +
3732 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3733 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3734 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003735 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3737 if (SHOW_INFO || Config.LOGV) {
3738 Log.v(TAG, " IntentFilter:");
3739 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3740 }
3741 removeFilter(intent);
3742 }
3743 }
3744
3745 @Override
3746 protected boolean allowFilterResult(
3747 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3748 ActivityInfo filterAi = filter.activity.info;
3749 for (int i=dest.size()-1; i>=0; i--) {
3750 ActivityInfo destAi = dest.get(i).activityInfo;
3751 if (destAi.name == filterAi.name
3752 && destAi.packageName == filterAi.packageName) {
3753 return false;
3754 }
3755 }
3756 return true;
3757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 @Override
3760 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3761 int match) {
3762 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3763 return null;
3764 }
3765 final PackageParser.Activity activity = info.activity;
3766 if (mSafeMode && (activity.info.applicationInfo.flags
3767 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3768 return null;
3769 }
3770 final ResolveInfo res = new ResolveInfo();
3771 res.activityInfo = PackageParser.generateActivityInfo(activity,
3772 mFlags);
3773 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3774 res.filter = info;
3775 }
3776 res.priority = info.getPriority();
3777 res.preferredOrder = activity.owner.mPreferredOrder;
3778 //System.out.println("Result: " + res.activityInfo.className +
3779 // " = " + res.priority);
3780 res.match = match;
3781 res.isDefault = info.hasDefault;
3782 res.labelRes = info.labelRes;
3783 res.nonLocalizedLabel = info.nonLocalizedLabel;
3784 res.icon = info.icon;
3785 return res;
3786 }
3787
3788 @Override
3789 protected void sortResults(List<ResolveInfo> results) {
3790 Collections.sort(results, mResolvePrioritySorter);
3791 }
3792
3793 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003794 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003796 out.print(prefix); out.print(
3797 Integer.toHexString(System.identityHashCode(filter.activity)));
3798 out.print(' ');
3799 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 }
3801
3802// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3803// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3804// final List<ResolveInfo> retList = Lists.newArrayList();
3805// while (i.hasNext()) {
3806// final ResolveInfo resolveInfo = i.next();
3807// if (isEnabledLP(resolveInfo.activityInfo)) {
3808// retList.add(resolveInfo);
3809// }
3810// }
3811// return retList;
3812// }
3813
3814 // Keys are String (activity class name), values are Activity.
3815 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3816 = new HashMap<ComponentName, PackageParser.Activity>();
3817 private int mFlags;
3818 }
3819
3820 private final class ServiceIntentResolver
3821 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003822 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003824 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 }
3826
Mihai Preda074edef2009-05-18 17:13:31 +02003827 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003829 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003830 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3831 }
3832
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003833 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3834 ArrayList<PackageParser.Service> packageServices) {
3835 if (packageServices == null) {
3836 return null;
3837 }
3838 mFlags = flags;
3839 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3840 int N = packageServices.size();
3841 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3842 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3843
3844 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3845 for (int i = 0; i < N; ++i) {
3846 intentFilters = packageServices.get(i).intents;
3847 if (intentFilters != null && intentFilters.size() > 0) {
3848 listCut.add(intentFilters);
3849 }
3850 }
3851 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3852 }
3853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 public final void addService(PackageParser.Service s) {
3855 mServices.put(s.component, s);
3856 if (SHOW_INFO || Config.LOGV) Log.v(
3857 TAG, " " + (s.info.nonLocalizedLabel != null
3858 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3859 if (SHOW_INFO || Config.LOGV) Log.v(
3860 TAG, " Class=" + s.info.name);
3861 int NI = s.intents.size();
3862 int j;
3863 for (j=0; j<NI; j++) {
3864 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3865 if (SHOW_INFO || Config.LOGV) {
3866 Log.v(TAG, " IntentFilter:");
3867 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3868 }
3869 if (!intent.debugCheck()) {
3870 Log.w(TAG, "==> For Service " + s.info.name);
3871 }
3872 addFilter(intent);
3873 }
3874 }
3875
3876 public final void removeService(PackageParser.Service s) {
3877 mServices.remove(s.component);
3878 if (SHOW_INFO || Config.LOGV) Log.v(
3879 TAG, " " + (s.info.nonLocalizedLabel != null
3880 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3881 if (SHOW_INFO || Config.LOGV) Log.v(
3882 TAG, " Class=" + s.info.name);
3883 int NI = s.intents.size();
3884 int j;
3885 for (j=0; j<NI; j++) {
3886 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3887 if (SHOW_INFO || Config.LOGV) {
3888 Log.v(TAG, " IntentFilter:");
3889 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3890 }
3891 removeFilter(intent);
3892 }
3893 }
3894
3895 @Override
3896 protected boolean allowFilterResult(
3897 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3898 ServiceInfo filterSi = filter.service.info;
3899 for (int i=dest.size()-1; i>=0; i--) {
3900 ServiceInfo destAi = dest.get(i).serviceInfo;
3901 if (destAi.name == filterSi.name
3902 && destAi.packageName == filterSi.packageName) {
3903 return false;
3904 }
3905 }
3906 return true;
3907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 @Override
3910 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3911 int match) {
3912 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3913 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3914 return null;
3915 }
3916 final PackageParser.Service service = info.service;
3917 if (mSafeMode && (service.info.applicationInfo.flags
3918 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3919 return null;
3920 }
3921 final ResolveInfo res = new ResolveInfo();
3922 res.serviceInfo = PackageParser.generateServiceInfo(service,
3923 mFlags);
3924 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3925 res.filter = filter;
3926 }
3927 res.priority = info.getPriority();
3928 res.preferredOrder = service.owner.mPreferredOrder;
3929 //System.out.println("Result: " + res.activityInfo.className +
3930 // " = " + res.priority);
3931 res.match = match;
3932 res.isDefault = info.hasDefault;
3933 res.labelRes = info.labelRes;
3934 res.nonLocalizedLabel = info.nonLocalizedLabel;
3935 res.icon = info.icon;
3936 return res;
3937 }
3938
3939 @Override
3940 protected void sortResults(List<ResolveInfo> results) {
3941 Collections.sort(results, mResolvePrioritySorter);
3942 }
3943
3944 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003945 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003947 out.print(prefix); out.print(
3948 Integer.toHexString(System.identityHashCode(filter.service)));
3949 out.print(' ');
3950 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003951 }
3952
3953// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3954// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3955// final List<ResolveInfo> retList = Lists.newArrayList();
3956// while (i.hasNext()) {
3957// final ResolveInfo resolveInfo = (ResolveInfo) i;
3958// if (isEnabledLP(resolveInfo.serviceInfo)) {
3959// retList.add(resolveInfo);
3960// }
3961// }
3962// return retList;
3963// }
3964
3965 // Keys are String (activity class name), values are Activity.
3966 private final HashMap<ComponentName, PackageParser.Service> mServices
3967 = new HashMap<ComponentName, PackageParser.Service>();
3968 private int mFlags;
3969 };
3970
3971 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3972 new Comparator<ResolveInfo>() {
3973 public int compare(ResolveInfo r1, ResolveInfo r2) {
3974 int v1 = r1.priority;
3975 int v2 = r2.priority;
3976 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3977 if (v1 != v2) {
3978 return (v1 > v2) ? -1 : 1;
3979 }
3980 v1 = r1.preferredOrder;
3981 v2 = r2.preferredOrder;
3982 if (v1 != v2) {
3983 return (v1 > v2) ? -1 : 1;
3984 }
3985 if (r1.isDefault != r2.isDefault) {
3986 return r1.isDefault ? -1 : 1;
3987 }
3988 v1 = r1.match;
3989 v2 = r2.match;
3990 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3991 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3992 }
3993 };
3994
3995 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3996 new Comparator<ProviderInfo>() {
3997 public int compare(ProviderInfo p1, ProviderInfo p2) {
3998 final int v1 = p1.initOrder;
3999 final int v2 = p2.initOrder;
4000 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4001 }
4002 };
4003
4004 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4005 IActivityManager am = ActivityManagerNative.getDefault();
4006 if (am != null) {
4007 try {
4008 final Intent intent = new Intent(action,
4009 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4010 if (extras != null) {
4011 intent.putExtras(extras);
4012 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004013 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 am.broadcastIntent(
4015 null, intent,
4016 null, null, 0, null, null, null, false, false);
4017 } catch (RemoteException ex) {
4018 }
4019 }
4020 }
4021
4022 private final class AppDirObserver extends FileObserver {
4023 public AppDirObserver(String path, int mask, boolean isrom) {
4024 super(path, mask);
4025 mRootDir = path;
4026 mIsRom = isrom;
4027 }
4028
4029 public void onEvent(int event, String path) {
4030 String removedPackage = null;
4031 int removedUid = -1;
4032 String addedPackage = null;
4033 int addedUid = -1;
4034
4035 synchronized (mInstallLock) {
4036 String fullPathStr = null;
4037 File fullPath = null;
4038 if (path != null) {
4039 fullPath = new File(mRootDir, path);
4040 fullPathStr = fullPath.getPath();
4041 }
4042
4043 if (Config.LOGV) Log.v(
4044 TAG, "File " + fullPathStr + " changed: "
4045 + Integer.toHexString(event));
4046
4047 if (!isPackageFilename(path)) {
4048 if (Config.LOGV) Log.v(
4049 TAG, "Ignoring change of non-package file: " + fullPathStr);
4050 return;
4051 }
4052
4053 if ((event&REMOVE_EVENTS) != 0) {
4054 synchronized (mInstallLock) {
4055 PackageParser.Package p = mAppDirs.get(fullPathStr);
4056 if (p != null) {
4057 removePackageLI(p, true);
4058 removedPackage = p.applicationInfo.packageName;
4059 removedUid = p.applicationInfo.uid;
4060 }
4061 }
4062 }
4063
4064 if ((event&ADD_EVENTS) != 0) {
4065 PackageParser.Package p = mAppDirs.get(fullPathStr);
4066 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004067 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4069 PackageParser.PARSE_CHATTY |
4070 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004071 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 if (p != null) {
4073 synchronized (mPackages) {
4074 grantPermissionsLP(p, false);
4075 }
4076 addedPackage = p.applicationInfo.packageName;
4077 addedUid = p.applicationInfo.uid;
4078 }
4079 }
4080 }
4081
4082 synchronized (mPackages) {
4083 mSettings.writeLP();
4084 }
4085 }
4086
4087 if (removedPackage != null) {
4088 Bundle extras = new Bundle(1);
4089 extras.putInt(Intent.EXTRA_UID, removedUid);
4090 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4091 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4092 }
4093 if (addedPackage != null) {
4094 Bundle extras = new Bundle(1);
4095 extras.putInt(Intent.EXTRA_UID, addedUid);
4096 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4097 }
4098 }
4099
4100 private final String mRootDir;
4101 private final boolean mIsRom;
4102 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 /* Called when a downloaded package installation has been confirmed by the user */
4105 public void installPackage(
4106 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004107 installPackage(packageURI, observer, flags, null);
4108 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004109
Jacek Surazski65e13172009-04-28 15:26:38 +02004110 /* Called when a downloaded package installation has been confirmed by the user */
4111 public void installPackage(
4112 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4113 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 mContext.enforceCallingOrSelfPermission(
4115 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004116
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004117 Message msg = mHandler.obtainMessage(INIT_COPY);
4118 msg.obj = createInstallArgs(packageURI, observer, flags, installerPackageName);
4119 mHandler.sendMessage(msg);
4120 }
4121
4122 private InstallArgs createInstallArgs(Uri packageURI, IPackageInstallObserver observer,
4123 int flags, String installerPackageName) {
4124 if (installOnSd(flags)) {
4125 return new SdInstallArgs(packageURI, observer, flags,
4126 installerPackageName);
4127 } else {
4128 return new FileInstallArgs(packageURI, observer, flags,
4129 installerPackageName);
4130 }
4131 }
4132
4133 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4134 if (installOnSd(flags)) {
4135 return new SdInstallArgs(fullCodePath, fullResourcePath);
4136 } else {
4137 return new FileInstallArgs(fullCodePath, fullResourcePath);
4138 }
4139 }
4140
4141 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 // Queue up an async operation since the package installation may take a little while.
4143 mHandler.post(new Runnable() {
4144 public void run() {
4145 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004146 // Result object to be returned
4147 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004148 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004149 res.uid = -1;
4150 res.pkg = null;
4151 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004152 args.doPreInstall(res.returnCode);
4153 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004154 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004155 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004156 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004157 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004158 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004159 if (args.observer != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004161 args.observer.packageInstalled(res.name, res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 } catch (RemoteException e) {
4163 Log.i(TAG, "Observer no longer exists.");
4164 }
4165 }
4166 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
4167 // call appears in the synchronized block above.
4168 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4169 res.removedInfo.sendBroadcast(false, true);
4170 Bundle extras = new Bundle(1);
4171 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004172 final boolean update = res.removedInfo.removedPackage != null;
4173 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4175 }
4176 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
4177 res.pkg.applicationInfo.packageName,
4178 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004179 if (update) {
4180 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
4181 res.pkg.applicationInfo.packageName,
4182 extras);
4183 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004184 if (res.removedInfo.args != null) {
4185 // Remove the replaced package's older resources safely now
4186 synchronized (mInstallLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004187 res.removedInfo.args.doPostDeleteLI(true);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004188 }
4189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 }
4191 Runtime.getRuntime().gc();
4192 }
4193 });
4194 }
4195
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004196 static abstract class InstallArgs {
4197 final IPackageInstallObserver observer;
4198 final int flags;
4199 final Uri packageURI;
4200 final String installerPackageName;
4201
4202 InstallArgs(Uri packageURI,
4203 IPackageInstallObserver observer, int flags,
4204 String installerPackageName) {
4205 this.packageURI = packageURI;
4206 this.flags = flags;
4207 this.observer = observer;
4208 this.installerPackageName = installerPackageName;
4209 }
4210
4211 abstract void createCopyFile();
4212 abstract int copyApk(IMediaContainerService imcs);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004213 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004214 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004215 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004216 abstract String getCodePath();
4217 abstract String getResourcePath();
4218 // Need installer lock especially for dex file removal.
4219 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004220 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004221 }
4222
4223 class FileInstallArgs extends InstallArgs {
4224 File installDir;
4225 String codeFileName;
4226 String resourceFileName;
4227
4228 FileInstallArgs(Uri packageURI,
4229 IPackageInstallObserver observer, int flags,
4230 String installerPackageName) {
4231 super(packageURI, observer, flags, installerPackageName);
4232 }
4233
4234 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4235 super(null, null, 0, null);
4236 File codeFile = new File(fullCodePath);
4237 installDir = codeFile.getParentFile();
4238 codeFileName = fullCodePath;
4239 resourceFileName = fullResourcePath;
4240 }
4241
4242 void createCopyFile() {
4243 boolean fwdLocked = isFwdLocked(flags);
4244 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4245 codeFileName = createTempPackageFile(installDir).getPath();
4246 resourceFileName = getResourcePathFromCodePath();
4247 }
4248
4249 String getCodePath() {
4250 return codeFileName;
4251 }
4252
4253 int copyApk(IMediaContainerService imcs) {
4254 // Get a ParcelFileDescriptor to write to the output file
4255 File codeFile = new File(codeFileName);
4256 ParcelFileDescriptor out = null;
4257 try {
4258 out = ParcelFileDescriptor.open(codeFile,
4259 ParcelFileDescriptor.MODE_READ_WRITE);
4260 } catch (FileNotFoundException e) {
4261 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4262 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4263 }
4264 // Copy the resource now
4265 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4266 try {
4267 if (imcs.copyResource(packageURI, out)) {
4268 ret = PackageManager.INSTALL_SUCCEEDED;
4269 }
4270 } catch (RemoteException e) {
4271 } finally {
4272 try { if (out != null) out.close(); } catch (IOException e) {}
4273 }
4274 return ret;
4275 }
4276
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004277 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004278 if (status != PackageManager.INSTALL_SUCCEEDED) {
4279 cleanUp();
4280 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004281 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004282 }
4283
4284 boolean doRename(int status, final String pkgName, String oldCodePath) {
4285 if (status != PackageManager.INSTALL_SUCCEEDED) {
4286 cleanUp();
4287 return false;
4288 } else {
4289 // Rename based on packageName
4290 File codeFile = new File(getCodePath());
4291 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4292 File desFile = new File(installDir, apkName + ".apk");
4293 if (!codeFile.renameTo(desFile)) {
4294 return false;
4295 }
4296 // Reset paths since the file has been renamed.
4297 codeFileName = desFile.getPath();
4298 resourceFileName = getResourcePathFromCodePath();
4299 // Set permissions
4300 if (!setPermissions(pkgName)) {
4301 // Failed setting permissions.
4302 return false;
4303 }
4304 return true;
4305 }
4306 }
4307
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004308 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004309 if (status != PackageManager.INSTALL_SUCCEEDED) {
4310 cleanUp();
4311 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004312 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004313 }
4314
4315 String getResourcePath() {
4316 return resourceFileName;
4317 }
4318
4319 String getResourcePathFromCodePath() {
4320 String codePath = getCodePath();
4321 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4322 String apkNameOnly = getApkName(codePath);
4323 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4324 } else {
4325 return codePath;
4326 }
4327 }
4328
4329 private boolean cleanUp() {
4330 boolean ret = true;
4331 String sourceDir = getCodePath();
4332 String publicSourceDir = getResourcePath();
4333 if (sourceDir != null) {
4334 File sourceFile = new File(sourceDir);
4335 if (!sourceFile.exists()) {
4336 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4337 ret = false;
4338 }
4339 // Delete application's code and resources
4340 sourceFile.delete();
4341 }
4342 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4343 final File publicSourceFile = new File(publicSourceDir);
4344 if (!publicSourceFile.exists()) {
4345 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4346 }
4347 if (publicSourceFile.exists()) {
4348 publicSourceFile.delete();
4349 }
4350 }
4351 return ret;
4352 }
4353
4354 void cleanUpResourcesLI() {
4355 String sourceDir = getCodePath();
4356 if (cleanUp() && mInstaller != null) {
4357 int retCode = mInstaller.rmdex(sourceDir);
4358 if (retCode < 0) {
4359 Log.w(TAG, "Couldn't remove dex file for package: "
4360 + " at location "
4361 + sourceDir + ", retcode=" + retCode);
4362 // we don't consider this to be a failure of the core package deletion
4363 }
4364 }
4365 }
4366
4367 private boolean setPermissions(String pkgName) {
4368 // TODO Do this in a more elegant way later on. for now just a hack
4369 if (!isFwdLocked(flags)) {
4370 final int filePermissions =
4371 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4372 |FileUtils.S_IROTH;
4373 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4374 if (retCode != 0) {
4375 Log.e(TAG, "Couldn't set new package file permissions for " +
4376 getCodePath()
4377 + ". The return code was: " + retCode);
4378 // TODO Define new internal error
4379 return false;
4380 }
4381 return true;
4382 }
4383 return true;
4384 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004385
4386 boolean doPostDeleteLI(boolean delete) {
4387 cleanUpResourcesLI();
4388 return true;
4389 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004390 }
4391
4392 class SdInstallArgs extends InstallArgs {
4393 String cid;
4394 String cachePath;
4395 static final String RES_FILE_NAME = "pkg.apk";
4396
4397 SdInstallArgs(Uri packageURI,
4398 IPackageInstallObserver observer, int flags,
4399 String installerPackageName) {
4400 super(packageURI, observer, flags, installerPackageName);
4401 }
4402
4403 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004404 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004405 // Extract cid from fullCodePath
4406 int eidx = fullCodePath.lastIndexOf("/");
4407 String subStr1 = fullCodePath.substring(0, eidx);
4408 int sidx = subStr1.lastIndexOf("/");
4409 cid = subStr1.substring(sidx+1, eidx);
4410 cachePath = subStr1;
4411 }
4412
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004413 SdInstallArgs(String cid) {
4414 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
4415 this.cid = cid;
4416 }
4417
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004418 void createCopyFile() {
4419 cid = getTempContainerId();
4420 }
4421
4422 int copyApk(IMediaContainerService imcs) {
4423 try {
4424 cachePath = imcs.copyResourceToContainer(
4425 packageURI, cid,
4426 getEncryptKey(), RES_FILE_NAME);
4427 } catch (RemoteException e) {
4428 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004429 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4430 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004431 }
4432
4433 @Override
4434 String getCodePath() {
4435 return cachePath + "/" + RES_FILE_NAME;
4436 }
4437
4438 @Override
4439 String getResourcePath() {
4440 return cachePath + "/" + RES_FILE_NAME;
4441 }
4442
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004443 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004444 if (status != PackageManager.INSTALL_SUCCEEDED) {
4445 // Destroy container
4446 destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004447 } else {
4448 // STOPSHIP Remove once new api is added in MountService
4449 //boolean mounted = isContainerMounted(cid);
4450 boolean mounted = false;
4451 if (!mounted) {
4452 cachePath = mountSdDir(cid, Process.SYSTEM_UID);
4453 if (cachePath == null) {
4454 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4455 }
4456 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004457 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004458 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004459 }
4460
4461 boolean doRename(int status, final String pkgName,
4462 String oldCodePath) {
4463 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004464 String newCachePath = null;
4465 /*final int RENAME_FAILED = 1;
4466 final int MOUNT_FAILED = 2;
4467 final int DESTROY_FAILED = 3;
4468 final int PASS = 4;
4469 int errCode = RENAME_FAILED;
4470 if (mounted) {
4471 // Unmount the container
4472 if (!unMountSdDir(cid)) {
4473 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
4474 return false;
4475 }
4476 mounted = false;
4477 }
4478 if (renameSdDir(cid, newCacheId)) {
4479 errCode = MOUNT_FAILED;
4480 if ((newCachePath = mountSdDir(newCacheId, Process.SYSTEM_UID)) != null) {
4481 errCode = PASS;
4482 }
4483 }
4484 String errMsg = "";
4485 switch (errCode) {
4486 case RENAME_FAILED:
4487 errMsg = "RENAME_FAILED";
4488 break;
4489 case MOUNT_FAILED:
4490 errMsg = "MOUNT_FAILED";
4491 break;
4492 case DESTROY_FAILED:
4493 errMsg = "DESTROY_FAILED";
4494 break;
4495 default:
4496 errMsg = "PASS";
4497 break;
4498 }
4499 Log.i(TAG, "Status: " + errMsg);
4500 if (errCode != PASS) {
4501 return false;
4502 }
4503 Log.i(TAG, "Succesfully renamed " + cid + " to " +newCacheId +
4504 " at path: " + cachePath + " to new path: " + newCachePath);
4505 cid = newCacheId;
4506 cachePath = newCachePath;
4507 return true;
4508 */
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004509 // STOPSHIP TEMPORARY HACK FOR RENAME
4510 // Create new container at newCachePath
4511 String codePath = getCodePath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004512 final int CREATE_FAILED = 1;
4513 final int COPY_FAILED = 3;
4514 final int FINALIZE_FAILED = 5;
4515 final int PASS = 7;
4516 int errCode = CREATE_FAILED;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004517
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004518 if ((newCachePath = createSdDir(new File(codePath), newCacheId)) != null) {
4519 errCode = COPY_FAILED;
4520 // Copy file from codePath
4521 if (FileUtils.copyFile(new File(codePath), new File(newCachePath, RES_FILE_NAME))) {
4522 errCode = FINALIZE_FAILED;
4523 if (finalizeSdDir(newCacheId)) {
4524 errCode = PASS;
4525 }
4526 }
4527 }
4528 // Print error based on errCode
4529 String errMsg = "";
4530 switch (errCode) {
4531 case CREATE_FAILED:
4532 errMsg = "CREATE_FAILED";
4533 break;
4534 case COPY_FAILED:
4535 errMsg = "COPY_FAILED";
4536 destroySdDir(newCacheId);
4537 break;
4538 case FINALIZE_FAILED:
4539 errMsg = "FINALIZE_FAILED";
4540 destroySdDir(newCacheId);
4541 break;
4542 default:
4543 errMsg = "PASS";
4544 break;
4545 }
4546 // Destroy the temporary container
4547 destroySdDir(cid);
4548 Log.i(TAG, "Status: " + errMsg);
4549 if (errCode != PASS) {
4550 return false;
4551 }
4552 cid = newCacheId;
4553 cachePath = newCachePath;
4554
4555 return true;
4556 }
4557
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004558 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004559 if (status != PackageManager.INSTALL_SUCCEEDED) {
4560 cleanUp();
4561 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004562 // STOP SHIP Change this once new api is added.
4563 //boolean mounted = isContainerMounted(cid);
4564 boolean mounted = false;
4565 if (!mounted) {
4566 mountSdDir(cid, Process.SYSTEM_UID);
4567 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004568 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004569 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004570 }
4571
4572 private void cleanUp() {
4573 // Destroy secure container
4574 destroySdDir(cid);
4575 }
4576
4577 void cleanUpResourcesLI() {
4578 String sourceFile = getCodePath();
4579 // Remove dex file
4580 if (mInstaller != null) {
4581 int retCode = mInstaller.rmdex(sourceFile.toString());
4582 if (retCode < 0) {
4583 Log.w(TAG, "Couldn't remove dex file for package: "
4584 + " at location "
4585 + sourceFile.toString() + ", retcode=" + retCode);
4586 // we don't consider this to be a failure of the core package deletion
4587 }
4588 }
4589 cleanUp();
4590 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004591
4592 boolean matchContainer(String app) {
4593 if (cid.startsWith(app)) {
4594 return true;
4595 }
4596 return false;
4597 }
4598
4599 String getPackageName() {
4600 int idx = cid.lastIndexOf("-");
4601 if (idx == -1) {
4602 return cid;
4603 }
4604 return cid.substring(0, idx);
4605 }
4606
4607 boolean doPostDeleteLI(boolean delete) {
4608 boolean ret = false;
4609 boolean mounted = isContainerMounted(cid);
4610 if (mounted) {
4611 // Unmount first
4612 ret = unMountSdDir(cid);
4613 }
4614 if (ret && delete) {
4615 cleanUpResourcesLI();
4616 }
4617 return ret;
4618 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004619 };
4620
4621 // Utility method used to create code paths based on package name and available index.
4622 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4623 String idxStr = "";
4624 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004625 // Fall back to default value of idx=1 if prefix is not
4626 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004627 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004628 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004629 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004630 if (subStr.endsWith(suffix)) {
4631 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004632 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004633 // If oldCodePath already contains prefix find out the
4634 // ending index to either increment or decrement.
4635 int sidx = subStr.lastIndexOf(prefix);
4636 if (sidx != -1) {
4637 subStr = subStr.substring(sidx + prefix.length());
4638 if (subStr != null) {
4639 if (subStr.startsWith("-")) {
4640 subStr = subStr.substring(1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004641 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004642 try {
4643 idx = Integer.parseInt(subStr);
4644 if (idx <= 1) {
4645 idx++;
4646 } else {
4647 idx--;
4648 }
4649 } catch(NumberFormatException e) {
4650 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004651 }
4652 }
4653 }
4654 idxStr = "-" + Integer.toString(idx);
4655 return prefix + idxStr;
4656 }
4657
4658 // Utility method that returns the relative package path with respect
4659 // to the installation directory. Like say for /data/data/com.test-1.apk
4660 // string com.test-1 is returned.
4661 static String getApkName(String codePath) {
4662 if (codePath == null) {
4663 return null;
4664 }
4665 int sidx = codePath.lastIndexOf("/");
4666 int eidx = codePath.lastIndexOf(".");
4667 if (eidx == -1) {
4668 eidx = codePath.length();
4669 } else if (eidx == 0) {
4670 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
4671 return null;
4672 }
4673 return codePath.substring(sidx+1, eidx);
4674 }
4675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676 class PackageInstalledInfo {
4677 String name;
4678 int uid;
4679 PackageParser.Package pkg;
4680 int returnCode;
4681 PackageRemovedInfo removedInfo;
4682 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 /*
4685 * Install a non-existing package.
4686 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004687 private void installNewPackageLI(PackageParser.Package pkg,
4688 int parseFlags,
4689 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004690 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004691 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08004692 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004693 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08004694
4695 if (useEncryptedFilesystemForPackage(pkg)) {
4696 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
4697 } else {
4698 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
4699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 res.name = pkgName;
4701 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004702 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004704 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 + " without first uninstalling.");
4706 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4707 return;
4708 }
4709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004710 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004711 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004712 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004713 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004714 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4715 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4716 }
4717 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004718 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004719 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004720 res);
4721 // delete the partially installed application. the data directory will have to be
4722 // restored if it was already existing
4723 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4724 // remove package from internal structures. Note that we want deletePackageX to
4725 // delete the package data and cache directories that it created in
4726 // scanPackageLocked, unless those directories existed before we even tried to
4727 // install.
4728 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004729 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004730 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
4731 res.removedInfo);
4732 }
4733 }
4734 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004735
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004736 private void replacePackageLI(PackageParser.Package pkg,
4737 int parseFlags,
4738 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004739 String installerPackageName, PackageInstalledInfo res) {
4740
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004741 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004742 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004743 // First find the old package info and check signatures
4744 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004745 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004746 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
4747 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4749 return;
4750 }
4751 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004752 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753 if(sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004754 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004755 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004756 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004757 }
4758 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004761 PackageParser.Package pkg,
4762 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004763 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004764 PackageParser.Package newPackage = null;
4765 String pkgName = deletedPackage.packageName;
4766 boolean deletedPkg = true;
4767 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004768
Jacek Surazski65e13172009-04-28 15:26:38 +02004769 String oldInstallerPackageName = null;
4770 synchronized (mPackages) {
4771 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
4772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004773
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004774 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004775 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004776 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004777 res.removedInfo)) {
4778 // If the existing package was'nt successfully deleted
4779 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4780 deletedPkg = false;
4781 } else {
4782 // Successfully deleted the old package. Now proceed with re-installation
4783 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004784 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004785 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004786 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004787 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4788 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08004789 }
4790 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004791 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004792 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004793 res);
4794 updatedSettings = true;
4795 }
4796 }
4797
4798 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4799 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004800 // were keeping around in case we needed them (see below) can now be deleted.
4801 // This info will be set on the res.removedInfo to clean up later on as post
4802 // install action.
4803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004804 //update signature on the new package setting
4805 //this should always succeed, since we checked the
4806 //signature earlier.
4807 synchronized(mPackages) {
4808 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
4809 parseFlags, true);
4810 }
4811 } else {
4812 // remove package from internal structures. Note that we want deletePackageX to
4813 // delete the package data and cache directories that it created in
4814 // scanPackageLocked, unless those directories existed before we even tried to
4815 // install.
4816 if(updatedSettings) {
4817 deletePackageLI(
4818 pkgName, true,
4819 PackageManager.DONT_DELETE_DATA,
4820 res.removedInfo);
4821 }
4822 // Since we failed to install the new package we need to restore the old
4823 // package that we deleted.
4824 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004825 File restoreFile = new File(deletedPackage.mPath);
4826 if (restoreFile == null) {
4827 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
4828 return;
4829 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004830 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4831 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004832 // Parse old package
4833 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
4834 scanPackageLI(restoreFile, parseFlags, scanMode);
4835 synchronized (mPackages) {
4836 grantPermissionsLP(deletedPackage, false);
4837 mSettings.writeLP();
4838 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004839 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4840 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004842 }
4843 }
4844 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004846 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004847 PackageParser.Package pkg,
4848 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004849 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004850 PackageParser.Package newPackage = null;
4851 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004852 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004853 PackageParser.PARSE_IS_SYSTEM;
4854 String packageName = deletedPackage.packageName;
4855 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4856 if (packageName == null) {
4857 Log.w(TAG, "Attempt to delete null packageName.");
4858 return;
4859 }
4860 PackageParser.Package oldPkg;
4861 PackageSetting oldPkgSetting;
4862 synchronized (mPackages) {
4863 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004864 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004865 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
4866 (oldPkgSetting == null)) {
4867 Log.w(TAG, "Could'nt find package:"+packageName+" information");
4868 return;
4869 }
4870 }
4871 res.removedInfo.uid = oldPkg.applicationInfo.uid;
4872 res.removedInfo.removedPackage = packageName;
4873 // Remove existing system package
4874 removePackageLI(oldPkg, true);
4875 synchronized (mPackages) {
4876 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
4877 }
4878
4879 // Successfully disabled the old package. Now proceed with re-installation
4880 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4881 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004882 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004884 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004885 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4886 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4887 }
4888 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004889 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 updatedSettings = true;
4891 }
4892
4893 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4894 //update signature on the new package setting
4895 //this should always succeed, since we checked the
4896 //signature earlier.
4897 synchronized(mPackages) {
4898 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
4899 parseFlags, true);
4900 }
4901 } else {
4902 // Re installation failed. Restore old information
4903 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07004904 if (newPackage != null) {
4905 removePackageLI(newPackage, true);
4906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004907 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004908 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004909 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07004910 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004911 // Restore the old system information in Settings
4912 synchronized(mPackages) {
4913 if(updatedSettings) {
4914 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004915 mSettings.setInstallerPackageName(packageName,
4916 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004917 }
4918 mSettings.writeLP();
4919 }
4920 }
4921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004922
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004923 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004924 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004925 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004926 synchronized (mPackages) {
4927 //write settings. the installStatus will be incomplete at this stage.
4928 //note that the new package setting would have already been
4929 //added to mPackages. It hasn't been persisted yet.
4930 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4931 mSettings.writeLP();
4932 }
4933
4934 int retCode = 0;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004935 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4936 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004937 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004938 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4940 return;
4941 }
4942 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004943 res.returnCode = setPermissionsLI(newPackage);
4944 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4945 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004946 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004947 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004948 }
4949 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4950 if (mInstaller != null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004951 mInstaller.rmdex(newPackage.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 }
4953 }
4954
4955 synchronized (mPackages) {
4956 grantPermissionsLP(newPackage, true);
4957 res.name = pkgName;
4958 res.uid = newPackage.applicationInfo.uid;
4959 res.pkg = newPackage;
4960 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02004961 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4963 //to update install status
4964 mSettings.writeLP();
4965 }
4966 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004967
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004968 private void installPackageLI(InstallArgs args,
4969 boolean newInstall, PackageInstalledInfo res) {
4970 int pFlags = args.flags;
4971 String installerPackageName = args.installerPackageName;
4972 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004973 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
4974 boolean onSd = ((pFlags & PackageManager.INSTALL_ON_SDCARD) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08004975 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004976 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
4977 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004978 // Result object to be returned
4979 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4980
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08004981 // Retrieve PackageSettings and parse package
4982 int parseFlags = PackageParser.PARSE_CHATTY |
4983 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
4984 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
4985 parseFlags |= mDefParseFlags;
4986 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4987 pp.setSeparateProcesses(mSeparateProcesses);
4988 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
4989 null, mMetrics, parseFlags);
4990 if (pkg == null) {
4991 res.returnCode = pp.getParseError();
4992 return;
4993 }
4994 String pkgName = res.name = pkg.packageName;
4995 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4996 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4997 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4998 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004999 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005000 }
5001 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5002 res.returnCode = pp.getParseError();
5003 return;
5004 }
5005 // Some preinstall checks
5006 if (forwardLocked && onSd) {
5007 // Make sure forward locked apps can only be installed
5008 // on internal storage
5009 Log.w(TAG, "Cannot install protected apps on sdcard");
5010 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5011 return;
5012 }
5013 // Get rid of all references to package scan path via parser.
5014 pp = null;
5015 String oldCodePath = null;
5016 boolean systemApp = false;
5017 synchronized (mPackages) {
5018 // Check if installing already existing package
5019 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
5020 && mPackages.containsKey(pkgName)) {
5021 replace = true;
5022 }
5023 PackageSetting ps = mSettings.mPackages.get(pkgName);
5024 if (ps != null) {
5025 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5026 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5027 systemApp = (ps.pkg.applicationInfo.flags &
5028 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005029 }
5030 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005031 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005032
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005033 if (systemApp && onSd) {
5034 // Disable updates to system apps on sdcard
5035 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5036 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5037 return;
5038 }
5039 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5040 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5041 return;
5042 }
5043 // Set application objects path explicitly after the rename
5044 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
5045 if(replace) {
5046 replacePackageLI(pkg, parseFlags, scanMode,
5047 installerPackageName, res);
5048 } else {
5049 installNewPackageLI(pkg, parseFlags, scanMode,
5050 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005051 }
5052 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005053
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005054 private int setPermissionsLI(PackageParser.Package newPackage) {
5055 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005056 int retCode = 0;
5057 // TODO Gross hack but fix later. Ideally move this to be a post installation
5058 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005059 if ((newPackage.applicationInfo.flags
5060 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5061 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 try {
5063 extractPublicFiles(newPackage, destResourceFile);
5064 } catch (IOException e) {
5065 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5066 " forward-locked app.");
5067 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5068 } finally {
5069 //TODO clean up the extracted public files
5070 }
5071 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005072 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005073 newPackage.applicationInfo.uid);
5074 } else {
5075 final int filePermissions =
5076 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005077 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005078 newPackage.applicationInfo.uid);
5079 }
5080 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005081 // The permissions on the resource file was set when it was copied for
5082 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005083 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005085 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005086 Log.e(TAG, "Couldn't set new package file permissions for " +
5087 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005089 // TODO Define new internal error
5090 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091 }
5092 return PackageManager.INSTALL_SUCCEEDED;
5093 }
5094
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005095 private boolean isForwardLocked(PackageParser.Package pkg) {
5096 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 }
5098
5099 private void extractPublicFiles(PackageParser.Package newPackage,
5100 File publicZipFile) throws IOException {
5101 final ZipOutputStream publicZipOutStream =
5102 new ZipOutputStream(new FileOutputStream(publicZipFile));
5103 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5104
5105 // Copy manifest, resources.arsc and res directory to public zip
5106
5107 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5108 while (privateZipEntries.hasMoreElements()) {
5109 final ZipEntry zipEntry = privateZipEntries.nextElement();
5110 final String zipEntryName = zipEntry.getName();
5111 if ("AndroidManifest.xml".equals(zipEntryName)
5112 || "resources.arsc".equals(zipEntryName)
5113 || zipEntryName.startsWith("res/")) {
5114 try {
5115 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5116 } catch (IOException e) {
5117 try {
5118 publicZipOutStream.close();
5119 throw e;
5120 } finally {
5121 publicZipFile.delete();
5122 }
5123 }
5124 }
5125 }
5126
5127 publicZipOutStream.close();
5128 FileUtils.setPermissions(
5129 publicZipFile.getAbsolutePath(),
5130 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5131 -1, -1);
5132 }
5133
5134 private static void copyZipEntry(ZipEntry zipEntry,
5135 ZipFile inZipFile,
5136 ZipOutputStream outZipStream) throws IOException {
5137 byte[] buffer = new byte[4096];
5138 int num;
5139
5140 ZipEntry newEntry;
5141 if (zipEntry.getMethod() == ZipEntry.STORED) {
5142 // Preserve the STORED method of the input entry.
5143 newEntry = new ZipEntry(zipEntry);
5144 } else {
5145 // Create a new entry so that the compressed len is recomputed.
5146 newEntry = new ZipEntry(zipEntry.getName());
5147 }
5148 outZipStream.putNextEntry(newEntry);
5149
5150 InputStream data = inZipFile.getInputStream(zipEntry);
5151 while ((num = data.read(buffer)) > 0) {
5152 outZipStream.write(buffer, 0, num);
5153 }
5154 outZipStream.flush();
5155 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005157 private void deleteTempPackageFiles() {
5158 FilenameFilter filter = new FilenameFilter() {
5159 public boolean accept(File dir, String name) {
5160 return name.startsWith("vmdl") && name.endsWith(".tmp");
5161 }
5162 };
5163 String tmpFilesList[] = mAppInstallDir.list(filter);
5164 if(tmpFilesList == null) {
5165 return;
5166 }
5167 for(int i = 0; i < tmpFilesList.length; i++) {
5168 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5169 tmpFile.delete();
5170 }
5171 }
5172
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005173 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005174 File tmpPackageFile;
5175 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005176 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005177 } catch (IOException e) {
5178 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5179 return null;
5180 }
5181 try {
5182 FileUtils.setPermissions(
5183 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5184 -1, -1);
5185 } catch (IOException e) {
5186 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5187 return null;
5188 }
5189 return tmpPackageFile;
5190 }
5191
5192 public void deletePackage(final String packageName,
5193 final IPackageDeleteObserver observer,
5194 final int flags) {
5195 mContext.enforceCallingOrSelfPermission(
5196 android.Manifest.permission.DELETE_PACKAGES, null);
5197 // Queue up an async operation since the package deletion may take a little while.
5198 mHandler.post(new Runnable() {
5199 public void run() {
5200 mHandler.removeCallbacks(this);
5201 final boolean succeded = deletePackageX(packageName, true, true, flags);
5202 if (observer != null) {
5203 try {
5204 observer.packageDeleted(succeded);
5205 } catch (RemoteException e) {
5206 Log.i(TAG, "Observer no longer exists.");
5207 } //end catch
5208 } //end if
5209 } //end run
5210 });
5211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005213 /**
5214 * This method is an internal method that could be get invoked either
5215 * to delete an installed package or to clean up a failed installation.
5216 * After deleting an installed package, a broadcast is sent to notify any
5217 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005218 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 * installation wouldn't have sent the initial broadcast either
5220 * The key steps in deleting a package are
5221 * deleting the package information in internal structures like mPackages,
5222 * deleting the packages base directories through installd
5223 * updating mSettings to reflect current status
5224 * persisting settings for later use
5225 * sending a broadcast if necessary
5226 */
5227
5228 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5229 boolean deleteCodeAndResources, int flags) {
5230 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005231 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232
5233 synchronized (mInstallLock) {
5234 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5235 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005238 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5239 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5240
5241 // If the removed package was a system update, the old system packaged
5242 // was re-enabled; we need to broadcast this information
5243 if (systemUpdate) {
5244 Bundle extras = new Bundle(1);
5245 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5246 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5247
5248 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5249 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005251 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005252 // Delete the resources here after sending the broadcast to let
5253 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005254 if (info.args != null) {
5255 synchronized (mInstallLock) {
5256 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005257 }
5258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005259 return res;
5260 }
5261
5262 static class PackageRemovedInfo {
5263 String removedPackage;
5264 int uid = -1;
5265 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005266 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005267 // Clean up resources deleted packages.
5268 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270 void sendBroadcast(boolean fullRemove, boolean replacing) {
5271 Bundle extras = new Bundle(1);
5272 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5273 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5274 if (replacing) {
5275 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5276 }
5277 if (removedPackage != null) {
5278 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5279 }
5280 if (removedUid >= 0) {
5281 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5282 }
5283 }
5284 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286 /*
5287 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5288 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005289 * 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 -08005290 * delete a partially installed application.
5291 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005292 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005293 int flags) {
5294 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005295 if (outInfo != null) {
5296 outInfo.removedPackage = packageName;
5297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005298 removePackageLI(p, true);
5299 // Retrieve object to delete permissions for shared user later on
5300 PackageSetting deletedPs;
5301 synchronized (mPackages) {
5302 deletedPs = mSettings.mPackages.get(packageName);
5303 }
5304 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005305 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005306 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005307 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 if (retCode < 0) {
5309 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5310 + packageName + ", retcode=" + retCode);
5311 // we don't consider this to be a failure of the core package deletion
5312 }
5313 } else {
5314 //for emulator
5315 PackageParser.Package pkg = mPackages.get(packageName);
5316 File dataDir = new File(pkg.applicationInfo.dataDir);
5317 dataDir.delete();
5318 }
5319 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005320 if (outInfo != null) {
5321 outInfo.removedUid = mSettings.removePackageLP(packageName);
5322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005323 }
5324 }
5325 synchronized (mPackages) {
5326 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5327 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005328 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005329 }
5330 // Save settings now
5331 mSettings.writeLP ();
5332 }
5333 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005335 /*
5336 * Tries to delete system package.
5337 */
5338 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005339 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005340 ApplicationInfo applicationInfo = p.applicationInfo;
5341 //applicable for non-partially installed applications only
5342 if (applicationInfo == null) {
5343 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5344 return false;
5345 }
5346 PackageSetting ps = null;
5347 // Confirm if the system package has been updated
5348 // An updated system app can be deleted. This will also have to restore
5349 // the system pkg from system partition
5350 synchronized (mPackages) {
5351 ps = mSettings.getDisabledSystemPkg(p.packageName);
5352 }
5353 if (ps == null) {
5354 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5355 return false;
5356 } else {
5357 Log.i(TAG, "Deleting system pkg from data partition");
5358 }
5359 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005360 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005361 boolean deleteCodeAndResources = false;
5362 if (ps.versionCode < p.mVersionCode) {
5363 // Delete code and resources for downgrades
5364 deleteCodeAndResources = true;
5365 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5366 flags &= ~PackageManager.DONT_DELETE_DATA;
5367 }
5368 } else {
5369 // Preserve data by setting flag
5370 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5371 flags |= PackageManager.DONT_DELETE_DATA;
5372 }
5373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5375 if (!ret) {
5376 return false;
5377 }
5378 synchronized (mPackages) {
5379 // Reinstate the old system package
5380 mSettings.enableSystemPackageLP(p.packageName);
5381 }
5382 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005383 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005385 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 if (newPkg == null) {
5388 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5389 return false;
5390 }
5391 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005392 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393 mSettings.writeLP();
5394 }
5395 return true;
5396 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5399 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5400 ApplicationInfo applicationInfo = p.applicationInfo;
5401 if (applicationInfo == null) {
5402 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5403 return false;
5404 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005405 if (outInfo != null) {
5406 outInfo.uid = applicationInfo.uid;
5407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408
5409 // Delete package data from internal structures and also remove data if flag is set
5410 removePackageDataLI(p, outInfo, flags);
5411
5412 // Delete application code and resources
5413 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005414 // TODO can pick up from PackageSettings as well
5415 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
5416 PackageManager.INSTALL_ON_SDCARD : 0;
5417 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5418 PackageManager.INSTALL_FORWARD_LOCK : 0;
5419 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005420 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421 }
5422 return true;
5423 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005425 /*
5426 * This method handles package deletion in general
5427 */
5428 private boolean deletePackageLI(String packageName,
5429 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5430 if (packageName == null) {
5431 Log.w(TAG, "Attempt to delete null packageName.");
5432 return false;
5433 }
5434 PackageParser.Package p;
5435 boolean dataOnly = false;
5436 synchronized (mPackages) {
5437 p = mPackages.get(packageName);
5438 if (p == null) {
5439 //this retrieves partially installed apps
5440 dataOnly = true;
5441 PackageSetting ps = mSettings.mPackages.get(packageName);
5442 if (ps == null) {
5443 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5444 return false;
5445 }
5446 p = ps.pkg;
5447 }
5448 }
5449 if (p == null) {
5450 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5451 return false;
5452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 if (dataOnly) {
5455 // Delete application data first
5456 removePackageDataLI(p, outInfo, flags);
5457 return true;
5458 }
5459 // At this point the package should have ApplicationInfo associated with it
5460 if (p.applicationInfo == null) {
5461 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5462 return false;
5463 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005464 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5466 Log.i(TAG, "Removing system package:"+p.packageName);
5467 // When an updated system application is deleted we delete the existing resources as well and
5468 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005469 ret = deleteSystemPackageLI(p, flags, outInfo);
5470 } else {
5471 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005472 // Kill application pre-emptively especially for apps on sd.
5473 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005474 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005476 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 public void clearApplicationUserData(final String packageName,
5480 final IPackageDataObserver observer) {
5481 mContext.enforceCallingOrSelfPermission(
5482 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5483 // Queue up an async operation since the package deletion may take a little while.
5484 mHandler.post(new Runnable() {
5485 public void run() {
5486 mHandler.removeCallbacks(this);
5487 final boolean succeeded;
5488 synchronized (mInstallLock) {
5489 succeeded = clearApplicationUserDataLI(packageName);
5490 }
5491 if (succeeded) {
5492 // invoke DeviceStorageMonitor's update method to clear any notifications
5493 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5494 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5495 if (dsm != null) {
5496 dsm.updateMemory();
5497 }
5498 }
5499 if(observer != null) {
5500 try {
5501 observer.onRemoveCompleted(packageName, succeeded);
5502 } catch (RemoteException e) {
5503 Log.i(TAG, "Observer no longer exists.");
5504 }
5505 } //end if observer
5506 } //end run
5507 });
5508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 private boolean clearApplicationUserDataLI(String packageName) {
5511 if (packageName == null) {
5512 Log.w(TAG, "Attempt to delete null packageName.");
5513 return false;
5514 }
5515 PackageParser.Package p;
5516 boolean dataOnly = false;
5517 synchronized (mPackages) {
5518 p = mPackages.get(packageName);
5519 if(p == null) {
5520 dataOnly = true;
5521 PackageSetting ps = mSettings.mPackages.get(packageName);
5522 if((ps == null) || (ps.pkg == null)) {
5523 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5524 return false;
5525 }
5526 p = ps.pkg;
5527 }
5528 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005529 boolean useEncryptedFSDir = false;
5530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005531 if(!dataOnly) {
5532 //need to check this only for fully installed applications
5533 if (p == null) {
5534 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5535 return false;
5536 }
5537 final ApplicationInfo applicationInfo = p.applicationInfo;
5538 if (applicationInfo == null) {
5539 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5540 return false;
5541 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005542 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 }
5544 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005545 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 if (retCode < 0) {
5547 Log.w(TAG, "Couldn't remove cache files for package: "
5548 + packageName);
5549 return false;
5550 }
5551 }
5552 return true;
5553 }
5554
5555 public void deleteApplicationCacheFiles(final String packageName,
5556 final IPackageDataObserver observer) {
5557 mContext.enforceCallingOrSelfPermission(
5558 android.Manifest.permission.DELETE_CACHE_FILES, null);
5559 // Queue up an async operation since the package deletion may take a little while.
5560 mHandler.post(new Runnable() {
5561 public void run() {
5562 mHandler.removeCallbacks(this);
5563 final boolean succeded;
5564 synchronized (mInstallLock) {
5565 succeded = deleteApplicationCacheFilesLI(packageName);
5566 }
5567 if(observer != null) {
5568 try {
5569 observer.onRemoveCompleted(packageName, succeded);
5570 } catch (RemoteException e) {
5571 Log.i(TAG, "Observer no longer exists.");
5572 }
5573 } //end if observer
5574 } //end run
5575 });
5576 }
5577
5578 private boolean deleteApplicationCacheFilesLI(String packageName) {
5579 if (packageName == null) {
5580 Log.w(TAG, "Attempt to delete null packageName.");
5581 return false;
5582 }
5583 PackageParser.Package p;
5584 synchronized (mPackages) {
5585 p = mPackages.get(packageName);
5586 }
5587 if (p == null) {
5588 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5589 return false;
5590 }
5591 final ApplicationInfo applicationInfo = p.applicationInfo;
5592 if (applicationInfo == null) {
5593 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5594 return false;
5595 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005596 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005598 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 if (retCode < 0) {
5600 Log.w(TAG, "Couldn't remove cache files for package: "
5601 + packageName);
5602 return false;
5603 }
5604 }
5605 return true;
5606 }
5607
5608 public void getPackageSizeInfo(final String packageName,
5609 final IPackageStatsObserver observer) {
5610 mContext.enforceCallingOrSelfPermission(
5611 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5612 // Queue up an async operation since the package deletion may take a little while.
5613 mHandler.post(new Runnable() {
5614 public void run() {
5615 mHandler.removeCallbacks(this);
5616 PackageStats lStats = new PackageStats(packageName);
5617 final boolean succeded;
5618 synchronized (mInstallLock) {
5619 succeded = getPackageSizeInfoLI(packageName, lStats);
5620 }
5621 if(observer != null) {
5622 try {
5623 observer.onGetStatsCompleted(lStats, succeded);
5624 } catch (RemoteException e) {
5625 Log.i(TAG, "Observer no longer exists.");
5626 }
5627 } //end if observer
5628 } //end run
5629 });
5630 }
5631
5632 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5633 if (packageName == null) {
5634 Log.w(TAG, "Attempt to get size of null packageName.");
5635 return false;
5636 }
5637 PackageParser.Package p;
5638 boolean dataOnly = false;
5639 synchronized (mPackages) {
5640 p = mPackages.get(packageName);
5641 if(p == null) {
5642 dataOnly = true;
5643 PackageSetting ps = mSettings.mPackages.get(packageName);
5644 if((ps == null) || (ps.pkg == null)) {
5645 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5646 return false;
5647 }
5648 p = ps.pkg;
5649 }
5650 }
5651 String publicSrcDir = null;
5652 if(!dataOnly) {
5653 final ApplicationInfo applicationInfo = p.applicationInfo;
5654 if (applicationInfo == null) {
5655 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5656 return false;
5657 }
5658 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
5659 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005660 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 if (mInstaller != null) {
5662 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08005663 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 if (res < 0) {
5665 return false;
5666 } else {
5667 return true;
5668 }
5669 }
5670 return true;
5671 }
5672
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 public void addPackageToPreferred(String packageName) {
5675 mContext.enforceCallingOrSelfPermission(
5676 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005677 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 }
5679
5680 public void removePackageFromPreferred(String packageName) {
5681 mContext.enforceCallingOrSelfPermission(
5682 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005683 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 }
5685
5686 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005687 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 }
5689
5690 public void addPreferredActivity(IntentFilter filter, int match,
5691 ComponentName[] set, ComponentName activity) {
5692 mContext.enforceCallingOrSelfPermission(
5693 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5694
5695 synchronized (mPackages) {
5696 Log.i(TAG, "Adding preferred activity " + activity + ":");
5697 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5698 mSettings.mPreferredActivities.addFilter(
5699 new PreferredActivity(filter, match, set, activity));
5700 mSettings.writeLP();
5701 }
5702 }
5703
Satish Sampath8dbe6122009-06-02 23:35:54 +01005704 public void replacePreferredActivity(IntentFilter filter, int match,
5705 ComponentName[] set, ComponentName activity) {
5706 mContext.enforceCallingOrSelfPermission(
5707 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5708 if (filter.countActions() != 1) {
5709 throw new IllegalArgumentException(
5710 "replacePreferredActivity expects filter to have only 1 action.");
5711 }
5712 if (filter.countCategories() != 1) {
5713 throw new IllegalArgumentException(
5714 "replacePreferredActivity expects filter to have only 1 category.");
5715 }
5716 if (filter.countDataAuthorities() != 0
5717 || filter.countDataPaths() != 0
5718 || filter.countDataSchemes() != 0
5719 || filter.countDataTypes() != 0) {
5720 throw new IllegalArgumentException(
5721 "replacePreferredActivity expects filter to have no data authorities, " +
5722 "paths, schemes or types.");
5723 }
5724 synchronized (mPackages) {
5725 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5726 String action = filter.getAction(0);
5727 String category = filter.getCategory(0);
5728 while (it.hasNext()) {
5729 PreferredActivity pa = it.next();
5730 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5731 it.remove();
5732 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5733 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5734 }
5735 }
5736 addPreferredActivity(filter, match, set, activity);
5737 }
5738 }
5739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 public void clearPackagePreferredActivities(String packageName) {
5741 mContext.enforceCallingOrSelfPermission(
5742 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5743
5744 synchronized (mPackages) {
5745 if (clearPackagePreferredActivitiesLP(packageName)) {
5746 mSettings.writeLP();
5747 }
5748 }
5749 }
5750
5751 boolean clearPackagePreferredActivitiesLP(String packageName) {
5752 boolean changed = false;
5753 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5754 while (it.hasNext()) {
5755 PreferredActivity pa = it.next();
5756 if (pa.mActivity.getPackageName().equals(packageName)) {
5757 it.remove();
5758 changed = true;
5759 }
5760 }
5761 return changed;
5762 }
5763
5764 public int getPreferredActivities(List<IntentFilter> outFilters,
5765 List<ComponentName> outActivities, String packageName) {
5766
5767 int num = 0;
5768 synchronized (mPackages) {
5769 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5770 while (it.hasNext()) {
5771 PreferredActivity pa = it.next();
5772 if (packageName == null
5773 || pa.mActivity.getPackageName().equals(packageName)) {
5774 if (outFilters != null) {
5775 outFilters.add(new IntentFilter(pa));
5776 }
5777 if (outActivities != null) {
5778 outActivities.add(pa.mActivity);
5779 }
5780 }
5781 }
5782 }
5783
5784 return num;
5785 }
5786
5787 public void setApplicationEnabledSetting(String appPackageName,
5788 int newState, int flags) {
5789 setEnabledSetting(appPackageName, null, newState, flags);
5790 }
5791
5792 public void setComponentEnabledSetting(ComponentName componentName,
5793 int newState, int flags) {
5794 setEnabledSetting(componentName.getPackageName(),
5795 componentName.getClassName(), newState, flags);
5796 }
5797
5798 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005799 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5801 || newState == COMPONENT_ENABLED_STATE_ENABLED
5802 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5803 throw new IllegalArgumentException("Invalid new component state: "
5804 + newState);
5805 }
5806 PackageSetting pkgSetting;
5807 final int uid = Binder.getCallingUid();
5808 final int permission = mContext.checkCallingPermission(
5809 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5810 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005811 boolean sendNow = false;
5812 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005813 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005815 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005817 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005819 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005821 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 }
5823 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005824 "Unknown component: " + packageName
5825 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 }
5827 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5828 throw new SecurityException(
5829 "Permission Denial: attempt to change component state from pid="
5830 + Binder.getCallingPid()
5831 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5832 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005833 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 // We're dealing with an application/package level state change
5835 pkgSetting.enabled = newState;
5836 } else {
5837 // We're dealing with a component level state change
5838 switch (newState) {
5839 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005840 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 break;
5842 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005843 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 break;
5845 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005846 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 break;
5848 default:
5849 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005850 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 }
5852 }
5853 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005854 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005855 components = mPendingBroadcasts.get(packageName);
5856 boolean newPackage = components == null;
5857 if (newPackage) {
5858 components = new ArrayList<String>();
5859 }
5860 if (!components.contains(componentName)) {
5861 components.add(componentName);
5862 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005863 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5864 sendNow = true;
5865 // Purge entry from pending broadcast list if another one exists already
5866 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005867 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005868 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005869 if (newPackage) {
5870 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005871 }
5872 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5873 // Schedule a message
5874 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5875 }
5876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 long callingId = Binder.clearCallingIdentity();
5880 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005881 if (sendNow) {
5882 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005883 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 } finally {
5886 Binder.restoreCallingIdentity(callingId);
5887 }
5888 }
5889
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005890 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005891 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
5892 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
5893 + " components=" + componentNames);
5894 Bundle extras = new Bundle(4);
5895 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
5896 String nameList[] = new String[componentNames.size()];
5897 componentNames.toArray(nameList);
5898 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005899 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5900 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005901 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005902 }
5903
Jacek Surazski65e13172009-04-28 15:26:38 +02005904 public String getInstallerPackageName(String packageName) {
5905 synchronized (mPackages) {
5906 PackageSetting pkg = mSettings.mPackages.get(packageName);
5907 if (pkg == null) {
5908 throw new IllegalArgumentException("Unknown package: " + packageName);
5909 }
5910 return pkg.installerPackageName;
5911 }
5912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005914 public int getApplicationEnabledSetting(String appPackageName) {
5915 synchronized (mPackages) {
5916 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5917 if (pkg == null) {
5918 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5919 }
5920 return pkg.enabled;
5921 }
5922 }
5923
5924 public int getComponentEnabledSetting(ComponentName componentName) {
5925 synchronized (mPackages) {
5926 final String packageNameStr = componentName.getPackageName();
5927 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5928 if (pkg == null) {
5929 throw new IllegalArgumentException("Unknown component: " + componentName);
5930 }
5931 final String classNameStr = componentName.getClassName();
5932 return pkg.currentEnabledStateLP(classNameStr);
5933 }
5934 }
5935
5936 public void enterSafeMode() {
5937 if (!mSystemReady) {
5938 mSafeMode = true;
5939 }
5940 }
5941
5942 public void systemReady() {
5943 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005944
5945 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005946 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005947 mContext.getContentResolver(),
5948 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005949 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005950 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005951 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005953 }
5954
5955 public boolean isSafeMode() {
5956 return mSafeMode;
5957 }
5958
5959 public boolean hasSystemUidErrors() {
5960 return mHasSystemUidErrors;
5961 }
5962
5963 static String arrayToString(int[] array) {
5964 StringBuffer buf = new StringBuffer(128);
5965 buf.append('[');
5966 if (array != null) {
5967 for (int i=0; i<array.length; i++) {
5968 if (i > 0) buf.append(", ");
5969 buf.append(array[i]);
5970 }
5971 }
5972 buf.append(']');
5973 return buf.toString();
5974 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 @Override
5977 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5978 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5979 != PackageManager.PERMISSION_GRANTED) {
5980 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5981 + Binder.getCallingPid()
5982 + ", uid=" + Binder.getCallingUid()
5983 + " without permission "
5984 + android.Manifest.permission.DUMP);
5985 return;
5986 }
5987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 synchronized (mPackages) {
5989 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005990 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 pw.println(" ");
5992 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005993 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 pw.println(" ");
5995 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005996 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 pw.println(" ");
5998 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005999 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006000 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 pw.println("Permissions:");
6002 {
6003 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006004 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6005 pw.print(Integer.toHexString(System.identityHashCode(p)));
6006 pw.println("):");
6007 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6008 pw.print(" uid="); pw.print(p.uid);
6009 pw.print(" gids="); pw.print(arrayToString(p.gids));
6010 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 }
6012 }
6013 pw.println(" ");
6014 pw.println("Packages:");
6015 {
6016 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006017 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
6018 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6019 pw.println("):");
6020 pw.print(" userId="); pw.print(ps.userId);
6021 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6022 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6023 pw.print(" pkg="); pw.println(ps.pkg);
6024 pw.print(" codePath="); pw.println(ps.codePathString);
6025 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006027 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006028 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006029 pw.print(" supportsScreens=[");
6030 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006031 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006032 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006033 if (!first) pw.print(", ");
6034 first = false;
6035 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006036 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006037 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006038 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006039 if (!first) pw.print(", ");
6040 first = false;
6041 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006042 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006043 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006044 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006045 if (!first) pw.print(", ");
6046 first = false;
6047 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006048 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006049 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006050 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006051 if (!first) pw.print(", ");
6052 first = false;
6053 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006054 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006055 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006056 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6057 if (!first) pw.print(", ");
6058 first = false;
6059 pw.print("anyDensity");
6060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006062 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006063 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6064 pw.print(" signatures="); pw.println(ps.signatures);
6065 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6066 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6067 pw.print(" installStatus="); pw.print(ps.installStatus);
6068 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 if (ps.disabledComponents.size() > 0) {
6070 pw.println(" disabledComponents:");
6071 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006072 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006073 }
6074 }
6075 if (ps.enabledComponents.size() > 0) {
6076 pw.println(" enabledComponents:");
6077 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006078 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 }
6080 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006081 if (ps.grantedPermissions.size() > 0) {
6082 pw.println(" grantedPermissions:");
6083 for (String s : ps.grantedPermissions) {
6084 pw.print(" "); pw.println(s);
6085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006087 if (ps.loadedPermissions.size() > 0) {
6088 pw.println(" loadedPermissions:");
6089 for (String s : ps.loadedPermissions) {
6090 pw.print(" "); pw.println(s);
6091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006092 }
6093 }
6094 }
6095 pw.println(" ");
6096 pw.println("Shared Users:");
6097 {
6098 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006099 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6100 pw.print(Integer.toHexString(System.identityHashCode(su)));
6101 pw.println("):");
6102 pw.print(" userId="); pw.print(su.userId);
6103 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 pw.println(" grantedPermissions:");
6105 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006106 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 }
6108 pw.println(" loadedPermissions:");
6109 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006110 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 }
6112 }
6113 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 pw.println(" ");
6116 pw.println("Settings parse messages:");
6117 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006118
6119 pw.println(" ");
6120 pw.println("Package warning messages:");
6121 File fname = getSettingsProblemFile();
6122 FileInputStream in;
6123 try {
6124 in = new FileInputStream(fname);
6125 int avail = in.available();
6126 byte[] data = new byte[avail];
6127 in.read(data);
6128 pw.println(new String(data));
6129 } catch (FileNotFoundException e) {
6130 } catch (IOException e) {
6131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006133
6134 synchronized (mProviders) {
6135 pw.println(" ");
6136 pw.println("Registered ContentProviders:");
6137 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006138 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006139 pw.println(p.toString());
6140 }
6141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 }
6143
6144 static final class BasePermission {
6145 final static int TYPE_NORMAL = 0;
6146 final static int TYPE_BUILTIN = 1;
6147 final static int TYPE_DYNAMIC = 2;
6148
6149 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006150 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 final int type;
6152 PackageParser.Permission perm;
6153 PermissionInfo pendingInfo;
6154 int uid;
6155 int[] gids;
6156
6157 BasePermission(String _name, String _sourcePackage, int _type) {
6158 name = _name;
6159 sourcePackage = _sourcePackage;
6160 type = _type;
6161 }
6162 }
6163
6164 static class PackageSignatures {
6165 private Signature[] mSignatures;
6166
6167 PackageSignatures(Signature[] sigs) {
6168 assignSignatures(sigs);
6169 }
6170
6171 PackageSignatures() {
6172 }
6173
6174 void writeXml(XmlSerializer serializer, String tagName,
6175 ArrayList<Signature> pastSignatures) throws IOException {
6176 if (mSignatures == null) {
6177 return;
6178 }
6179 serializer.startTag(null, tagName);
6180 serializer.attribute(null, "count",
6181 Integer.toString(mSignatures.length));
6182 for (int i=0; i<mSignatures.length; i++) {
6183 serializer.startTag(null, "cert");
6184 final Signature sig = mSignatures[i];
6185 final int sigHash = sig.hashCode();
6186 final int numPast = pastSignatures.size();
6187 int j;
6188 for (j=0; j<numPast; j++) {
6189 Signature pastSig = pastSignatures.get(j);
6190 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6191 serializer.attribute(null, "index", Integer.toString(j));
6192 break;
6193 }
6194 }
6195 if (j >= numPast) {
6196 pastSignatures.add(sig);
6197 serializer.attribute(null, "index", Integer.toString(numPast));
6198 serializer.attribute(null, "key", sig.toCharsString());
6199 }
6200 serializer.endTag(null, "cert");
6201 }
6202 serializer.endTag(null, tagName);
6203 }
6204
6205 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6206 throws IOException, XmlPullParserException {
6207 String countStr = parser.getAttributeValue(null, "count");
6208 if (countStr == null) {
6209 reportSettingsProblem(Log.WARN,
6210 "Error in package manager settings: <signatures> has"
6211 + " no count at " + parser.getPositionDescription());
6212 XmlUtils.skipCurrentTag(parser);
6213 }
6214 final int count = Integer.parseInt(countStr);
6215 mSignatures = new Signature[count];
6216 int pos = 0;
6217
6218 int outerDepth = parser.getDepth();
6219 int type;
6220 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6221 && (type != XmlPullParser.END_TAG
6222 || parser.getDepth() > outerDepth)) {
6223 if (type == XmlPullParser.END_TAG
6224 || type == XmlPullParser.TEXT) {
6225 continue;
6226 }
6227
6228 String tagName = parser.getName();
6229 if (tagName.equals("cert")) {
6230 if (pos < count) {
6231 String index = parser.getAttributeValue(null, "index");
6232 if (index != null) {
6233 try {
6234 int idx = Integer.parseInt(index);
6235 String key = parser.getAttributeValue(null, "key");
6236 if (key == null) {
6237 if (idx >= 0 && idx < pastSignatures.size()) {
6238 Signature sig = pastSignatures.get(idx);
6239 if (sig != null) {
6240 mSignatures[pos] = pastSignatures.get(idx);
6241 pos++;
6242 } else {
6243 reportSettingsProblem(Log.WARN,
6244 "Error in package manager settings: <cert> "
6245 + "index " + index + " is not defined at "
6246 + parser.getPositionDescription());
6247 }
6248 } else {
6249 reportSettingsProblem(Log.WARN,
6250 "Error in package manager settings: <cert> "
6251 + "index " + index + " is out of bounds at "
6252 + parser.getPositionDescription());
6253 }
6254 } else {
6255 while (pastSignatures.size() <= idx) {
6256 pastSignatures.add(null);
6257 }
6258 Signature sig = new Signature(key);
6259 pastSignatures.set(idx, sig);
6260 mSignatures[pos] = sig;
6261 pos++;
6262 }
6263 } catch (NumberFormatException e) {
6264 reportSettingsProblem(Log.WARN,
6265 "Error in package manager settings: <cert> "
6266 + "index " + index + " is not a number at "
6267 + parser.getPositionDescription());
6268 }
6269 } else {
6270 reportSettingsProblem(Log.WARN,
6271 "Error in package manager settings: <cert> has"
6272 + " no index at " + parser.getPositionDescription());
6273 }
6274 } else {
6275 reportSettingsProblem(Log.WARN,
6276 "Error in package manager settings: too "
6277 + "many <cert> tags, expected " + count
6278 + " at " + parser.getPositionDescription());
6279 }
6280 } else {
6281 reportSettingsProblem(Log.WARN,
6282 "Unknown element under <cert>: "
6283 + parser.getName());
6284 }
6285 XmlUtils.skipCurrentTag(parser);
6286 }
6287
6288 if (pos < count) {
6289 // Should never happen -- there is an error in the written
6290 // settings -- but if it does we don't want to generate
6291 // a bad array.
6292 Signature[] newSigs = new Signature[pos];
6293 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6294 mSignatures = newSigs;
6295 }
6296 }
6297
6298 /**
6299 * If any of the given 'sigs' is contained in the existing signatures,
6300 * then completely replace the current signatures with the ones in
6301 * 'sigs'. This is used for updating an existing package to a newly
6302 * installed version.
6303 */
6304 boolean updateSignatures(Signature[] sigs, boolean update) {
6305 if (mSignatures == null) {
6306 if (update) {
6307 assignSignatures(sigs);
6308 }
6309 return true;
6310 }
6311 if (sigs == null) {
6312 return false;
6313 }
6314
6315 for (int i=0; i<sigs.length; i++) {
6316 Signature sig = sigs[i];
6317 for (int j=0; j<mSignatures.length; j++) {
6318 if (mSignatures[j].equals(sig)) {
6319 if (update) {
6320 assignSignatures(sigs);
6321 }
6322 return true;
6323 }
6324 }
6325 }
6326 return false;
6327 }
6328
6329 /**
6330 * If any of the given 'sigs' is contained in the existing signatures,
6331 * then add in any new signatures found in 'sigs'. This is used for
6332 * including a new package into an existing shared user id.
6333 */
6334 boolean mergeSignatures(Signature[] sigs, boolean update) {
6335 if (mSignatures == null) {
6336 if (update) {
6337 assignSignatures(sigs);
6338 }
6339 return true;
6340 }
6341 if (sigs == null) {
6342 return false;
6343 }
6344
6345 Signature[] added = null;
6346 int addedCount = 0;
6347 boolean haveMatch = false;
6348 for (int i=0; i<sigs.length; i++) {
6349 Signature sig = sigs[i];
6350 boolean found = false;
6351 for (int j=0; j<mSignatures.length; j++) {
6352 if (mSignatures[j].equals(sig)) {
6353 found = true;
6354 haveMatch = true;
6355 break;
6356 }
6357 }
6358
6359 if (!found) {
6360 if (added == null) {
6361 added = new Signature[sigs.length];
6362 }
6363 added[i] = sig;
6364 addedCount++;
6365 }
6366 }
6367
6368 if (!haveMatch) {
6369 // Nothing matched -- reject the new signatures.
6370 return false;
6371 }
6372 if (added == null) {
6373 // Completely matched -- nothing else to do.
6374 return true;
6375 }
6376
6377 // Add additional signatures in.
6378 if (update) {
6379 Signature[] total = new Signature[addedCount+mSignatures.length];
6380 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6381 int j = mSignatures.length;
6382 for (int i=0; i<added.length; i++) {
6383 if (added[i] != null) {
6384 total[j] = added[i];
6385 j++;
6386 }
6387 }
6388 mSignatures = total;
6389 }
6390 return true;
6391 }
6392
6393 private void assignSignatures(Signature[] sigs) {
6394 if (sigs == null) {
6395 mSignatures = null;
6396 return;
6397 }
6398 mSignatures = new Signature[sigs.length];
6399 for (int i=0; i<sigs.length; i++) {
6400 mSignatures[i] = sigs[i];
6401 }
6402 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 @Override
6405 public String toString() {
6406 StringBuffer buf = new StringBuffer(128);
6407 buf.append("PackageSignatures{");
6408 buf.append(Integer.toHexString(System.identityHashCode(this)));
6409 buf.append(" [");
6410 if (mSignatures != null) {
6411 for (int i=0; i<mSignatures.length; i++) {
6412 if (i > 0) buf.append(", ");
6413 buf.append(Integer.toHexString(
6414 System.identityHashCode(mSignatures[i])));
6415 }
6416 }
6417 buf.append("]}");
6418 return buf.toString();
6419 }
6420 }
6421
6422 static class PreferredActivity extends IntentFilter {
6423 final int mMatch;
6424 final String[] mSetPackages;
6425 final String[] mSetClasses;
6426 final String[] mSetComponents;
6427 final ComponentName mActivity;
6428 final String mShortActivity;
6429 String mParseError;
6430
6431 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6432 ComponentName activity) {
6433 super(filter);
6434 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6435 mActivity = activity;
6436 mShortActivity = activity.flattenToShortString();
6437 mParseError = null;
6438 if (set != null) {
6439 final int N = set.length;
6440 String[] myPackages = new String[N];
6441 String[] myClasses = new String[N];
6442 String[] myComponents = new String[N];
6443 for (int i=0; i<N; i++) {
6444 ComponentName cn = set[i];
6445 if (cn == null) {
6446 mSetPackages = null;
6447 mSetClasses = null;
6448 mSetComponents = null;
6449 return;
6450 }
6451 myPackages[i] = cn.getPackageName().intern();
6452 myClasses[i] = cn.getClassName().intern();
6453 myComponents[i] = cn.flattenToShortString().intern();
6454 }
6455 mSetPackages = myPackages;
6456 mSetClasses = myClasses;
6457 mSetComponents = myComponents;
6458 } else {
6459 mSetPackages = null;
6460 mSetClasses = null;
6461 mSetComponents = null;
6462 }
6463 }
6464
6465 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6466 IOException {
6467 mShortActivity = parser.getAttributeValue(null, "name");
6468 mActivity = ComponentName.unflattenFromString(mShortActivity);
6469 if (mActivity == null) {
6470 mParseError = "Bad activity name " + mShortActivity;
6471 }
6472 String matchStr = parser.getAttributeValue(null, "match");
6473 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6474 String setCountStr = parser.getAttributeValue(null, "set");
6475 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6476
6477 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6478 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6479 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6480
6481 int setPos = 0;
6482
6483 int outerDepth = parser.getDepth();
6484 int type;
6485 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6486 && (type != XmlPullParser.END_TAG
6487 || parser.getDepth() > outerDepth)) {
6488 if (type == XmlPullParser.END_TAG
6489 || type == XmlPullParser.TEXT) {
6490 continue;
6491 }
6492
6493 String tagName = parser.getName();
6494 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6495 // + parser.getDepth() + " tag=" + tagName);
6496 if (tagName.equals("set")) {
6497 String name = parser.getAttributeValue(null, "name");
6498 if (name == null) {
6499 if (mParseError == null) {
6500 mParseError = "No name in set tag in preferred activity "
6501 + mShortActivity;
6502 }
6503 } else if (setPos >= setCount) {
6504 if (mParseError == null) {
6505 mParseError = "Too many set tags in preferred activity "
6506 + mShortActivity;
6507 }
6508 } else {
6509 ComponentName cn = ComponentName.unflattenFromString(name);
6510 if (cn == null) {
6511 if (mParseError == null) {
6512 mParseError = "Bad set name " + name + " in preferred activity "
6513 + mShortActivity;
6514 }
6515 } else {
6516 myPackages[setPos] = cn.getPackageName();
6517 myClasses[setPos] = cn.getClassName();
6518 myComponents[setPos] = name;
6519 setPos++;
6520 }
6521 }
6522 XmlUtils.skipCurrentTag(parser);
6523 } else if (tagName.equals("filter")) {
6524 //Log.i(TAG, "Starting to parse filter...");
6525 readFromXml(parser);
6526 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6527 // + parser.getDepth() + " tag=" + parser.getName());
6528 } else {
6529 reportSettingsProblem(Log.WARN,
6530 "Unknown element under <preferred-activities>: "
6531 + parser.getName());
6532 XmlUtils.skipCurrentTag(parser);
6533 }
6534 }
6535
6536 if (setPos != setCount) {
6537 if (mParseError == null) {
6538 mParseError = "Not enough set tags (expected " + setCount
6539 + " but found " + setPos + ") in " + mShortActivity;
6540 }
6541 }
6542
6543 mSetPackages = myPackages;
6544 mSetClasses = myClasses;
6545 mSetComponents = myComponents;
6546 }
6547
6548 public void writeToXml(XmlSerializer serializer) throws IOException {
6549 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6550 serializer.attribute(null, "name", mShortActivity);
6551 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6552 serializer.attribute(null, "set", Integer.toString(NS));
6553 for (int s=0; s<NS; s++) {
6554 serializer.startTag(null, "set");
6555 serializer.attribute(null, "name", mSetComponents[s]);
6556 serializer.endTag(null, "set");
6557 }
6558 serializer.startTag(null, "filter");
6559 super.writeToXml(serializer);
6560 serializer.endTag(null, "filter");
6561 }
6562
6563 boolean sameSet(List<ResolveInfo> query, int priority) {
6564 if (mSetPackages == null) return false;
6565 final int NQ = query.size();
6566 final int NS = mSetPackages.length;
6567 int numMatch = 0;
6568 for (int i=0; i<NQ; i++) {
6569 ResolveInfo ri = query.get(i);
6570 if (ri.priority != priority) continue;
6571 ActivityInfo ai = ri.activityInfo;
6572 boolean good = false;
6573 for (int j=0; j<NS; j++) {
6574 if (mSetPackages[j].equals(ai.packageName)
6575 && mSetClasses[j].equals(ai.name)) {
6576 numMatch++;
6577 good = true;
6578 break;
6579 }
6580 }
6581 if (!good) return false;
6582 }
6583 return numMatch == NS;
6584 }
6585 }
6586
6587 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006588 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 HashSet<String> grantedPermissions = new HashSet<String>();
6591 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006593 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006596 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
6597 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6598 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006599 }
6600 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 /**
6603 * Settings base class for pending and resolved classes.
6604 */
6605 static class PackageSettingBase extends GrantedPermissions {
6606 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006607 File codePath;
6608 String codePathString;
6609 File resourcePath;
6610 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 private long timeStamp;
6612 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006613 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006615 boolean uidError;
6616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 PackageSignatures signatures = new PackageSignatures();
6618
6619 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 /* Explicitly disabled components */
6622 HashSet<String> disabledComponents = new HashSet<String>(0);
6623 /* Explicitly enabled components */
6624 HashSet<String> enabledComponents = new HashSet<String>(0);
6625 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6626 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006627
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006628 PackageSettingBase origPackage;
6629
Jacek Surazski65e13172009-04-28 15:26:38 +02006630 /* package name of the app that installed this package */
6631 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632
6633 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006634 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 super(pkgFlags);
6636 this.name = name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006637 init(codePath, resourcePath, pVersionCode);
6638 }
6639
6640 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 this.codePath = codePath;
6642 this.codePathString = codePath.toString();
6643 this.resourcePath = resourcePath;
6644 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006645 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006647
Jacek Surazski65e13172009-04-28 15:26:38 +02006648 public void setInstallerPackageName(String packageName) {
6649 installerPackageName = packageName;
6650 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006651
Jacek Surazski65e13172009-04-28 15:26:38 +02006652 String getInstallerPackageName() {
6653 return installerPackageName;
6654 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006656 public void setInstallStatus(int newStatus) {
6657 installStatus = newStatus;
6658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660 public int getInstallStatus() {
6661 return installStatus;
6662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006664 public void setTimeStamp(long newStamp) {
6665 if (newStamp != timeStamp) {
6666 timeStamp = newStamp;
6667 timeStampString = Long.toString(newStamp);
6668 }
6669 }
6670
6671 public void setTimeStamp(long newStamp, String newStampStr) {
6672 timeStamp = newStamp;
6673 timeStampString = newStampStr;
6674 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006676 public long getTimeStamp() {
6677 return timeStamp;
6678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006680 public String getTimeStampStr() {
6681 return timeStampString;
6682 }
6683
6684 public void copyFrom(PackageSettingBase base) {
6685 grantedPermissions = base.grantedPermissions;
6686 gids = base.gids;
6687 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 timeStamp = base.timeStamp;
6690 timeStampString = base.timeStampString;
6691 signatures = base.signatures;
6692 permissionsFixed = base.permissionsFixed;
6693 disabledComponents = base.disabledComponents;
6694 enabledComponents = base.enabledComponents;
6695 enabled = base.enabled;
6696 installStatus = base.installStatus;
6697 }
6698
6699 void enableComponentLP(String componentClassName) {
6700 disabledComponents.remove(componentClassName);
6701 enabledComponents.add(componentClassName);
6702 }
6703
6704 void disableComponentLP(String componentClassName) {
6705 enabledComponents.remove(componentClassName);
6706 disabledComponents.add(componentClassName);
6707 }
6708
6709 void restoreComponentLP(String componentClassName) {
6710 enabledComponents.remove(componentClassName);
6711 disabledComponents.remove(componentClassName);
6712 }
6713
6714 int currentEnabledStateLP(String componentName) {
6715 if (enabledComponents.contains(componentName)) {
6716 return COMPONENT_ENABLED_STATE_ENABLED;
6717 } else if (disabledComponents.contains(componentName)) {
6718 return COMPONENT_ENABLED_STATE_DISABLED;
6719 } else {
6720 return COMPONENT_ENABLED_STATE_DEFAULT;
6721 }
6722 }
6723 }
6724
6725 /**
6726 * Settings data for a particular package we know about.
6727 */
6728 static final class PackageSetting extends PackageSettingBase {
6729 int userId;
6730 PackageParser.Package pkg;
6731 SharedUserSetting sharedUser;
6732
6733 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006734 int pVersionCode, int pkgFlags) {
6735 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 @Override
6739 public String toString() {
6740 return "PackageSetting{"
6741 + Integer.toHexString(System.identityHashCode(this))
6742 + " " + name + "/" + userId + "}";
6743 }
6744 }
6745
6746 /**
6747 * Settings data for a particular shared user ID we know about.
6748 */
6749 static final class SharedUserSetting extends GrantedPermissions {
6750 final String name;
6751 int userId;
6752 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6753 final PackageSignatures signatures = new PackageSignatures();
6754
6755 SharedUserSetting(String _name, int _pkgFlags) {
6756 super(_pkgFlags);
6757 name = _name;
6758 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 @Override
6761 public String toString() {
6762 return "SharedUserSetting{"
6763 + Integer.toHexString(System.identityHashCode(this))
6764 + " " + name + "/" + userId + "}";
6765 }
6766 }
6767
6768 /**
6769 * Holds information about dynamic settings.
6770 */
6771 private static final class Settings {
6772 private final File mSettingsFilename;
6773 private final File mBackupSettingsFilename;
6774 private final HashMap<String, PackageSetting> mPackages =
6775 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006776 // List of replaced system applications
6777 final HashMap<String, PackageSetting> mDisabledSysPackages =
6778 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006780 // The user's preferred activities associated with particular intent
6781 // filters.
6782 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6783 new IntentResolver<PreferredActivity, PreferredActivity>() {
6784 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006785 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006786 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006787 out.print(prefix); out.print(
6788 Integer.toHexString(System.identityHashCode(filter)));
6789 out.print(' ');
6790 out.print(filter.mActivity.flattenToShortString());
6791 out.print(" match=0x");
6792 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006794 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006795 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006796 out.print(prefix); out.print(" ");
6797 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006798 }
6799 }
6800 }
6801 };
6802 private final HashMap<String, SharedUserSetting> mSharedUsers =
6803 new HashMap<String, SharedUserSetting>();
6804 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6805 private final SparseArray<Object> mOtherUserIds =
6806 new SparseArray<Object>();
6807
6808 // For reading/writing settings file.
6809 private final ArrayList<Signature> mPastSignatures =
6810 new ArrayList<Signature>();
6811
6812 // Mapping from permission names to info about them.
6813 final HashMap<String, BasePermission> mPermissions =
6814 new HashMap<String, BasePermission>();
6815
6816 // Mapping from permission tree names to info about them.
6817 final HashMap<String, BasePermission> mPermissionTrees =
6818 new HashMap<String, BasePermission>();
6819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820 private final StringBuilder mReadMessages = new StringBuilder();
6821
6822 private static final class PendingPackage extends PackageSettingBase {
6823 final int sharedId;
6824
6825 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006826 int sharedId, int pVersionCode, int pkgFlags) {
6827 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006828 this.sharedId = sharedId;
6829 }
6830 }
6831 private final ArrayList<PendingPackage> mPendingPackages
6832 = new ArrayList<PendingPackage>();
6833
6834 Settings() {
6835 File dataDir = Environment.getDataDirectory();
6836 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08006837 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
6838 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08006840 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 FileUtils.setPermissions(systemDir.toString(),
6842 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6843 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6844 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08006845 FileUtils.setPermissions(systemSecureDir.toString(),
6846 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6847 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6848 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006849 mSettingsFilename = new File(systemDir, "packages.xml");
6850 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6851 }
6852
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006853 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006854 SharedUserSetting sharedUser, File codePath, File resourcePath,
6855 int pkgFlags, boolean create, boolean add) {
6856 final String name = pkg.packageName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006857 PackageSetting p = getPackageLP(name, origPackage, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006858 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006859 return p;
6860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006861
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006862 PackageSetting peekPackageLP(String name) {
6863 return mPackages.get(name);
6864 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 PackageSetting p = mPackages.get(name);
6866 if (p != null && p.codePath.getPath().equals(codePath)) {
6867 return p;
6868 }
6869 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006870 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006873 void setInstallStatus(String pkgName, int status) {
6874 PackageSetting p = mPackages.get(pkgName);
6875 if(p != null) {
6876 if(p.getInstallStatus() != status) {
6877 p.setInstallStatus(status);
6878 }
6879 }
6880 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006881
Jacek Surazski65e13172009-04-28 15:26:38 +02006882 void setInstallerPackageName(String pkgName,
6883 String installerPkgName) {
6884 PackageSetting p = mPackages.get(pkgName);
6885 if(p != null) {
6886 p.setInstallerPackageName(installerPkgName);
6887 }
6888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006889
Jacek Surazski65e13172009-04-28 15:26:38 +02006890 String getInstallerPackageName(String pkgName) {
6891 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006892 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02006893 }
6894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006895 int getInstallStatus(String pkgName) {
6896 PackageSetting p = mPackages.get(pkgName);
6897 if(p != null) {
6898 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006900 return -1;
6901 }
6902
6903 SharedUserSetting getSharedUserLP(String name,
6904 int pkgFlags, boolean create) {
6905 SharedUserSetting s = mSharedUsers.get(name);
6906 if (s == null) {
6907 if (!create) {
6908 return null;
6909 }
6910 s = new SharedUserSetting(name, pkgFlags);
6911 if (MULTIPLE_APPLICATION_UIDS) {
6912 s.userId = newUserIdLP(s);
6913 } else {
6914 s.userId = FIRST_APPLICATION_UID;
6915 }
6916 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6917 // < 0 means we couldn't assign a userid; fall out and return
6918 // s, which is currently null
6919 if (s.userId >= 0) {
6920 mSharedUsers.put(name, s);
6921 }
6922 }
6923
6924 return s;
6925 }
6926
6927 int disableSystemPackageLP(String name) {
6928 PackageSetting p = mPackages.get(name);
6929 if(p == null) {
6930 Log.w(TAG, "Package:"+name+" is not an installed package");
6931 return -1;
6932 }
6933 PackageSetting dp = mDisabledSysPackages.get(name);
6934 // always make sure the system package code and resource paths dont change
6935 if(dp == null) {
6936 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6937 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6938 }
6939 mDisabledSysPackages.put(name, p);
6940 }
6941 return removePackageLP(name);
6942 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 PackageSetting enableSystemPackageLP(String name) {
6945 PackageSetting p = mDisabledSysPackages.get(name);
6946 if(p == null) {
6947 Log.w(TAG, "Package:"+name+" is not disabled");
6948 return null;
6949 }
6950 // Reset flag in ApplicationInfo object
6951 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6952 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6953 }
6954 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006955 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956 mDisabledSysPackages.remove(name);
6957 return ret;
6958 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006960 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006961 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 PackageSetting p = mPackages.get(name);
6963 if (p != null) {
6964 if (p.userId == uid) {
6965 return p;
6966 }
6967 reportSettingsProblem(Log.ERROR,
6968 "Adding duplicate package, keeping first: " + name);
6969 return null;
6970 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006971 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006972 p.userId = uid;
6973 if (addUserIdLP(uid, p, name)) {
6974 mPackages.put(name, p);
6975 return p;
6976 }
6977 return null;
6978 }
6979
6980 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6981 SharedUserSetting s = mSharedUsers.get(name);
6982 if (s != null) {
6983 if (s.userId == uid) {
6984 return s;
6985 }
6986 reportSettingsProblem(Log.ERROR,
6987 "Adding duplicate shared user, keeping first: " + name);
6988 return null;
6989 }
6990 s = new SharedUserSetting(name, pkgFlags);
6991 s.userId = uid;
6992 if (addUserIdLP(uid, s, name)) {
6993 mSharedUsers.put(name, s);
6994 return s;
6995 }
6996 return null;
6997 }
6998
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006999 // Transfer ownership of permissions from one package to another.
7000 private void transferPermissions(String origPkg, String newPkg) {
7001 // Transfer ownership of permissions to the new package.
7002 for (int i=0; i<2; i++) {
7003 HashMap<String, BasePermission> permissions =
7004 i == 0 ? mPermissionTrees : mPermissions;
7005 for (BasePermission bp : permissions.values()) {
7006 if (origPkg.equals(bp.sourcePackage)) {
7007 if (DEBUG_UPGRADE) Log.v(TAG,
7008 "Moving permission " + bp.name
7009 + " from pkg " + bp.sourcePackage
7010 + " to " + newPkg);
7011 bp.sourcePackage = newPkg;
7012 bp.perm = null;
7013 if (bp.pendingInfo != null) {
7014 bp.sourcePackage = newPkg;
7015 }
7016 bp.uid = 0;
7017 bp.gids = null;
7018 }
7019 }
7020 }
7021 }
7022
7023 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007025 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007026 PackageSetting p = mPackages.get(name);
7027 if (p != null) {
7028 if (!p.codePath.equals(codePath)) {
7029 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007030 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007031 // This is an updated system app with versions in both system
7032 // and data partition. Just let the most recent version
7033 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007034 Log.w(TAG, "Trying to update system app code path from " +
7035 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007036 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007037 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07007038 reportSettingsProblem(Log.WARN,
7039 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007040 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007042 }
7043 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 reportSettingsProblem(Log.WARN,
7045 "Package " + name + " shared user changed from "
7046 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7047 + " to "
7048 + (sharedUser != null ? sharedUser.name : "<nothing>")
7049 + "; replacing with new");
7050 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007051 } else {
7052 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7053 // If what we are scanning is a system package, then
7054 // make it so, regardless of whether it was previously
7055 // installed only in the data partition.
7056 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007058 }
7059 }
7060 if (p == null) {
7061 // Create a new PackageSettings entry. this can end up here because
7062 // of code path mismatch or user id mismatch of an updated system partition
7063 if (!create) {
7064 return null;
7065 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007066 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007067 if (origPackage != null) {
7068 // We are consuming the data from an existing package.
7069 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7070 + " is adopting original package " + origPackage.name);
7071 p.copyFrom(origPackage);
7072 p.sharedUser = origPackage.sharedUser;
7073 p.userId = origPackage.userId;
7074 p.origPackage = origPackage;
7075 transferPermissions(origPackage.name, name);
7076 // Update new package state.
7077 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007078 } else {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007079 p.setTimeStamp(codePath.lastModified());
7080 p.sharedUser = sharedUser;
7081 if (sharedUser != null) {
7082 p.userId = sharedUser.userId;
7083 } else if (MULTIPLE_APPLICATION_UIDS) {
7084 // Clone the setting here for disabled system packages
7085 PackageSetting dis = mDisabledSysPackages.get(name);
7086 if (dis != null) {
7087 // For disabled packages a new setting is created
7088 // from the existing user id. This still has to be
7089 // added to list of user id's
7090 // Copy signatures from previous setting
7091 if (dis.signatures.mSignatures != null) {
7092 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7093 }
7094 p.userId = dis.userId;
7095 // Clone permissions
7096 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7097 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7098 // Clone component info
7099 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7100 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7101 // Add new setting to list of user ids
7102 addUserIdLP(p.userId, p, name);
7103 } else {
7104 // Assign new user id
7105 p.userId = newUserIdLP(p);
7106 }
7107 } else {
7108 p.userId = FIRST_APPLICATION_UID;
7109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110 }
7111 if (p.userId < 0) {
7112 reportSettingsProblem(Log.WARN,
7113 "Package " + name + " could not be assigned a valid uid");
7114 return null;
7115 }
7116 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007117 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007119 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007120 }
7121 }
7122 return p;
7123 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007124
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007125 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007126 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007127 String codePath = pkg.applicationInfo.sourceDir;
7128 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007129 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007130 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007131 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007132 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007133 p.codePath = new File(codePath);
7134 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007135 }
7136 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007137 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007138 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007139 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007140 p.resourcePath = new File(resourcePath);
7141 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007142 }
7143 // Update version code if needed
7144 if (pkg.mVersionCode != p.versionCode) {
7145 p.versionCode = pkg.mVersionCode;
7146 }
7147 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7148 }
7149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007150 // Utility method that adds a PackageSetting to mPackages and
7151 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007152 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 SharedUserSetting sharedUser) {
7154 mPackages.put(name, p);
7155 if (sharedUser != null) {
7156 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7157 reportSettingsProblem(Log.ERROR,
7158 "Package " + p.name + " was user "
7159 + p.sharedUser + " but is now " + sharedUser
7160 + "; I am not changing its files so it will probably fail!");
7161 p.sharedUser.packages.remove(p);
7162 } else if (p.userId != sharedUser.userId) {
7163 reportSettingsProblem(Log.ERROR,
7164 "Package " + p.name + " was user id " + p.userId
7165 + " but is now user " + sharedUser
7166 + " with id " + sharedUser.userId
7167 + "; I am not changing its files so it will probably fail!");
7168 }
7169
7170 sharedUser.packages.add(p);
7171 p.sharedUser = sharedUser;
7172 p.userId = sharedUser.userId;
7173 }
7174 }
7175
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007176 /*
7177 * Update the shared user setting when a package using
7178 * specifying the shared user id is removed. The gids
7179 * associated with each permission of the deleted package
7180 * are removed from the shared user's gid list only if its
7181 * not in use by other permissions of packages in the
7182 * shared user setting.
7183 */
7184 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007185 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7186 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7187 return;
7188 }
7189 // No sharedUserId
7190 if (deletedPs.sharedUser == null) {
7191 return;
7192 }
7193 SharedUserSetting sus = deletedPs.sharedUser;
7194 // Update permissions
7195 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7196 boolean used = false;
7197 if (!sus.grantedPermissions.contains (eachPerm)) {
7198 continue;
7199 }
7200 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007201 if (pkg.pkg != null &&
7202 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7203 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 used = true;
7205 break;
7206 }
7207 }
7208 if (!used) {
7209 // can safely delete this permission from list
7210 sus.grantedPermissions.remove(eachPerm);
7211 sus.loadedPermissions.remove(eachPerm);
7212 }
7213 }
7214 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007215 int newGids[] = globalGids;
7216 for (String eachPerm : sus.grantedPermissions) {
7217 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007218 if (bp != null) {
7219 newGids = appendInts(newGids, bp.gids);
7220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 }
7222 sus.gids = newGids;
7223 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007225 private int removePackageLP(String name) {
7226 PackageSetting p = mPackages.get(name);
7227 if (p != null) {
7228 mPackages.remove(name);
7229 if (p.sharedUser != null) {
7230 p.sharedUser.packages.remove(p);
7231 if (p.sharedUser.packages.size() == 0) {
7232 mSharedUsers.remove(p.sharedUser.name);
7233 removeUserIdLP(p.sharedUser.userId);
7234 return p.sharedUser.userId;
7235 }
7236 } else {
7237 removeUserIdLP(p.userId);
7238 return p.userId;
7239 }
7240 }
7241 return -1;
7242 }
7243
7244 private boolean addUserIdLP(int uid, Object obj, Object name) {
7245 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7246 return false;
7247 }
7248
7249 if (uid >= FIRST_APPLICATION_UID) {
7250 int N = mUserIds.size();
7251 final int index = uid - FIRST_APPLICATION_UID;
7252 while (index >= N) {
7253 mUserIds.add(null);
7254 N++;
7255 }
7256 if (mUserIds.get(index) != null) {
7257 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007258 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007259 + " name=" + name);
7260 return false;
7261 }
7262 mUserIds.set(index, obj);
7263 } else {
7264 if (mOtherUserIds.get(uid) != null) {
7265 reportSettingsProblem(Log.ERROR,
7266 "Adding duplicate shared id: " + uid
7267 + " name=" + name);
7268 return false;
7269 }
7270 mOtherUserIds.put(uid, obj);
7271 }
7272 return true;
7273 }
7274
7275 public Object getUserIdLP(int uid) {
7276 if (uid >= FIRST_APPLICATION_UID) {
7277 int N = mUserIds.size();
7278 final int index = uid - FIRST_APPLICATION_UID;
7279 return index < N ? mUserIds.get(index) : null;
7280 } else {
7281 return mOtherUserIds.get(uid);
7282 }
7283 }
7284
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007285 private Set<String> findPackagesWithFlag(int flag) {
7286 Set<String> ret = new HashSet<String>();
7287 for (PackageSetting ps : mPackages.values()) {
7288 // Has to match atleast all the flag bits set on flag
7289 if ((ps.pkgFlags & flag) == flag) {
7290 ret.add(ps.name);
7291 }
7292 }
7293 return ret;
7294 }
7295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 private void removeUserIdLP(int uid) {
7297 if (uid >= FIRST_APPLICATION_UID) {
7298 int N = mUserIds.size();
7299 final int index = uid - FIRST_APPLICATION_UID;
7300 if (index < N) mUserIds.set(index, null);
7301 } else {
7302 mOtherUserIds.remove(uid);
7303 }
7304 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306 void writeLP() {
7307 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7308
7309 // Keep the old settings around until we know the new ones have
7310 // been successfully written.
7311 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007312 // Presence of backup settings file indicates that we failed
7313 // to persist settings earlier. So preserve the older
7314 // backup for future reference since the current settings
7315 // might have been corrupted.
7316 if (!mBackupSettingsFilename.exists()) {
7317 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7318 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7319 return;
7320 }
7321 } else {
7322 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 }
7325
7326 mPastSignatures.clear();
7327
7328 try {
7329 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7330
7331 //XmlSerializer serializer = XmlUtils.serializerInstance();
7332 XmlSerializer serializer = new FastXmlSerializer();
7333 serializer.setOutput(str, "utf-8");
7334 serializer.startDocument(null, true);
7335 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7336
7337 serializer.startTag(null, "packages");
7338
7339 serializer.startTag(null, "permission-trees");
7340 for (BasePermission bp : mPermissionTrees.values()) {
7341 writePermission(serializer, bp);
7342 }
7343 serializer.endTag(null, "permission-trees");
7344
7345 serializer.startTag(null, "permissions");
7346 for (BasePermission bp : mPermissions.values()) {
7347 writePermission(serializer, bp);
7348 }
7349 serializer.endTag(null, "permissions");
7350
7351 for (PackageSetting pkg : mPackages.values()) {
7352 writePackage(serializer, pkg);
7353 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007355 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7356 writeDisabledSysPackage(serializer, pkg);
7357 }
7358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007359 serializer.startTag(null, "preferred-activities");
7360 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7361 serializer.startTag(null, "item");
7362 pa.writeToXml(serializer);
7363 serializer.endTag(null, "item");
7364 }
7365 serializer.endTag(null, "preferred-activities");
7366
7367 for (SharedUserSetting usr : mSharedUsers.values()) {
7368 serializer.startTag(null, "shared-user");
7369 serializer.attribute(null, "name", usr.name);
7370 serializer.attribute(null, "userId",
7371 Integer.toString(usr.userId));
7372 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7373 serializer.startTag(null, "perms");
7374 for (String name : usr.grantedPermissions) {
7375 serializer.startTag(null, "item");
7376 serializer.attribute(null, "name", name);
7377 serializer.endTag(null, "item");
7378 }
7379 serializer.endTag(null, "perms");
7380 serializer.endTag(null, "shared-user");
7381 }
7382
7383 serializer.endTag(null, "packages");
7384
7385 serializer.endDocument();
7386
7387 str.flush();
7388 str.close();
7389
7390 // New settings successfully written, old ones are no longer
7391 // needed.
7392 mBackupSettingsFilename.delete();
7393 FileUtils.setPermissions(mSettingsFilename.toString(),
7394 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7395 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7396 |FileUtils.S_IROTH,
7397 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007398 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007399
7400 } catch(XmlPullParserException e) {
7401 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 -08007402 } catch(java.io.IOException e) {
7403 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 -08007404 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007405 // Clean up partially written file
7406 if (mSettingsFilename.exists()) {
7407 if (!mSettingsFilename.delete()) {
7408 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7409 }
7410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007411 //Debug.stopMethodTracing();
7412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007413
7414 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 throws java.io.IOException {
7416 serializer.startTag(null, "updated-package");
7417 serializer.attribute(null, "name", pkg.name);
7418 serializer.attribute(null, "codePath", pkg.codePathString);
7419 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007420 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7422 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7423 }
7424 if (pkg.sharedUser == null) {
7425 serializer.attribute(null, "userId",
7426 Integer.toString(pkg.userId));
7427 } else {
7428 serializer.attribute(null, "sharedUserId",
7429 Integer.toString(pkg.userId));
7430 }
7431 serializer.startTag(null, "perms");
7432 if (pkg.sharedUser == null) {
7433 // If this is a shared user, the permissions will
7434 // be written there. We still need to write an
7435 // empty permissions list so permissionsFixed will
7436 // be set.
7437 for (final String name : pkg.grantedPermissions) {
7438 BasePermission bp = mPermissions.get(name);
7439 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7440 // We only need to write signature or system permissions but this wont
7441 // match the semantics of grantedPermissions. So write all permissions.
7442 serializer.startTag(null, "item");
7443 serializer.attribute(null, "name", name);
7444 serializer.endTag(null, "item");
7445 }
7446 }
7447 }
7448 serializer.endTag(null, "perms");
7449 serializer.endTag(null, "updated-package");
7450 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007451
7452 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007453 throws java.io.IOException {
7454 serializer.startTag(null, "package");
7455 serializer.attribute(null, "name", pkg.name);
7456 serializer.attribute(null, "codePath", pkg.codePathString);
7457 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7458 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7459 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007460 serializer.attribute(null, "flags",
7461 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007462 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007463 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007464 if (pkg.sharedUser == null) {
7465 serializer.attribute(null, "userId",
7466 Integer.toString(pkg.userId));
7467 } else {
7468 serializer.attribute(null, "sharedUserId",
7469 Integer.toString(pkg.userId));
7470 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007471 if (pkg.uidError) {
7472 serializer.attribute(null, "uidError", "true");
7473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007474 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7475 serializer.attribute(null, "enabled",
7476 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7477 ? "true" : "false");
7478 }
7479 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7480 serializer.attribute(null, "installStatus", "false");
7481 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007482 if (pkg.installerPackageName != null) {
7483 serializer.attribute(null, "installer", pkg.installerPackageName);
7484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007485 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7486 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7487 serializer.startTag(null, "perms");
7488 if (pkg.sharedUser == null) {
7489 // If this is a shared user, the permissions will
7490 // be written there. We still need to write an
7491 // empty permissions list so permissionsFixed will
7492 // be set.
7493 for (final String name : pkg.grantedPermissions) {
7494 serializer.startTag(null, "item");
7495 serializer.attribute(null, "name", name);
7496 serializer.endTag(null, "item");
7497 }
7498 }
7499 serializer.endTag(null, "perms");
7500 }
7501 if (pkg.disabledComponents.size() > 0) {
7502 serializer.startTag(null, "disabled-components");
7503 for (final String name : pkg.disabledComponents) {
7504 serializer.startTag(null, "item");
7505 serializer.attribute(null, "name", name);
7506 serializer.endTag(null, "item");
7507 }
7508 serializer.endTag(null, "disabled-components");
7509 }
7510 if (pkg.enabledComponents.size() > 0) {
7511 serializer.startTag(null, "enabled-components");
7512 for (final String name : pkg.enabledComponents) {
7513 serializer.startTag(null, "item");
7514 serializer.attribute(null, "name", name);
7515 serializer.endTag(null, "item");
7516 }
7517 serializer.endTag(null, "enabled-components");
7518 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 serializer.endTag(null, "package");
7521 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 void writePermission(XmlSerializer serializer, BasePermission bp)
7524 throws XmlPullParserException, java.io.IOException {
7525 if (bp.type != BasePermission.TYPE_BUILTIN
7526 && bp.sourcePackage != null) {
7527 serializer.startTag(null, "item");
7528 serializer.attribute(null, "name", bp.name);
7529 serializer.attribute(null, "package", bp.sourcePackage);
7530 if (DEBUG_SETTINGS) Log.v(TAG,
7531 "Writing perm: name=" + bp.name + " type=" + bp.type);
7532 if (bp.type == BasePermission.TYPE_DYNAMIC) {
7533 PermissionInfo pi = bp.perm != null ? bp.perm.info
7534 : bp.pendingInfo;
7535 if (pi != null) {
7536 serializer.attribute(null, "type", "dynamic");
7537 if (pi.icon != 0) {
7538 serializer.attribute(null, "icon",
7539 Integer.toString(pi.icon));
7540 }
7541 if (pi.nonLocalizedLabel != null) {
7542 serializer.attribute(null, "label",
7543 pi.nonLocalizedLabel.toString());
7544 }
7545 if (pi.protectionLevel !=
7546 PermissionInfo.PROTECTION_NORMAL) {
7547 serializer.attribute(null, "protection",
7548 Integer.toString(pi.protectionLevel));
7549 }
7550 }
7551 }
7552 serializer.endTag(null, "item");
7553 }
7554 }
7555
7556 String getReadMessagesLP() {
7557 return mReadMessages.toString();
7558 }
7559
Oscar Montemayora8529f62009-11-18 10:14:20 -08007560 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
7562 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007563 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 while(its.hasNext()) {
7565 String key = its.next();
7566 PackageSetting ps = mPackages.get(key);
7567 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08007568 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 }
7570 }
7571 return ret;
7572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 boolean readLP() {
7575 FileInputStream str = null;
7576 if (mBackupSettingsFilename.exists()) {
7577 try {
7578 str = new FileInputStream(mBackupSettingsFilename);
7579 mReadMessages.append("Reading from backup settings file\n");
7580 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007581 if (mSettingsFilename.exists()) {
7582 // If both the backup and settings file exist, we
7583 // ignore the settings since it might have been
7584 // corrupted.
7585 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
7586 mSettingsFilename.delete();
7587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 } catch (java.io.IOException e) {
7589 // We'll try for the normal settings file.
7590 }
7591 }
7592
7593 mPastSignatures.clear();
7594
7595 try {
7596 if (str == null) {
7597 if (!mSettingsFilename.exists()) {
7598 mReadMessages.append("No settings file found\n");
7599 Log.i(TAG, "No current settings file!");
7600 return false;
7601 }
7602 str = new FileInputStream(mSettingsFilename);
7603 }
7604 XmlPullParser parser = Xml.newPullParser();
7605 parser.setInput(str, null);
7606
7607 int type;
7608 while ((type=parser.next()) != XmlPullParser.START_TAG
7609 && type != XmlPullParser.END_DOCUMENT) {
7610 ;
7611 }
7612
7613 if (type != XmlPullParser.START_TAG) {
7614 mReadMessages.append("No start tag found in settings file\n");
7615 Log.e(TAG, "No start tag found in package manager settings");
7616 return false;
7617 }
7618
7619 int outerDepth = parser.getDepth();
7620 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7621 && (type != XmlPullParser.END_TAG
7622 || parser.getDepth() > outerDepth)) {
7623 if (type == XmlPullParser.END_TAG
7624 || type == XmlPullParser.TEXT) {
7625 continue;
7626 }
7627
7628 String tagName = parser.getName();
7629 if (tagName.equals("package")) {
7630 readPackageLP(parser);
7631 } else if (tagName.equals("permissions")) {
7632 readPermissionsLP(mPermissions, parser);
7633 } else if (tagName.equals("permission-trees")) {
7634 readPermissionsLP(mPermissionTrees, parser);
7635 } else if (tagName.equals("shared-user")) {
7636 readSharedUserLP(parser);
7637 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08007638 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007639 } else if (tagName.equals("preferred-activities")) {
7640 readPreferredActivitiesLP(parser);
7641 } else if(tagName.equals("updated-package")) {
7642 readDisabledSysPackageLP(parser);
7643 } else {
7644 Log.w(TAG, "Unknown element under <packages>: "
7645 + parser.getName());
7646 XmlUtils.skipCurrentTag(parser);
7647 }
7648 }
7649
7650 str.close();
7651
7652 } catch(XmlPullParserException e) {
7653 mReadMessages.append("Error reading: " + e.toString());
7654 Log.e(TAG, "Error reading package manager settings", e);
7655
7656 } catch(java.io.IOException e) {
7657 mReadMessages.append("Error reading: " + e.toString());
7658 Log.e(TAG, "Error reading package manager settings", e);
7659
7660 }
7661
7662 int N = mPendingPackages.size();
7663 for (int i=0; i<N; i++) {
7664 final PendingPackage pp = mPendingPackages.get(i);
7665 Object idObj = getUserIdLP(pp.sharedId);
7666 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007667 PackageSetting p = getPackageLP(pp.name, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007669 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 if (p == null) {
7671 Log.w(TAG, "Unable to create application package for "
7672 + pp.name);
7673 continue;
7674 }
7675 p.copyFrom(pp);
7676 } else if (idObj != null) {
7677 String msg = "Bad package setting: package " + pp.name
7678 + " has shared uid " + pp.sharedId
7679 + " that is not a shared uid\n";
7680 mReadMessages.append(msg);
7681 Log.e(TAG, msg);
7682 } else {
7683 String msg = "Bad package setting: package " + pp.name
7684 + " has shared uid " + pp.sharedId
7685 + " that is not defined\n";
7686 mReadMessages.append(msg);
7687 Log.e(TAG, msg);
7688 }
7689 }
7690 mPendingPackages.clear();
7691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 mReadMessages.append("Read completed successfully: "
7693 + mPackages.size() + " packages, "
7694 + mSharedUsers.size() + " shared uids\n");
7695
7696 return true;
7697 }
7698
7699 private int readInt(XmlPullParser parser, String ns, String name,
7700 int defValue) {
7701 String v = parser.getAttributeValue(ns, name);
7702 try {
7703 if (v == null) {
7704 return defValue;
7705 }
7706 return Integer.parseInt(v);
7707 } catch (NumberFormatException e) {
7708 reportSettingsProblem(Log.WARN,
7709 "Error in package manager settings: attribute " +
7710 name + " has bad integer value " + v + " at "
7711 + parser.getPositionDescription());
7712 }
7713 return defValue;
7714 }
7715
7716 private void readPermissionsLP(HashMap<String, BasePermission> out,
7717 XmlPullParser parser)
7718 throws IOException, XmlPullParserException {
7719 int outerDepth = parser.getDepth();
7720 int type;
7721 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7722 && (type != XmlPullParser.END_TAG
7723 || parser.getDepth() > outerDepth)) {
7724 if (type == XmlPullParser.END_TAG
7725 || type == XmlPullParser.TEXT) {
7726 continue;
7727 }
7728
7729 String tagName = parser.getName();
7730 if (tagName.equals("item")) {
7731 String name = parser.getAttributeValue(null, "name");
7732 String sourcePackage = parser.getAttributeValue(null, "package");
7733 String ptype = parser.getAttributeValue(null, "type");
7734 if (name != null && sourcePackage != null) {
7735 boolean dynamic = "dynamic".equals(ptype);
7736 BasePermission bp = new BasePermission(name, sourcePackage,
7737 dynamic
7738 ? BasePermission.TYPE_DYNAMIC
7739 : BasePermission.TYPE_NORMAL);
7740 if (dynamic) {
7741 PermissionInfo pi = new PermissionInfo();
7742 pi.packageName = sourcePackage.intern();
7743 pi.name = name.intern();
7744 pi.icon = readInt(parser, null, "icon", 0);
7745 pi.nonLocalizedLabel = parser.getAttributeValue(
7746 null, "label");
7747 pi.protectionLevel = readInt(parser, null, "protection",
7748 PermissionInfo.PROTECTION_NORMAL);
7749 bp.pendingInfo = pi;
7750 }
7751 out.put(bp.name, bp);
7752 } else {
7753 reportSettingsProblem(Log.WARN,
7754 "Error in package manager settings: permissions has"
7755 + " no name at " + parser.getPositionDescription());
7756 }
7757 } else {
7758 reportSettingsProblem(Log.WARN,
7759 "Unknown element reading permissions: "
7760 + parser.getName() + " at "
7761 + parser.getPositionDescription());
7762 }
7763 XmlUtils.skipCurrentTag(parser);
7764 }
7765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007767 private void readDisabledSysPackageLP(XmlPullParser parser)
7768 throws XmlPullParserException, IOException {
7769 String name = parser.getAttributeValue(null, "name");
7770 String codePathStr = parser.getAttributeValue(null, "codePath");
7771 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
7772 if(resourcePathStr == null) {
7773 resourcePathStr = codePathStr;
7774 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007775 String version = parser.getAttributeValue(null, "version");
7776 int versionCode = 0;
7777 if (version != null) {
7778 try {
7779 versionCode = Integer.parseInt(version);
7780 } catch (NumberFormatException e) {
7781 }
7782 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007784 int pkgFlags = 0;
7785 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007786 PackageSetting ps = new PackageSetting(name,
7787 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007788 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007789 String timeStampStr = parser.getAttributeValue(null, "ts");
7790 if (timeStampStr != null) {
7791 try {
7792 long timeStamp = Long.parseLong(timeStampStr);
7793 ps.setTimeStamp(timeStamp, timeStampStr);
7794 } catch (NumberFormatException e) {
7795 }
7796 }
7797 String idStr = parser.getAttributeValue(null, "userId");
7798 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
7799 if(ps.userId <= 0) {
7800 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7801 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
7802 }
7803 int outerDepth = parser.getDepth();
7804 int type;
7805 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7806 && (type != XmlPullParser.END_TAG
7807 || parser.getDepth() > outerDepth)) {
7808 if (type == XmlPullParser.END_TAG
7809 || type == XmlPullParser.TEXT) {
7810 continue;
7811 }
7812
7813 String tagName = parser.getName();
7814 if (tagName.equals("perms")) {
7815 readGrantedPermissionsLP(parser,
7816 ps.grantedPermissions);
7817 } else {
7818 reportSettingsProblem(Log.WARN,
7819 "Unknown element under <updated-package>: "
7820 + parser.getName());
7821 XmlUtils.skipCurrentTag(parser);
7822 }
7823 }
7824 mDisabledSysPackages.put(name, ps);
7825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 private void readPackageLP(XmlPullParser parser)
7828 throws XmlPullParserException, IOException {
7829 String name = null;
7830 String idStr = null;
7831 String sharedIdStr = null;
7832 String codePathStr = null;
7833 String resourcePathStr = null;
7834 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02007835 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007836 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007837 int pkgFlags = 0;
7838 String timeStampStr;
7839 long timeStamp = 0;
7840 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007841 String version = null;
7842 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 try {
7844 name = parser.getAttributeValue(null, "name");
7845 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007846 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
7848 codePathStr = parser.getAttributeValue(null, "codePath");
7849 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007850 version = parser.getAttributeValue(null, "version");
7851 if (version != null) {
7852 try {
7853 versionCode = Integer.parseInt(version);
7854 } catch (NumberFormatException e) {
7855 }
7856 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007857 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007858
7859 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007860 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007861 try {
7862 pkgFlags = Integer.parseInt(systemStr);
7863 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 }
7865 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007866 // For backward compatibility
7867 systemStr = parser.getAttributeValue(null, "system");
7868 if (systemStr != null) {
7869 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
7870 } else {
7871 // Old settings that don't specify system... just treat
7872 // them as system, good enough.
7873 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007875 }
7876 timeStampStr = parser.getAttributeValue(null, "ts");
7877 if (timeStampStr != null) {
7878 try {
7879 timeStamp = Long.parseLong(timeStampStr);
7880 } catch (NumberFormatException e) {
7881 }
7882 }
7883 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7884 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7885 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7886 if (resourcePathStr == null) {
7887 resourcePathStr = codePathStr;
7888 }
7889 if (name == null) {
7890 reportSettingsProblem(Log.WARN,
7891 "Error in package manager settings: <package> has no name at "
7892 + parser.getPositionDescription());
7893 } else if (codePathStr == null) {
7894 reportSettingsProblem(Log.WARN,
7895 "Error in package manager settings: <package> has no codePath at "
7896 + parser.getPositionDescription());
7897 } else if (userId > 0) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007898 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007899 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7901 + ": userId=" + userId + " pkg=" + packageSetting);
7902 if (packageSetting == null) {
7903 reportSettingsProblem(Log.ERROR,
7904 "Failure adding uid " + userId
7905 + " while parsing settings at "
7906 + parser.getPositionDescription());
7907 } else {
7908 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7909 }
7910 } else if (sharedIdStr != null) {
7911 userId = sharedIdStr != null
7912 ? Integer.parseInt(sharedIdStr) : 0;
7913 if (userId > 0) {
7914 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007915 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7917 mPendingPackages.add((PendingPackage) packageSetting);
7918 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7919 + ": sharedUserId=" + userId + " pkg="
7920 + packageSetting);
7921 } else {
7922 reportSettingsProblem(Log.WARN,
7923 "Error in package manager settings: package "
7924 + name + " has bad sharedId " + sharedIdStr
7925 + " at " + parser.getPositionDescription());
7926 }
7927 } else {
7928 reportSettingsProblem(Log.WARN,
7929 "Error in package manager settings: package "
7930 + name + " has bad userId " + idStr + " at "
7931 + parser.getPositionDescription());
7932 }
7933 } catch (NumberFormatException e) {
7934 reportSettingsProblem(Log.WARN,
7935 "Error in package manager settings: package "
7936 + name + " has bad userId " + idStr + " at "
7937 + parser.getPositionDescription());
7938 }
7939 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007940 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02007941 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007942 final String enabledStr = parser.getAttributeValue(null, "enabled");
7943 if (enabledStr != null) {
7944 if (enabledStr.equalsIgnoreCase("true")) {
7945 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7946 } else if (enabledStr.equalsIgnoreCase("false")) {
7947 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7948 } else if (enabledStr.equalsIgnoreCase("default")) {
7949 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7950 } else {
7951 reportSettingsProblem(Log.WARN,
7952 "Error in package manager settings: package "
7953 + name + " has bad enabled value: " + idStr
7954 + " at " + parser.getPositionDescription());
7955 }
7956 } else {
7957 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7958 }
7959 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7960 if (installStatusStr != null) {
7961 if (installStatusStr.equalsIgnoreCase("false")) {
7962 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7963 } else {
7964 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7965 }
7966 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 int outerDepth = parser.getDepth();
7969 int type;
7970 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7971 && (type != XmlPullParser.END_TAG
7972 || parser.getDepth() > outerDepth)) {
7973 if (type == XmlPullParser.END_TAG
7974 || type == XmlPullParser.TEXT) {
7975 continue;
7976 }
7977
7978 String tagName = parser.getName();
7979 if (tagName.equals("disabled-components")) {
7980 readDisabledComponentsLP(packageSetting, parser);
7981 } else if (tagName.equals("enabled-components")) {
7982 readEnabledComponentsLP(packageSetting, parser);
7983 } else if (tagName.equals("sigs")) {
7984 packageSetting.signatures.readXml(parser, mPastSignatures);
7985 } else if (tagName.equals("perms")) {
7986 readGrantedPermissionsLP(parser,
7987 packageSetting.loadedPermissions);
7988 packageSetting.permissionsFixed = true;
7989 } else {
7990 reportSettingsProblem(Log.WARN,
7991 "Unknown element under <package>: "
7992 + parser.getName());
7993 XmlUtils.skipCurrentTag(parser);
7994 }
7995 }
7996 } else {
7997 XmlUtils.skipCurrentTag(parser);
7998 }
7999 }
8000
8001 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8002 XmlPullParser parser)
8003 throws IOException, XmlPullParserException {
8004 int outerDepth = parser.getDepth();
8005 int type;
8006 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8007 && (type != XmlPullParser.END_TAG
8008 || parser.getDepth() > outerDepth)) {
8009 if (type == XmlPullParser.END_TAG
8010 || type == XmlPullParser.TEXT) {
8011 continue;
8012 }
8013
8014 String tagName = parser.getName();
8015 if (tagName.equals("item")) {
8016 String name = parser.getAttributeValue(null, "name");
8017 if (name != null) {
8018 packageSetting.disabledComponents.add(name.intern());
8019 } else {
8020 reportSettingsProblem(Log.WARN,
8021 "Error in package manager settings: <disabled-components> has"
8022 + " no name at " + parser.getPositionDescription());
8023 }
8024 } else {
8025 reportSettingsProblem(Log.WARN,
8026 "Unknown element under <disabled-components>: "
8027 + parser.getName());
8028 }
8029 XmlUtils.skipCurrentTag(parser);
8030 }
8031 }
8032
8033 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8034 XmlPullParser parser)
8035 throws IOException, XmlPullParserException {
8036 int outerDepth = parser.getDepth();
8037 int type;
8038 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8039 && (type != XmlPullParser.END_TAG
8040 || parser.getDepth() > outerDepth)) {
8041 if (type == XmlPullParser.END_TAG
8042 || type == XmlPullParser.TEXT) {
8043 continue;
8044 }
8045
8046 String tagName = parser.getName();
8047 if (tagName.equals("item")) {
8048 String name = parser.getAttributeValue(null, "name");
8049 if (name != null) {
8050 packageSetting.enabledComponents.add(name.intern());
8051 } else {
8052 reportSettingsProblem(Log.WARN,
8053 "Error in package manager settings: <enabled-components> has"
8054 + " no name at " + parser.getPositionDescription());
8055 }
8056 } else {
8057 reportSettingsProblem(Log.WARN,
8058 "Unknown element under <enabled-components>: "
8059 + parser.getName());
8060 }
8061 XmlUtils.skipCurrentTag(parser);
8062 }
8063 }
8064
8065 private void readSharedUserLP(XmlPullParser parser)
8066 throws XmlPullParserException, IOException {
8067 String name = null;
8068 String idStr = null;
8069 int pkgFlags = 0;
8070 SharedUserSetting su = null;
8071 try {
8072 name = parser.getAttributeValue(null, "name");
8073 idStr = parser.getAttributeValue(null, "userId");
8074 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8075 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8076 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8077 }
8078 if (name == null) {
8079 reportSettingsProblem(Log.WARN,
8080 "Error in package manager settings: <shared-user> has no name at "
8081 + parser.getPositionDescription());
8082 } else if (userId == 0) {
8083 reportSettingsProblem(Log.WARN,
8084 "Error in package manager settings: shared-user "
8085 + name + " has bad userId " + idStr + " at "
8086 + parser.getPositionDescription());
8087 } else {
8088 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8089 reportSettingsProblem(Log.ERROR,
8090 "Occurred while parsing settings at "
8091 + parser.getPositionDescription());
8092 }
8093 }
8094 } catch (NumberFormatException e) {
8095 reportSettingsProblem(Log.WARN,
8096 "Error in package manager settings: package "
8097 + name + " has bad userId " + idStr + " at "
8098 + parser.getPositionDescription());
8099 };
8100
8101 if (su != null) {
8102 int outerDepth = parser.getDepth();
8103 int type;
8104 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8105 && (type != XmlPullParser.END_TAG
8106 || parser.getDepth() > outerDepth)) {
8107 if (type == XmlPullParser.END_TAG
8108 || type == XmlPullParser.TEXT) {
8109 continue;
8110 }
8111
8112 String tagName = parser.getName();
8113 if (tagName.equals("sigs")) {
8114 su.signatures.readXml(parser, mPastSignatures);
8115 } else if (tagName.equals("perms")) {
8116 readGrantedPermissionsLP(parser, su.loadedPermissions);
8117 } else {
8118 reportSettingsProblem(Log.WARN,
8119 "Unknown element under <shared-user>: "
8120 + parser.getName());
8121 XmlUtils.skipCurrentTag(parser);
8122 }
8123 }
8124
8125 } else {
8126 XmlUtils.skipCurrentTag(parser);
8127 }
8128 }
8129
8130 private void readGrantedPermissionsLP(XmlPullParser parser,
8131 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8132 int outerDepth = parser.getDepth();
8133 int type;
8134 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8135 && (type != XmlPullParser.END_TAG
8136 || parser.getDepth() > outerDepth)) {
8137 if (type == XmlPullParser.END_TAG
8138 || type == XmlPullParser.TEXT) {
8139 continue;
8140 }
8141
8142 String tagName = parser.getName();
8143 if (tagName.equals("item")) {
8144 String name = parser.getAttributeValue(null, "name");
8145 if (name != null) {
8146 outPerms.add(name.intern());
8147 } else {
8148 reportSettingsProblem(Log.WARN,
8149 "Error in package manager settings: <perms> has"
8150 + " no name at " + parser.getPositionDescription());
8151 }
8152 } else {
8153 reportSettingsProblem(Log.WARN,
8154 "Unknown element under <perms>: "
8155 + parser.getName());
8156 }
8157 XmlUtils.skipCurrentTag(parser);
8158 }
8159 }
8160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008161 private void readPreferredActivitiesLP(XmlPullParser parser)
8162 throws XmlPullParserException, IOException {
8163 int outerDepth = parser.getDepth();
8164 int type;
8165 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8166 && (type != XmlPullParser.END_TAG
8167 || parser.getDepth() > outerDepth)) {
8168 if (type == XmlPullParser.END_TAG
8169 || type == XmlPullParser.TEXT) {
8170 continue;
8171 }
8172
8173 String tagName = parser.getName();
8174 if (tagName.equals("item")) {
8175 PreferredActivity pa = new PreferredActivity(parser);
8176 if (pa.mParseError == null) {
8177 mPreferredActivities.addFilter(pa);
8178 } else {
8179 reportSettingsProblem(Log.WARN,
8180 "Error in package manager settings: <preferred-activity> "
8181 + pa.mParseError + " at "
8182 + parser.getPositionDescription());
8183 }
8184 } else {
8185 reportSettingsProblem(Log.WARN,
8186 "Unknown element under <preferred-activities>: "
8187 + parser.getName());
8188 XmlUtils.skipCurrentTag(parser);
8189 }
8190 }
8191 }
8192
8193 // Returns -1 if we could not find an available UserId to assign
8194 private int newUserIdLP(Object obj) {
8195 // Let's be stupidly inefficient for now...
8196 final int N = mUserIds.size();
8197 for (int i=0; i<N; i++) {
8198 if (mUserIds.get(i) == null) {
8199 mUserIds.set(i, obj);
8200 return FIRST_APPLICATION_UID + i;
8201 }
8202 }
8203
8204 // None left?
8205 if (N >= MAX_APPLICATION_UIDS) {
8206 return -1;
8207 }
8208
8209 mUserIds.add(obj);
8210 return FIRST_APPLICATION_UID + N;
8211 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008213 public PackageSetting getDisabledSystemPkg(String name) {
8214 synchronized(mPackages) {
8215 PackageSetting ps = mDisabledSysPackages.get(name);
8216 return ps;
8217 }
8218 }
8219
8220 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8221 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8222 if (Config.LOGV) {
8223 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8224 + " componentName = " + componentInfo.name);
8225 Log.v(TAG, "enabledComponents: "
8226 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8227 Log.v(TAG, "disabledComponents: "
8228 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8229 }
8230 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8231 || ((componentInfo.enabled
8232 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8233 || (componentInfo.applicationInfo.enabled
8234 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8235 && !packageSettings.disabledComponents.contains(componentInfo.name))
8236 || packageSettings.enabledComponents.contains(componentInfo.name));
8237 }
8238 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008239
8240 // ------- apps on sdcard specific code -------
8241 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008242 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008243 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008244 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008245 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008246
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008247
8248 static MountService getMountService() {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008249 return (MountService) ServiceManager.getService("mount");
8250 }
8251
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008252 private String getEncryptKey() {
8253 try {
8254 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8255 if (sdEncKey == null) {
8256 sdEncKey = SystemKeyStore.getInstance().
8257 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8258 if (sdEncKey == null) {
8259 Log.e(TAG, "Failed to create encryption keys");
8260 return null;
8261 }
8262 }
8263 return sdEncKey;
8264 } catch (NoSuchAlgorithmException nsae) {
8265 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8266 return null;
8267 }
8268 }
8269
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008270 private String createSdDir(File tmpPackageFile, String pkgName) {
8271 // Create mount point via MountService
8272 MountService mountService = getMountService();
8273 long len = tmpPackageFile.length();
8274 int mbLen = (int) (len/(1024*1024));
8275 if ((len - (mbLen * 1024 * 1024)) > 0) {
8276 mbLen++;
8277 }
8278 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
8279 String cachePath = null;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008280 String sdEncKey;
8281 try {
8282 sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8283 if (sdEncKey == null) {
8284 sdEncKey = SystemKeyStore.getInstance().
8285 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8286 if (sdEncKey == null) {
8287 Log.e(TAG, "Failed to create encryption keys for package: " + pkgName + ".");
8288 return null;
8289 }
8290 }
8291 } catch (NoSuchAlgorithmException nsae) {
8292 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8293 return null;
8294 }
San Mehatbe16cb12010-01-29 05:35:35 -08008295
8296 int rc = mountService.createSecureContainer(
8297 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
San Mehatb1043402010-02-05 08:26:50 -08008298 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008299 Log.e(TAG, String.format("Failed to create container (%d)", rc));
8300
8301 rc = mountService.destroySecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008302 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008303 Log.e(TAG, String.format("Failed to cleanup container (%d)", rc));
8304 return null;
8305 }
8306 rc = mountService.createSecureContainer(
8307 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
San Mehatb1043402010-02-05 08:26:50 -08008308 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008309 Log.e(TAG, String.format("Failed to create container (2nd try) (%d)", rc));
8310 return null;
8311 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008312 }
San Mehatbe16cb12010-01-29 05:35:35 -08008313
8314 cachePath = mountService.getSecureContainerPath(pkgName);
8315 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008316 return cachePath;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008317 }
8318
8319 private String mountSdDir(String pkgName, int ownerUid) {
Oscar Montemayord02546b2010-01-14 16:38:40 -08008320 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8321 if (sdEncKey == null) {
8322 Log.e(TAG, "Failed to retrieve encryption keys to mount package code: " + pkgName + ".");
8323 return null;
8324 }
San Mehatbe16cb12010-01-29 05:35:35 -08008325
8326 int rc = getMountService().mountSecureContainer(pkgName, sdEncKey, ownerUid);
8327
San Mehatb1043402010-02-05 08:26:50 -08008328 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008329 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " rc : " + rc);
8330 return null;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008331 }
San Mehatbe16cb12010-01-29 05:35:35 -08008332
8333 return getMountService().getSecureContainerPath(pkgName);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008334 }
8335
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008336 private boolean unMountSdDir(String pkgName) {
8337 // STOPSHIP unmount directory
San Mehatbe16cb12010-01-29 05:35:35 -08008338 int rc = getMountService().unmountSecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008339 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008340 Log.e(TAG, "Failed to unmount : " + pkgName + " with rc " + rc);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008341 return false;
8342 }
San Mehatbe16cb12010-01-29 05:35:35 -08008343 return true;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008344 }
8345
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008346 private boolean renameSdDir(String oldId, String newId) {
8347 try {
8348 getMountService().renameSecureContainer(oldId, newId);
8349 return true;
8350 } catch (IllegalStateException e) {
8351 Log.i(TAG, "Failed ot rename " + oldId + " to " + newId +
8352 " with exception : " + e);
8353 }
8354 return false;
8355 }
8356
8357 private String getSdDir(String pkgName) {
8358 return getMountService().getSecureContainerPath(pkgName);
8359 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008360
San Mehatbe16cb12010-01-29 05:35:35 -08008361 private boolean finalizeSdDir(String pkgName) {
8362 int rc = getMountService().finalizeSecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008363 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008364 Log.i(TAG, "Failed to finalize container for pkg : " + pkgName);
8365 return false;
8366 }
8367 return true;
8368 }
8369
8370 private boolean destroySdDir(String pkgName) {
8371 int rc = getMountService().destroySecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008372 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008373 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
8374 return false;
8375 }
8376 return true;
8377 }
8378
8379 static String[] getSecureContainerList() {
8380 String[] list = getMountService().getSecureContainerList();
8381 return list.length == 0 ? null : list;
8382 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008383
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008384 static boolean isContainerMounted(String cid) {
8385 // STOPSHIP
8386 // New api from MountService
8387 try {
8388 return (getMountService().getSecureContainerPath(cid) != null);
8389 } catch (IllegalStateException e) {
8390 }
8391 return false;
8392 }
8393
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008394 static String getTempContainerId() {
8395 String prefix = "smdl1tmp";
8396 int tmpIdx = 1;
8397 String list[] = getSecureContainerList();
8398 if (list != null) {
8399 int idx = 0;
8400 int idList[] = new int[MAX_CONTAINERS];
8401 boolean neverFound = true;
8402 for (String name : list) {
8403 // Ignore null entries
8404 if (name == null) {
8405 continue;
8406 }
8407 int sidx = name.indexOf(prefix);
8408 if (sidx == -1) {
8409 // Not a temp file. just ignore
8410 continue;
8411 }
8412 String subStr = name.substring(sidx + prefix.length());
8413 idList[idx] = -1;
8414 if (subStr != null) {
8415 try {
8416 int cid = Integer.parseInt(subStr);
8417 idList[idx++] = cid;
8418 neverFound = false;
8419 } catch (NumberFormatException e) {
8420 }
8421 }
8422 }
8423 if (!neverFound) {
8424 // Sort idList
8425 Arrays.sort(idList);
8426 for (int j = 1; j <= idList.length; j++) {
8427 if (idList[j-1] != j) {
8428 tmpIdx = j;
8429 break;
8430 }
8431 }
8432 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008433 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008434 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008435 }
8436
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008437 public void updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008438 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8439 mediaStatus+", mMediaMounted=" + mMediaMounted);
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008440 if (mediaStatus == mMediaMounted) {
8441 return;
8442 }
8443 mMediaMounted = mediaStatus;
8444 // Queue up an async operation since the package installation may take a little while.
8445 mHandler.post(new Runnable() {
8446 public void run() {
8447 mHandler.removeCallbacks(this);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008448 updateExternalMediaStatusInner(mediaStatus);
8449 }
8450 });
8451 }
8452
8453 void updateExternalMediaStatusInner(boolean mediaStatus) {
8454 final String list[] = getSecureContainerList();
8455 if (list == null || list.length == 0) {
8456 return;
8457 }
8458 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8459 int uidList[] = new int[list.length];
8460 int num = 0;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008461 synchronized (mPackages) {
8462 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8463 for (String cid : list) {
8464 SdInstallArgs args = new SdInstallArgs(cid);
8465 String removeEntry = null;
8466 for (String app : appList) {
8467 if (args.matchContainer(app)) {
8468 removeEntry = app;
8469 break;
8470 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008471 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008472 if (removeEntry == null) {
8473 // No matching app on device. Skip entry or may be cleanup?
8474 // Ignore default package
8475 continue;
8476 }
8477 appList.remove(removeEntry);
8478 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8479 processCids.put(args, ps.codePathString);
8480 int uid = ps.userId;
8481 if (uid != -1) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008482 uidList[num++] = uid;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008483 }
8484 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008485 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008486 int uidArr[] = null;
8487 if (num > 0) {
8488 // Sort uid list
8489 Arrays.sort(uidList, 0, num);
8490 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008491 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008492 uidArr[0] = uidList[0];
8493 int di = 0;
8494 for (int i = 1; i < num; i++) {
8495 if (uidList[i-1] != uidList[i]) {
8496 uidArr[di++] = uidList[i];
8497 }
8498 }
8499 if (true) {
8500 for (int j = 0; j < num; j++) {
8501 Log.i(TAG, "uidArr[" + j + "]=" + uidArr[j]);
8502 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008503 }
8504 }
8505 if (mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008506 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008507 loadMediaPackages(processCids, uidArr);
8508 } else {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008509 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008510 unloadMediaPackages(processCids, uidArr);
8511 }
8512 }
8513
8514 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8515 ArrayList<String> pkgList, int uidArr[]) {
8516 int size = pkgList.size();
8517 if (size > 0) {
8518 // Send broadcasts here
8519 Bundle extras = new Bundle();
8520 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8521 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008522 if (uidArr != null) {
8523 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8524 }
8525 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8526 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008527 sendPackageBroadcast(action, null, extras);
8528 }
8529 }
8530
8531 void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8532 ArrayList<String> pkgList = new ArrayList<String>();
8533 Set<SdInstallArgs> keys = processCids.keySet();
8534 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008535 String codePath = processCids.get(args);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008536 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install pkg : "
8537 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008538 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008539 Log.e(TAG, "Failed to install package: " + codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008540 continue;
8541 }
8542 // Parse package
8543 int parseFlags = PackageParser.PARSE_CHATTY |
8544 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8545 PackageParser pp = new PackageParser(codePath);
8546 pp.setSeparateProcesses(mSeparateProcesses);
8547 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
8548 codePath, mMetrics, parseFlags);
8549 if (pkg == null) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008550 Log.e(TAG, "Trying to install pkg : "
8551 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008552 continue;
8553 }
8554 setApplicationInfoPaths(pkg, codePath, codePath);
8555 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8556 synchronized (mInstallLock) {
8557 // Scan the package
8558 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
8559 synchronized (mPackages) {
8560 // Grant permissions
8561 grantPermissionsLP(pkg, false);
8562 // Persist settings
8563 mSettings.writeLP();
8564 retCode = PackageManager.INSTALL_SUCCEEDED;
8565 pkgList.add(pkg.packageName);
8566 }
8567 } else {
8568 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
8569 }
8570 }
8571 args.doPostInstall(retCode);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008572 }
8573 // Send broadcasts first
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008574 if (pkgList.size() > 0) {
8575 sendResourcesChangedBroadcast(true, pkgList, uidArr);
8576 Runtime.getRuntime().gc();
8577 // If something failed do we clean up here or next install?
8578 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008579 }
8580
8581 void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008582 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008583 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008584 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008585 Set<SdInstallArgs> keys = processCids.keySet();
8586 for (SdInstallArgs args : keys) {
8587 String cid = args.cid;
8588 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008589 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008590 // Delete package internally
8591 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8592 synchronized (mInstallLock) {
8593 boolean res = deletePackageLI(pkgName, false,
8594 PackageManager.DONT_DELETE_DATA, outInfo);
8595 if (res) {
8596 pkgList.add(pkgName);
8597 } else {
8598 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008599 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008600 }
8601 }
8602 }
8603 // Send broadcasts
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008604 if (pkgList.size() > 0) {
8605 sendResourcesChangedBroadcast(false, pkgList, uidArr);
8606 Runtime.getRuntime().gc();
8607 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008608 // Do clean up. Just unmount
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008609 for (SdInstallArgs args : failedList) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008610 synchronized (mInstallLock) {
8611 args.doPostDeleteLI(false);
8612 }
8613 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615}