blob: 6289d4f8f54e056564a7f66714b85ae560f9e2ea [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
19import com.android.internal.app.ResolverActivity;
20import com.android.internal.util.FastXmlSerializer;
21import com.android.internal.util.XmlUtils;
22
23import org.xmlpull.v1.XmlPullParser;
24import org.xmlpull.v1.XmlPullParserException;
25import org.xmlpull.v1.XmlSerializer;
26
27import android.app.ActivityManagerNative;
28import android.app.IActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070033import android.content.IntentSender;
34import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.pm.ActivityInfo;
36import android.content.pm.ApplicationInfo;
37import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070038import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.pm.IPackageDataObserver;
40import android.content.pm.IPackageDeleteObserver;
41import android.content.pm.IPackageInstallObserver;
42import android.content.pm.IPackageManager;
43import android.content.pm.IPackageStatsObserver;
44import android.content.pm.InstrumentationInfo;
45import android.content.pm.PackageInfo;
46import android.content.pm.PackageManager;
47import android.content.pm.PackageStats;
48import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
49import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
50import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
51import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
52import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
53import android.content.pm.PackageParser;
54import android.content.pm.PermissionInfo;
55import android.content.pm.PermissionGroupInfo;
56import android.content.pm.ProviderInfo;
57import android.content.pm.ResolveInfo;
58import android.content.pm.ServiceInfo;
59import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.Uri;
61import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070062import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.os.Bundle;
64import android.os.HandlerThread;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070065import android.os.Looper;
66import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.os.Parcel;
68import android.os.RemoteException;
69import android.os.Environment;
70import android.os.FileObserver;
71import android.os.FileUtils;
72import android.os.Handler;
73import android.os.ParcelFileDescriptor;
74import android.os.Process;
75import android.os.ServiceManager;
76import android.os.SystemClock;
77import android.os.SystemProperties;
78import android.util.*;
79import android.view.Display;
80import android.view.WindowManager;
81
82import java.io.File;
83import java.io.FileDescriptor;
84import java.io.FileInputStream;
85import java.io.FileNotFoundException;
86import java.io.FileOutputStream;
87import java.io.FileReader;
88import java.io.FilenameFilter;
89import java.io.IOException;
90import java.io.InputStream;
91import java.io.PrintWriter;
92import java.util.ArrayList;
93import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -070094import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.util.Collections;
96import java.util.Comparator;
97import java.util.Enumeration;
98import java.util.HashMap;
99import java.util.HashSet;
100import java.util.Iterator;
101import java.util.List;
102import java.util.Map;
103import java.util.Set;
104import java.util.zip.ZipEntry;
105import java.util.zip.ZipFile;
106import java.util.zip.ZipOutputStream;
107
108class PackageManagerService extends IPackageManager.Stub {
109 private static final String TAG = "PackageManager";
110 private static final boolean DEBUG_SETTINGS = false;
111 private static final boolean DEBUG_PREFERRED = false;
112
113 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
114 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400115 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 private static final int FIRST_APPLICATION_UID =
117 Process.FIRST_APPLICATION_UID;
118 private static final int MAX_APPLICATION_UIDS = 1000;
119
120 private static final boolean SHOW_INFO = false;
121
122 private static final boolean GET_CERTIFICATES = true;
123
124 private static final int REMOVE_EVENTS =
125 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
126 private static final int ADD_EVENTS =
127 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
128
129 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
130
131 static final int SCAN_MONITOR = 1<<0;
132 static final int SCAN_NO_DEX = 1<<1;
133 static final int SCAN_FORCE_DEX = 1<<2;
134 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
135 static final int SCAN_FORWARD_LOCKED = 1<<4;
The Android Open Source Project10592532009-03-18 17:39:46 -0700136 static final int SCAN_NEW_INSTALL = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137
138 static final int LOG_BOOT_PROGRESS_PMS_START = 3060;
139 static final int LOG_BOOT_PROGRESS_PMS_SYSTEM_SCAN_START = 3070;
140 static final int LOG_BOOT_PROGRESS_PMS_DATA_SCAN_START = 3080;
141 static final int LOG_BOOT_PROGRESS_PMS_SCAN_END = 3090;
142 static final int LOG_BOOT_PROGRESS_PMS_READY = 3100;
143
144 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
145 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700146 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
Dianne Hackborn851a5412009-05-08 12:06:44 -0700148 final int mSdkVersion = Build.VERSION.SDK_INT;
149 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
150 ? null : Build.VERSION.CODENAME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
152 final Context mContext;
153 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700154 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 final DisplayMetrics mMetrics;
156 final int mDefParseFlags;
157 final String[] mSeparateProcesses;
158
159 // This is where all application persistent data goes.
160 final File mAppDataDir;
161
162 // This is the object monitoring the framework dir.
163 final FileObserver mFrameworkInstallObserver;
164
165 // This is the object monitoring the system app dir.
166 final FileObserver mSystemInstallObserver;
167
168 // This is the object monitoring mAppInstallDir.
169 final FileObserver mAppInstallObserver;
170
171 // This is the object monitoring mDrmAppPrivateInstallDir.
172 final FileObserver mDrmAppInstallObserver;
173
174 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
175 // LOCK HELD. Can be called with mInstallLock held.
176 final Installer mInstaller;
177
178 final File mFrameworkDir;
179 final File mSystemAppDir;
180 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700181 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
183 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
184 // apps.
185 final File mDrmAppPrivateInstallDir;
186
187 // ----------------------------------------------------------------
188
189 // Lock for state used when installing and doing other long running
190 // operations. Methods that must be called with this lock held have
191 // the prefix "LI".
192 final Object mInstallLock = new Object();
193
194 // These are the directories in the 3rd party applications installed dir
195 // that we have currently loaded packages from. Keys are the application's
196 // installed zip file (absolute codePath), and values are Package.
197 final HashMap<String, PackageParser.Package> mAppDirs =
198 new HashMap<String, PackageParser.Package>();
199
200 // Information for the parser to write more useful error messages.
201 File mScanningPath;
202 int mLastScanError;
203
204 final int[] mOutPermissions = new int[3];
205
206 // ----------------------------------------------------------------
207
208 // Keys are String (package name), values are Package. This also serves
209 // as the lock for the global state. Methods that must be called with
210 // this lock held have the prefix "LP".
211 final HashMap<String, PackageParser.Package> mPackages =
212 new HashMap<String, PackageParser.Package>();
213
214 final Settings mSettings;
215 boolean mRestoredSettings;
216 boolean mReportedUidError;
217
218 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
219 int[] mGlobalGids;
220
221 // These are the built-in uid -> permission mappings that were read from the
222 // etc/permissions.xml file.
223 final SparseArray<HashSet<String>> mSystemPermissions =
224 new SparseArray<HashSet<String>>();
225
226 // These are the built-in shared libraries that were read from the
227 // etc/permissions.xml file.
228 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
229
Dianne Hackborn49237342009-08-27 20:08:01 -0700230 // Temporary for building the final shared libraries for an .apk.
231 String[] mTmpSharedLibraries = null;
232
233 // These are the features this devices supports that were read from the
234 // etc/permissions.xml file.
235 final HashMap<String, FeatureInfo> mAvailableFeatures =
236 new HashMap<String, FeatureInfo>();
237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 // All available activities, for your resolving pleasure.
239 final ActivityIntentResolver mActivities =
240 new ActivityIntentResolver();
241
242 // All available receivers, for your resolving pleasure.
243 final ActivityIntentResolver mReceivers =
244 new ActivityIntentResolver();
245
246 // All available services, for your resolving pleasure.
247 final ServiceIntentResolver mServices = new ServiceIntentResolver();
248
249 // Keys are String (provider class name), values are Provider.
250 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
251 new HashMap<ComponentName, PackageParser.Provider>();
252
253 // Mapping from provider base names (first directory in content URI codePath)
254 // to the provider information.
255 final HashMap<String, PackageParser.Provider> mProviders =
256 new HashMap<String, PackageParser.Provider>();
257
258 // Mapping from instrumentation class names to info about them.
259 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
260 new HashMap<ComponentName, PackageParser.Instrumentation>();
261
262 // Mapping from permission names to info about them.
263 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
264 new HashMap<String, PackageParser.PermissionGroup>();
265
Dianne Hackborn854060af2009-07-09 18:14:31 -0700266 // Broadcast actions that are only available to the system.
267 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 boolean mSystemReady;
270 boolean mSafeMode;
271 boolean mHasSystemUidErrors;
272
273 ApplicationInfo mAndroidApplication;
274 final ActivityInfo mResolveActivity = new ActivityInfo();
275 final ResolveInfo mResolveInfo = new ResolveInfo();
276 ComponentName mResolveComponentName;
277 PackageParser.Package mPlatformPackage;
278
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700279 // Set of pending broadcasts for aggregating enable/disable of components.
280 final HashMap<String, String> mPendingBroadcasts = new HashMap<String, String>();
281 static final int SEND_PENDING_BROADCAST = 1;
282 // Delay time in millisecs
283 static final int BROADCAST_DELAY = 10 * 1000;
284
285 class PackageHandler extends Handler {
286 PackageHandler(Looper looper) {
287 super(looper);
288 }
289 public void handleMessage(Message msg) {
290 switch (msg.what) {
291 case SEND_PENDING_BROADCAST : {
292 int size = 0;
293 String broadcastList[];
294 HashMap<String, String> tmpMap;
295 int uids[];
296 synchronized (mPackages) {
297 size = mPendingBroadcasts.size();
298 if (size <= 0) {
299 // Nothing to be done. Just return
300 return;
301 }
302 broadcastList = new String[size];
303 mPendingBroadcasts.keySet().toArray(broadcastList);
304 tmpMap = new HashMap<String, String>(mPendingBroadcasts);
305 uids = new int[size];
306 for (int i = 0; i < size; i++) {
307 PackageSetting ps = mSettings.mPackages.get(mPendingBroadcasts.get(broadcastList[i]));
308 uids[i] = (ps != null) ? ps.userId : -1;
309 }
310 mPendingBroadcasts.clear();
311 }
312 // Send broadcasts
313 for (int i = 0; i < size; i++) {
314 String className = broadcastList[i];
315 sendPackageChangedBroadcast(className, true, tmpMap.get(className), uids[i]);
316 }
317 break;
318 }
319 }
320 }
321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 public static final IPackageManager main(Context context, boolean factoryTest) {
323 PackageManagerService m = new PackageManagerService(context, factoryTest);
324 ServiceManager.addService("package", m);
325 return m;
326 }
327
328 static String[] splitString(String str, char sep) {
329 int count = 1;
330 int i = 0;
331 while ((i=str.indexOf(sep, i)) >= 0) {
332 count++;
333 i++;
334 }
335
336 String[] res = new String[count];
337 i=0;
338 count = 0;
339 int lastI=0;
340 while ((i=str.indexOf(sep, i)) >= 0) {
341 res[count] = str.substring(lastI, i);
342 count++;
343 i++;
344 lastI = i;
345 }
346 res[count] = str.substring(lastI, str.length());
347 return res;
348 }
349
350 public PackageManagerService(Context context, boolean factoryTest) {
351 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_START,
352 SystemClock.uptimeMillis());
353
354 if (mSdkVersion <= 0) {
355 Log.w(TAG, "**** ro.build.version.sdk not set!");
356 }
357
358 mContext = context;
359 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700360 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 mMetrics = new DisplayMetrics();
362 mSettings = new Settings();
363 mSettings.addSharedUserLP("android.uid.system",
364 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
365 mSettings.addSharedUserLP("android.uid.phone",
366 MULTIPLE_APPLICATION_UIDS
367 ? RADIO_UID : FIRST_APPLICATION_UID,
368 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400369 mSettings.addSharedUserLP("android.uid.log",
370 MULTIPLE_APPLICATION_UIDS
371 ? LOG_UID : FIRST_APPLICATION_UID,
372 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800373
374 String separateProcesses = SystemProperties.get("debug.separate_processes");
375 if (separateProcesses != null && separateProcesses.length() > 0) {
376 if ("*".equals(separateProcesses)) {
377 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
378 mSeparateProcesses = null;
379 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
380 } else {
381 mDefParseFlags = 0;
382 mSeparateProcesses = separateProcesses.split(",");
383 Log.w(TAG, "Running with debug.separate_processes: "
384 + separateProcesses);
385 }
386 } else {
387 mDefParseFlags = 0;
388 mSeparateProcesses = null;
389 }
390
391 Installer installer = new Installer();
392 // Little hacky thing to check if installd is here, to determine
393 // whether we are running on the simulator and thus need to take
394 // care of building the /data file structure ourself.
395 // (apparently the sim now has a working installer)
396 if (installer.ping() && Process.supportsProcesses()) {
397 mInstaller = installer;
398 } else {
399 mInstaller = null;
400 }
401
402 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
403 Display d = wm.getDefaultDisplay();
404 d.getMetrics(mMetrics);
405
406 synchronized (mInstallLock) {
407 synchronized (mPackages) {
408 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700409 mHandler = new PackageHandler(mHandlerThread.getLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410
411 File dataDir = Environment.getDataDirectory();
412 mAppDataDir = new File(dataDir, "data");
413 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
414
415 if (mInstaller == null) {
416 // Make sure these dirs exist, when we are running in
417 // the simulator.
418 // Make a wide-open directory for random misc stuff.
419 File miscDir = new File(dataDir, "misc");
420 miscDir.mkdirs();
421 mAppDataDir.mkdirs();
422 mDrmAppPrivateInstallDir.mkdirs();
423 }
424
425 readPermissions();
426
427 mRestoredSettings = mSettings.readLP();
428 long startTime = SystemClock.uptimeMillis();
429
430 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
431 startTime);
432
433 int scanMode = SCAN_MONITOR;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700434 if (mNoDexOpt) {
435 Log.w(TAG, "Running ENG build: no pre-dexopt!");
436 scanMode |= SCAN_NO_DEX;
437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438
439 final HashSet<String> libFiles = new HashSet<String>();
440
441 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700442 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443
444 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700445 boolean didDexOpt = false;
446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 /**
448 * Out of paranoia, ensure that everything in the boot class
449 * path has been dexed.
450 */
451 String bootClassPath = System.getProperty("java.boot.class.path");
452 if (bootClassPath != null) {
453 String[] paths = splitString(bootClassPath, ':');
454 for (int i=0; i<paths.length; i++) {
455 try {
456 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
457 libFiles.add(paths[i]);
458 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700459 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 }
461 } catch (FileNotFoundException e) {
462 Log.w(TAG, "Boot class path not found: " + paths[i]);
463 } catch (IOException e) {
464 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
465 }
466 }
467 } else {
468 Log.w(TAG, "No BOOTCLASSPATH found!");
469 }
470
471 /**
472 * Also ensure all external libraries have had dexopt run on them.
473 */
474 if (mSharedLibraries.size() > 0) {
475 Iterator<String> libs = mSharedLibraries.values().iterator();
476 while (libs.hasNext()) {
477 String lib = libs.next();
478 try {
479 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
480 libFiles.add(lib);
481 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700482 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 }
484 } catch (FileNotFoundException e) {
485 Log.w(TAG, "Library not found: " + lib);
486 } catch (IOException e) {
487 Log.w(TAG, "Exception reading library: " + lib, e);
488 }
489 }
490 }
491
492 // Gross hack for now: we know this file doesn't contain any
493 // code, so don't dexopt it to avoid the resulting log spew.
494 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
495
496 /**
497 * And there are a number of commands implemented in Java, which
498 * we currently need to do the dexopt on so that they can be
499 * run from a non-root shell.
500 */
501 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700502 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 for (int i=0; i<frameworkFiles.length; i++) {
504 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
505 String path = libPath.getPath();
506 // Skip the file if we alrady did it.
507 if (libFiles.contains(path)) {
508 continue;
509 }
510 // Skip the file if it is not a type we want to dexopt.
511 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
512 continue;
513 }
514 try {
515 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
516 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700517 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 }
519 } catch (FileNotFoundException e) {
520 Log.w(TAG, "Jar not found: " + path);
521 } catch (IOException e) {
522 Log.w(TAG, "Exception reading jar: " + path, e);
523 }
524 }
525 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700526
527 if (didDexOpt) {
528 // If we had to do a dexopt of one of the previous
529 // things, then something on the system has changed.
530 // Consider this significant, and wipe away all other
531 // existing dexopt files to ensure we don't leave any
532 // dangling around.
533 String[] files = mDalvikCacheDir.list();
534 if (files != null) {
535 for (int i=0; i<files.length; i++) {
536 String fn = files[i];
537 if (fn.startsWith("data@app@")
538 || fn.startsWith("data@app-private@")) {
539 Log.i(TAG, "Pruning dalvik file: " + fn);
540 (new File(mDalvikCacheDir, fn)).delete();
541 }
542 }
543 }
544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 }
546
547 mFrameworkInstallObserver = new AppDirObserver(
548 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
549 mFrameworkInstallObserver.startWatching();
550 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
551 scanMode | SCAN_NO_DEX);
552 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
553 mSystemInstallObserver = new AppDirObserver(
554 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
555 mSystemInstallObserver.startWatching();
556 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
557 mAppInstallDir = new File(dataDir, "app");
558 if (mInstaller == null) {
559 // Make sure these dirs exist, when we are running in
560 // the simulator.
561 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
562 }
563 //look for any incomplete package installations
564 ArrayList<String> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
565 //clean up list
566 for(int i = 0; i < deletePkgsList.size(); i++) {
567 //clean up here
568 cleanupInstallFailedPackage(deletePkgsList.get(i));
569 }
570 //delete tmp files
571 deleteTempPackageFiles();
572
573 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_DATA_SCAN_START,
574 SystemClock.uptimeMillis());
575 mAppInstallObserver = new AppDirObserver(
576 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
577 mAppInstallObserver.startWatching();
578 scanDirLI(mAppInstallDir, 0, scanMode);
579
580 mDrmAppInstallObserver = new AppDirObserver(
581 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
582 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -0700583 scanDirLI(mDrmAppPrivateInstallDir, 0, scanMode | SCAN_FORWARD_LOCKED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
585 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_SCAN_END,
586 SystemClock.uptimeMillis());
587 Log.i(TAG, "Time to scan packages: "
588 + ((SystemClock.uptimeMillis()-startTime)/1000f)
589 + " seconds");
590
591 updatePermissionsLP();
592
593 mSettings.writeLP();
594
595 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_READY,
596 SystemClock.uptimeMillis());
597
598 // Now after opening every single application zip, make sure they
599 // are all flushed. Not really needed, but keeps things nice and
600 // tidy.
601 Runtime.getRuntime().gc();
602 } // synchronized (mPackages)
603 } // synchronized (mInstallLock)
604 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 @Override
607 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
608 throws RemoteException {
609 try {
610 return super.onTransact(code, data, reply, flags);
611 } catch (RuntimeException e) {
612 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
613 Log.e(TAG, "Package Manager Crash", e);
614 }
615 throw e;
616 }
617 }
618
619 void cleanupInstallFailedPackage(String packageName) {
620 if (mInstaller != null) {
621 int retCode = mInstaller.remove(packageName);
622 if (retCode < 0) {
623 Log.w(TAG, "Couldn't remove app data directory for package: "
624 + packageName + ", retcode=" + retCode);
625 }
626 } else {
627 //for emulator
628 PackageParser.Package pkg = mPackages.get(packageName);
629 File dataDir = new File(pkg.applicationInfo.dataDir);
630 dataDir.delete();
631 }
632 mSettings.removePackageLP(packageName);
633 }
634
635 void readPermissions() {
636 // Read permissions from .../etc/permission directory.
637 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
638 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
639 Log.w(TAG, "No directory " + libraryDir + ", skipping");
640 return;
641 }
642 if (!libraryDir.canRead()) {
643 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
644 return;
645 }
646
647 // Iterate over the files in the directory and scan .xml files
648 for (File f : libraryDir.listFiles()) {
649 // We'll read platform.xml last
650 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
651 continue;
652 }
653
654 if (!f.getPath().endsWith(".xml")) {
655 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
656 continue;
657 }
658 if (!f.canRead()) {
659 Log.w(TAG, "Permissions library file " + f + " cannot be read");
660 continue;
661 }
662
663 readPermissionsFromXml(f);
664 }
665
666 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
667 final File permFile = new File(Environment.getRootDirectory(),
668 "etc/permissions/platform.xml");
669 readPermissionsFromXml(permFile);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700670
671 StringBuilder sb = new StringBuilder(128);
672 sb.append("Libs:");
673 Iterator<String> it = mSharedLibraries.keySet().iterator();
674 while (it.hasNext()) {
675 sb.append(' ');
676 String name = it.next();
677 sb.append(name);
678 sb.append(':');
679 sb.append(mSharedLibraries.get(name));
680 }
681 Log.i(TAG, sb.toString());
682
683 sb.setLength(0);
684 sb.append("Features:");
685 it = mAvailableFeatures.keySet().iterator();
686 while (it.hasNext()) {
687 sb.append(' ');
688 sb.append(it.next());
689 }
690 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 }
692
693 private void readPermissionsFromXml(File permFile) {
694 FileReader permReader = null;
695 try {
696 permReader = new FileReader(permFile);
697 } catch (FileNotFoundException e) {
698 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
699 return;
700 }
701
702 try {
703 XmlPullParser parser = Xml.newPullParser();
704 parser.setInput(permReader);
705
706 XmlUtils.beginDocument(parser, "permissions");
707
708 while (true) {
709 XmlUtils.nextElement(parser);
710 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
711 break;
712 }
713
714 String name = parser.getName();
715 if ("group".equals(name)) {
716 String gidStr = parser.getAttributeValue(null, "gid");
717 if (gidStr != null) {
718 int gid = Integer.parseInt(gidStr);
719 mGlobalGids = appendInt(mGlobalGids, gid);
720 } else {
721 Log.w(TAG, "<group> without gid at "
722 + parser.getPositionDescription());
723 }
724
725 XmlUtils.skipCurrentTag(parser);
726 continue;
727 } else if ("permission".equals(name)) {
728 String perm = parser.getAttributeValue(null, "name");
729 if (perm == null) {
730 Log.w(TAG, "<permission> without name at "
731 + parser.getPositionDescription());
732 XmlUtils.skipCurrentTag(parser);
733 continue;
734 }
735 perm = perm.intern();
736 readPermission(parser, perm);
737
738 } else if ("assign-permission".equals(name)) {
739 String perm = parser.getAttributeValue(null, "name");
740 if (perm == null) {
741 Log.w(TAG, "<assign-permission> without name at "
742 + parser.getPositionDescription());
743 XmlUtils.skipCurrentTag(parser);
744 continue;
745 }
746 String uidStr = parser.getAttributeValue(null, "uid");
747 if (uidStr == null) {
748 Log.w(TAG, "<assign-permission> without uid at "
749 + parser.getPositionDescription());
750 XmlUtils.skipCurrentTag(parser);
751 continue;
752 }
753 int uid = Process.getUidForName(uidStr);
754 if (uid < 0) {
755 Log.w(TAG, "<assign-permission> with unknown uid \""
756 + uidStr + "\" at "
757 + parser.getPositionDescription());
758 XmlUtils.skipCurrentTag(parser);
759 continue;
760 }
761 perm = perm.intern();
762 HashSet<String> perms = mSystemPermissions.get(uid);
763 if (perms == null) {
764 perms = new HashSet<String>();
765 mSystemPermissions.put(uid, perms);
766 }
767 perms.add(perm);
768 XmlUtils.skipCurrentTag(parser);
769
770 } else if ("library".equals(name)) {
771 String lname = parser.getAttributeValue(null, "name");
772 String lfile = parser.getAttributeValue(null, "file");
773 if (lname == null) {
774 Log.w(TAG, "<library> without name at "
775 + parser.getPositionDescription());
776 } else if (lfile == null) {
777 Log.w(TAG, "<library> without file at "
778 + parser.getPositionDescription());
779 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700780 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700781 mSharedLibraries.put(lname, lfile);
782 }
783 XmlUtils.skipCurrentTag(parser);
784 continue;
785
786 } else if ("feature".equals(name)) {
787 String fname = parser.getAttributeValue(null, "name");
788 if (fname == null) {
789 Log.w(TAG, "<feature> without name at "
790 + parser.getPositionDescription());
791 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700792 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700793 FeatureInfo fi = new FeatureInfo();
794 fi.name = fname;
795 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
797 XmlUtils.skipCurrentTag(parser);
798 continue;
799
800 } else {
801 XmlUtils.skipCurrentTag(parser);
802 continue;
803 }
804
805 }
806 } catch (XmlPullParserException e) {
807 Log.w(TAG, "Got execption parsing permissions.", e);
808 } catch (IOException e) {
809 Log.w(TAG, "Got execption parsing permissions.", e);
810 }
811 }
812
813 void readPermission(XmlPullParser parser, String name)
814 throws IOException, XmlPullParserException {
815
816 name = name.intern();
817
818 BasePermission bp = mSettings.mPermissions.get(name);
819 if (bp == null) {
820 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
821 mSettings.mPermissions.put(name, bp);
822 }
823 int outerDepth = parser.getDepth();
824 int type;
825 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
826 && (type != XmlPullParser.END_TAG
827 || parser.getDepth() > outerDepth)) {
828 if (type == XmlPullParser.END_TAG
829 || type == XmlPullParser.TEXT) {
830 continue;
831 }
832
833 String tagName = parser.getName();
834 if ("group".equals(tagName)) {
835 String gidStr = parser.getAttributeValue(null, "gid");
836 if (gidStr != null) {
837 int gid = Process.getGidForName(gidStr);
838 bp.gids = appendInt(bp.gids, gid);
839 } else {
840 Log.w(TAG, "<group> without gid at "
841 + parser.getPositionDescription());
842 }
843 }
844 XmlUtils.skipCurrentTag(parser);
845 }
846 }
847
848 static int[] appendInt(int[] cur, int val) {
849 if (cur == null) {
850 return new int[] { val };
851 }
852 final int N = cur.length;
853 for (int i=0; i<N; i++) {
854 if (cur[i] == val) {
855 return cur;
856 }
857 }
858 int[] ret = new int[N+1];
859 System.arraycopy(cur, 0, ret, 0, N);
860 ret[N] = val;
861 return ret;
862 }
863
864 static int[] appendInts(int[] cur, int[] add) {
865 if (add == null) return cur;
866 if (cur == null) return add;
867 final int N = add.length;
868 for (int i=0; i<N; i++) {
869 cur = appendInt(cur, add[i]);
870 }
871 return cur;
872 }
873
874 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
875 final PackageSetting ps = (PackageSetting)p.mExtras;
876 if (ps == null) {
877 return null;
878 }
879 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
880 return PackageParser.generatePackageInfo(p, gp.gids, flags);
881 }
882
883 public PackageInfo getPackageInfo(String packageName, int flags) {
884 synchronized (mPackages) {
885 PackageParser.Package p = mPackages.get(packageName);
886 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700887 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 + ": " + p);
889 if (p != null) {
890 return generatePackageInfo(p, flags);
891 }
892 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
893 return generatePackageInfoFromSettingsLP(packageName, flags);
894 }
895 }
896 return null;
897 }
898
899 public int getPackageUid(String packageName) {
900 synchronized (mPackages) {
901 PackageParser.Package p = mPackages.get(packageName);
902 if(p != null) {
903 return p.applicationInfo.uid;
904 }
905 PackageSetting ps = mSettings.mPackages.get(packageName);
906 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
907 return -1;
908 }
909 p = ps.pkg;
910 return p != null ? p.applicationInfo.uid : -1;
911 }
912 }
913
914 public int[] getPackageGids(String packageName) {
915 synchronized (mPackages) {
916 PackageParser.Package p = mPackages.get(packageName);
917 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700918 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 + ": " + p);
920 if (p != null) {
921 final PackageSetting ps = (PackageSetting)p.mExtras;
922 final SharedUserSetting suid = ps.sharedUser;
923 return suid != null ? suid.gids : ps.gids;
924 }
925 }
926 // stupid thing to indicate an error.
927 return new int[0];
928 }
929
930 public PermissionInfo getPermissionInfo(String name, int flags) {
931 synchronized (mPackages) {
932 final BasePermission p = mSettings.mPermissions.get(name);
933 if (p != null && p.perm != null) {
934 return PackageParser.generatePermissionInfo(p.perm, flags);
935 }
936 return null;
937 }
938 }
939
940 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
941 synchronized (mPackages) {
942 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
943 for (BasePermission p : mSettings.mPermissions.values()) {
944 if (group == null) {
945 if (p.perm.info.group == null) {
946 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
947 }
948 } else {
949 if (group.equals(p.perm.info.group)) {
950 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
951 }
952 }
953 }
954
955 if (out.size() > 0) {
956 return out;
957 }
958 return mPermissionGroups.containsKey(group) ? out : null;
959 }
960 }
961
962 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
963 synchronized (mPackages) {
964 return PackageParser.generatePermissionGroupInfo(
965 mPermissionGroups.get(name), flags);
966 }
967 }
968
969 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
970 synchronized (mPackages) {
971 final int N = mPermissionGroups.size();
972 ArrayList<PermissionGroupInfo> out
973 = new ArrayList<PermissionGroupInfo>(N);
974 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
975 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
976 }
977 return out;
978 }
979 }
980
981 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
982 PackageSetting ps = mSettings.mPackages.get(packageName);
983 if(ps != null) {
984 if(ps.pkg == null) {
985 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
986 if(pInfo != null) {
987 return pInfo.applicationInfo;
988 }
989 return null;
990 }
991 return PackageParser.generateApplicationInfo(ps.pkg, flags);
992 }
993 return null;
994 }
995
996 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
997 PackageSetting ps = mSettings.mPackages.get(packageName);
998 if(ps != null) {
999 if(ps.pkg == null) {
1000 ps.pkg = new PackageParser.Package(packageName);
1001 ps.pkg.applicationInfo.packageName = packageName;
1002 }
1003 return generatePackageInfo(ps.pkg, flags);
1004 }
1005 return null;
1006 }
1007
1008 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1009 synchronized (mPackages) {
1010 PackageParser.Package p = mPackages.get(packageName);
1011 if (Config.LOGV) Log.v(
1012 TAG, "getApplicationInfo " + packageName
1013 + ": " + p);
1014 if (p != null) {
1015 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001016 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 }
1018 if ("android".equals(packageName)||"system".equals(packageName)) {
1019 return mAndroidApplication;
1020 }
1021 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1022 return generateApplicationInfoFromSettingsLP(packageName, flags);
1023 }
1024 }
1025 return null;
1026 }
1027
1028
1029 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1030 mContext.enforceCallingOrSelfPermission(
1031 android.Manifest.permission.CLEAR_APP_CACHE, null);
1032 // Queue up an async operation since clearing cache may take a little while.
1033 mHandler.post(new Runnable() {
1034 public void run() {
1035 mHandler.removeCallbacks(this);
1036 int retCode = -1;
1037 if (mInstaller != null) {
1038 retCode = mInstaller.freeCache(freeStorageSize);
1039 if (retCode < 0) {
1040 Log.w(TAG, "Couldn't clear application caches");
1041 }
1042 } //end if mInstaller
1043 if (observer != null) {
1044 try {
1045 observer.onRemoveCompleted(null, (retCode >= 0));
1046 } catch (RemoteException e) {
1047 Log.w(TAG, "RemoveException when invoking call back");
1048 }
1049 }
1050 }
1051 });
1052 }
1053
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001054 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001055 mContext.enforceCallingOrSelfPermission(
1056 android.Manifest.permission.CLEAR_APP_CACHE, null);
1057 // Queue up an async operation since clearing cache may take a little while.
1058 mHandler.post(new Runnable() {
1059 public void run() {
1060 mHandler.removeCallbacks(this);
1061 int retCode = -1;
1062 if (mInstaller != null) {
1063 retCode = mInstaller.freeCache(freeStorageSize);
1064 if (retCode < 0) {
1065 Log.w(TAG, "Couldn't clear application caches");
1066 }
1067 }
1068 if(pi != null) {
1069 try {
1070 // Callback via pending intent
1071 int code = (retCode >= 0) ? 1 : 0;
1072 pi.sendIntent(null, code, null,
1073 null, null);
1074 } catch (SendIntentException e1) {
1075 Log.i(TAG, "Failed to send pending intent");
1076 }
1077 }
1078 }
1079 });
1080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081
1082 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1083 synchronized (mPackages) {
1084 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001085
1086 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001088 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 }
1090 if (mResolveComponentName.equals(component)) {
1091 return mResolveActivity;
1092 }
1093 }
1094 return null;
1095 }
1096
1097 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1098 synchronized (mPackages) {
1099 PackageParser.Activity a = mReceivers.mActivities.get(component);
1100 if (Config.LOGV) Log.v(
1101 TAG, "getReceiverInfo " + component + ": " + a);
1102 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1103 return PackageParser.generateActivityInfo(a, flags);
1104 }
1105 }
1106 return null;
1107 }
1108
1109 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1110 synchronized (mPackages) {
1111 PackageParser.Service s = mServices.mServices.get(component);
1112 if (Config.LOGV) Log.v(
1113 TAG, "getServiceInfo " + component + ": " + s);
1114 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1115 return PackageParser.generateServiceInfo(s, flags);
1116 }
1117 }
1118 return null;
1119 }
1120
1121 public String[] getSystemSharedLibraryNames() {
1122 Set<String> libSet;
1123 synchronized (mPackages) {
1124 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001125 int size = libSet.size();
1126 if (size > 0) {
1127 String[] libs = new String[size];
1128 libSet.toArray(libs);
1129 return libs;
1130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001132 return null;
1133 }
1134
1135 public FeatureInfo[] getSystemAvailableFeatures() {
1136 Collection<FeatureInfo> featSet;
1137 synchronized (mPackages) {
1138 featSet = mAvailableFeatures.values();
1139 int size = featSet.size();
1140 if (size > 0) {
1141 FeatureInfo[] features = new FeatureInfo[size+1];
1142 featSet.toArray(features);
1143 FeatureInfo fi = new FeatureInfo();
1144 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1145 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1146 features[size] = fi;
1147 return features;
1148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
1150 return null;
1151 }
1152
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001153 public boolean hasSystemFeature(String name) {
1154 synchronized (mPackages) {
1155 return mAvailableFeatures.containsKey(name);
1156 }
1157 }
1158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 public int checkPermission(String permName, String pkgName) {
1160 synchronized (mPackages) {
1161 PackageParser.Package p = mPackages.get(pkgName);
1162 if (p != null && p.mExtras != null) {
1163 PackageSetting ps = (PackageSetting)p.mExtras;
1164 if (ps.sharedUser != null) {
1165 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1166 return PackageManager.PERMISSION_GRANTED;
1167 }
1168 } else if (ps.grantedPermissions.contains(permName)) {
1169 return PackageManager.PERMISSION_GRANTED;
1170 }
1171 }
1172 }
1173 return PackageManager.PERMISSION_DENIED;
1174 }
1175
1176 public int checkUidPermission(String permName, int uid) {
1177 synchronized (mPackages) {
1178 Object obj = mSettings.getUserIdLP(uid);
1179 if (obj != null) {
1180 if (obj instanceof SharedUserSetting) {
1181 SharedUserSetting sus = (SharedUserSetting)obj;
1182 if (sus.grantedPermissions.contains(permName)) {
1183 return PackageManager.PERMISSION_GRANTED;
1184 }
1185 } else if (obj instanceof PackageSetting) {
1186 PackageSetting ps = (PackageSetting)obj;
1187 if (ps.grantedPermissions.contains(permName)) {
1188 return PackageManager.PERMISSION_GRANTED;
1189 }
1190 }
1191 } else {
1192 HashSet<String> perms = mSystemPermissions.get(uid);
1193 if (perms != null && perms.contains(permName)) {
1194 return PackageManager.PERMISSION_GRANTED;
1195 }
1196 }
1197 }
1198 return PackageManager.PERMISSION_DENIED;
1199 }
1200
1201 private BasePermission findPermissionTreeLP(String permName) {
1202 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1203 if (permName.startsWith(bp.name) &&
1204 permName.length() > bp.name.length() &&
1205 permName.charAt(bp.name.length()) == '.') {
1206 return bp;
1207 }
1208 }
1209 return null;
1210 }
1211
1212 private BasePermission checkPermissionTreeLP(String permName) {
1213 if (permName != null) {
1214 BasePermission bp = findPermissionTreeLP(permName);
1215 if (bp != null) {
1216 if (bp.uid == Binder.getCallingUid()) {
1217 return bp;
1218 }
1219 throw new SecurityException("Calling uid "
1220 + Binder.getCallingUid()
1221 + " is not allowed to add to permission tree "
1222 + bp.name + " owned by uid " + bp.uid);
1223 }
1224 }
1225 throw new SecurityException("No permission tree found for " + permName);
1226 }
1227
1228 public boolean addPermission(PermissionInfo info) {
1229 synchronized (mPackages) {
1230 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1231 throw new SecurityException("Label must be specified in permission");
1232 }
1233 BasePermission tree = checkPermissionTreeLP(info.name);
1234 BasePermission bp = mSettings.mPermissions.get(info.name);
1235 boolean added = bp == null;
1236 if (added) {
1237 bp = new BasePermission(info.name, tree.sourcePackage,
1238 BasePermission.TYPE_DYNAMIC);
1239 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1240 throw new SecurityException(
1241 "Not allowed to modify non-dynamic permission "
1242 + info.name);
1243 }
1244 bp.perm = new PackageParser.Permission(tree.perm.owner,
1245 new PermissionInfo(info));
1246 bp.perm.info.packageName = tree.perm.info.packageName;
1247 bp.uid = tree.uid;
1248 if (added) {
1249 mSettings.mPermissions.put(info.name, bp);
1250 }
1251 mSettings.writeLP();
1252 return added;
1253 }
1254 }
1255
1256 public void removePermission(String name) {
1257 synchronized (mPackages) {
1258 checkPermissionTreeLP(name);
1259 BasePermission bp = mSettings.mPermissions.get(name);
1260 if (bp != null) {
1261 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1262 throw new SecurityException(
1263 "Not allowed to modify non-dynamic permission "
1264 + name);
1265 }
1266 mSettings.mPermissions.remove(name);
1267 mSettings.writeLP();
1268 }
1269 }
1270 }
1271
Dianne Hackborn854060af2009-07-09 18:14:31 -07001272 public boolean isProtectedBroadcast(String actionName) {
1273 synchronized (mPackages) {
1274 return mProtectedBroadcasts.contains(actionName);
1275 }
1276 }
1277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 public int checkSignatures(String pkg1, String pkg2) {
1279 synchronized (mPackages) {
1280 PackageParser.Package p1 = mPackages.get(pkg1);
1281 PackageParser.Package p2 = mPackages.get(pkg2);
1282 if (p1 == null || p1.mExtras == null
1283 || p2 == null || p2.mExtras == null) {
1284 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1285 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001286 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 }
1288 }
1289
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001290 public int checkUidSignatures(int uid1, int uid2) {
1291 synchronized (mPackages) {
1292 Signature[] s1;
1293 Signature[] s2;
1294 Object obj = mSettings.getUserIdLP(uid1);
1295 if (obj != null) {
1296 if (obj instanceof SharedUserSetting) {
1297 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1298 } else if (obj instanceof PackageSetting) {
1299 s1 = ((PackageSetting)obj).signatures.mSignatures;
1300 } else {
1301 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1302 }
1303 } else {
1304 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1305 }
1306 obj = mSettings.getUserIdLP(uid2);
1307 if (obj != null) {
1308 if (obj instanceof SharedUserSetting) {
1309 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1310 } else if (obj instanceof PackageSetting) {
1311 s2 = ((PackageSetting)obj).signatures.mSignatures;
1312 } else {
1313 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1314 }
1315 } else {
1316 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1317 }
1318 return checkSignaturesLP(s1, s2);
1319 }
1320 }
1321
1322 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1323 if (s1 == null) {
1324 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1326 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1327 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001328 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1330 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001331 final int N1 = s1.length;
1332 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 for (int i=0; i<N1; i++) {
1334 boolean match = false;
1335 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001336 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 match = true;
1338 break;
1339 }
1340 }
1341 if (!match) {
1342 return PackageManager.SIGNATURE_NO_MATCH;
1343 }
1344 }
1345 return PackageManager.SIGNATURE_MATCH;
1346 }
1347
1348 public String[] getPackagesForUid(int uid) {
1349 synchronized (mPackages) {
1350 Object obj = mSettings.getUserIdLP(uid);
1351 if (obj instanceof SharedUserSetting) {
1352 SharedUserSetting sus = (SharedUserSetting)obj;
1353 final int N = sus.packages.size();
1354 String[] res = new String[N];
1355 Iterator<PackageSetting> it = sus.packages.iterator();
1356 int i=0;
1357 while (it.hasNext()) {
1358 res[i++] = it.next().name;
1359 }
1360 return res;
1361 } else if (obj instanceof PackageSetting) {
1362 PackageSetting ps = (PackageSetting)obj;
1363 return new String[] { ps.name };
1364 }
1365 }
1366 return null;
1367 }
1368
1369 public String getNameForUid(int uid) {
1370 synchronized (mPackages) {
1371 Object obj = mSettings.getUserIdLP(uid);
1372 if (obj instanceof SharedUserSetting) {
1373 SharedUserSetting sus = (SharedUserSetting)obj;
1374 return sus.name + ":" + sus.userId;
1375 } else if (obj instanceof PackageSetting) {
1376 PackageSetting ps = (PackageSetting)obj;
1377 return ps.name;
1378 }
1379 }
1380 return null;
1381 }
1382
1383 public int getUidForSharedUser(String sharedUserName) {
1384 if(sharedUserName == null) {
1385 return -1;
1386 }
1387 synchronized (mPackages) {
1388 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1389 if(suid == null) {
1390 return -1;
1391 }
1392 return suid.userId;
1393 }
1394 }
1395
1396 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1397 int flags) {
1398 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001399 return chooseBestActivity(intent, resolvedType, flags, query);
1400 }
1401
Mihai Predaeae850c2009-05-13 10:13:48 +02001402 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1403 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 if (query != null) {
1405 final int N = query.size();
1406 if (N == 1) {
1407 return query.get(0);
1408 } else if (N > 1) {
1409 // If there is more than one activity with the same priority,
1410 // then let the user decide between them.
1411 ResolveInfo r0 = query.get(0);
1412 ResolveInfo r1 = query.get(1);
1413 if (false) {
1414 System.out.println(r0.activityInfo.name +
1415 "=" + r0.priority + " vs " +
1416 r1.activityInfo.name +
1417 "=" + r1.priority);
1418 }
1419 // If the first activity has a higher priority, or a different
1420 // default, then it is always desireable to pick it.
1421 if (r0.priority != r1.priority
1422 || r0.preferredOrder != r1.preferredOrder
1423 || r0.isDefault != r1.isDefault) {
1424 return query.get(0);
1425 }
1426 // If we have saved a preference for a preferred activity for
1427 // this Intent, use that.
1428 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1429 flags, query, r0.priority);
1430 if (ri != null) {
1431 return ri;
1432 }
1433 return mResolveInfo;
1434 }
1435 }
1436 return null;
1437 }
1438
1439 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1440 int flags, List<ResolveInfo> query, int priority) {
1441 synchronized (mPackages) {
1442 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1443 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001444 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1446 if (prefs != null && prefs.size() > 0) {
1447 // First figure out how good the original match set is.
1448 // We will only allow preferred activities that came
1449 // from the same match quality.
1450 int match = 0;
1451 final int N = query.size();
1452 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1453 for (int j=0; j<N; j++) {
1454 ResolveInfo ri = query.get(j);
1455 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1456 + ": 0x" + Integer.toHexString(match));
1457 if (ri.match > match) match = ri.match;
1458 }
1459 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1460 + Integer.toHexString(match));
1461 match &= IntentFilter.MATCH_CATEGORY_MASK;
1462 final int M = prefs.size();
1463 for (int i=0; i<M; i++) {
1464 PreferredActivity pa = prefs.get(i);
1465 if (pa.mMatch != match) {
1466 continue;
1467 }
1468 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1469 if (DEBUG_PREFERRED) {
1470 Log.v(TAG, "Got preferred activity:");
1471 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1472 }
1473 if (ai != null) {
1474 for (int j=0; j<N; j++) {
1475 ResolveInfo ri = query.get(j);
1476 if (!ri.activityInfo.applicationInfo.packageName
1477 .equals(ai.applicationInfo.packageName)) {
1478 continue;
1479 }
1480 if (!ri.activityInfo.name.equals(ai.name)) {
1481 continue;
1482 }
1483
1484 // Okay we found a previously set preferred app.
1485 // If the result set is different from when this
1486 // was created, we need to clear it and re-ask the
1487 // user their preference.
1488 if (!pa.sameSet(query, priority)) {
1489 Log.i(TAG, "Result set changed, dropping preferred activity for "
1490 + intent + " type " + resolvedType);
1491 mSettings.mPreferredActivities.removeFilter(pa);
1492 return null;
1493 }
1494
1495 // Yay!
1496 return ri;
1497 }
1498 }
1499 }
1500 }
1501 }
1502 return null;
1503 }
1504
1505 public List<ResolveInfo> queryIntentActivities(Intent intent,
1506 String resolvedType, int flags) {
1507 ComponentName comp = intent.getComponent();
1508 if (comp != null) {
1509 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1510 ActivityInfo ai = getActivityInfo(comp, flags);
1511 if (ai != null) {
1512 ResolveInfo ri = new ResolveInfo();
1513 ri.activityInfo = ai;
1514 list.add(ri);
1515 }
1516 return list;
1517 }
1518
1519 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001520 String pkgName = intent.getPackage();
1521 if (pkgName == null) {
1522 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1523 resolvedType, flags);
1524 }
1525 PackageParser.Package pkg = mPackages.get(pkgName);
1526 if (pkg != null) {
1527 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1528 resolvedType, flags, pkg.activities);
1529 }
1530 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 }
1532 }
1533
1534 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1535 Intent[] specifics, String[] specificTypes, Intent intent,
1536 String resolvedType, int flags) {
1537 final String resultsAction = intent.getAction();
1538
1539 List<ResolveInfo> results = queryIntentActivities(
1540 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1541 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1542
1543 int specificsPos = 0;
1544 int N;
1545
1546 // todo: note that the algorithm used here is O(N^2). This
1547 // isn't a problem in our current environment, but if we start running
1548 // into situations where we have more than 5 or 10 matches then this
1549 // should probably be changed to something smarter...
1550
1551 // First we go through and resolve each of the specific items
1552 // that were supplied, taking care of removing any corresponding
1553 // duplicate items in the generic resolve list.
1554 if (specifics != null) {
1555 for (int i=0; i<specifics.length; i++) {
1556 final Intent sintent = specifics[i];
1557 if (sintent == null) {
1558 continue;
1559 }
1560
1561 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1562 String action = sintent.getAction();
1563 if (resultsAction != null && resultsAction.equals(action)) {
1564 // If this action was explicitly requested, then don't
1565 // remove things that have it.
1566 action = null;
1567 }
1568 ComponentName comp = sintent.getComponent();
1569 ResolveInfo ri = null;
1570 ActivityInfo ai = null;
1571 if (comp == null) {
1572 ri = resolveIntent(
1573 sintent,
1574 specificTypes != null ? specificTypes[i] : null,
1575 flags);
1576 if (ri == null) {
1577 continue;
1578 }
1579 if (ri == mResolveInfo) {
1580 // ACK! Must do something better with this.
1581 }
1582 ai = ri.activityInfo;
1583 comp = new ComponentName(ai.applicationInfo.packageName,
1584 ai.name);
1585 } else {
1586 ai = getActivityInfo(comp, flags);
1587 if (ai == null) {
1588 continue;
1589 }
1590 }
1591
1592 // Look for any generic query activities that are duplicates
1593 // of this specific one, and remove them from the results.
1594 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1595 N = results.size();
1596 int j;
1597 for (j=specificsPos; j<N; j++) {
1598 ResolveInfo sri = results.get(j);
1599 if ((sri.activityInfo.name.equals(comp.getClassName())
1600 && sri.activityInfo.applicationInfo.packageName.equals(
1601 comp.getPackageName()))
1602 || (action != null && sri.filter.matchAction(action))) {
1603 results.remove(j);
1604 if (Config.LOGV) Log.v(
1605 TAG, "Removing duplicate item from " + j
1606 + " due to specific " + specificsPos);
1607 if (ri == null) {
1608 ri = sri;
1609 }
1610 j--;
1611 N--;
1612 }
1613 }
1614
1615 // Add this specific item to its proper place.
1616 if (ri == null) {
1617 ri = new ResolveInfo();
1618 ri.activityInfo = ai;
1619 }
1620 results.add(specificsPos, ri);
1621 ri.specificIndex = i;
1622 specificsPos++;
1623 }
1624 }
1625
1626 // Now we go through the remaining generic results and remove any
1627 // duplicate actions that are found here.
1628 N = results.size();
1629 for (int i=specificsPos; i<N-1; i++) {
1630 final ResolveInfo rii = results.get(i);
1631 if (rii.filter == null) {
1632 continue;
1633 }
1634
1635 // Iterate over all of the actions of this result's intent
1636 // filter... typically this should be just one.
1637 final Iterator<String> it = rii.filter.actionsIterator();
1638 if (it == null) {
1639 continue;
1640 }
1641 while (it.hasNext()) {
1642 final String action = it.next();
1643 if (resultsAction != null && resultsAction.equals(action)) {
1644 // If this action was explicitly requested, then don't
1645 // remove things that have it.
1646 continue;
1647 }
1648 for (int j=i+1; j<N; j++) {
1649 final ResolveInfo rij = results.get(j);
1650 if (rij.filter != null && rij.filter.hasAction(action)) {
1651 results.remove(j);
1652 if (Config.LOGV) Log.v(
1653 TAG, "Removing duplicate item from " + j
1654 + " due to action " + action + " at " + i);
1655 j--;
1656 N--;
1657 }
1658 }
1659 }
1660
1661 // If the caller didn't request filter information, drop it now
1662 // so we don't have to marshall/unmarshall it.
1663 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1664 rii.filter = null;
1665 }
1666 }
1667
1668 // Filter out the caller activity if so requested.
1669 if (caller != null) {
1670 N = results.size();
1671 for (int i=0; i<N; i++) {
1672 ActivityInfo ainfo = results.get(i).activityInfo;
1673 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1674 && caller.getClassName().equals(ainfo.name)) {
1675 results.remove(i);
1676 break;
1677 }
1678 }
1679 }
1680
1681 // If the caller didn't request filter information,
1682 // drop them now so we don't have to
1683 // marshall/unmarshall it.
1684 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1685 N = results.size();
1686 for (int i=0; i<N; i++) {
1687 results.get(i).filter = null;
1688 }
1689 }
1690
1691 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1692 return results;
1693 }
1694
1695 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1696 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001697 ComponentName comp = intent.getComponent();
1698 if (comp != null) {
1699 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1700 ActivityInfo ai = getReceiverInfo(comp, flags);
1701 if (ai != null) {
1702 ResolveInfo ri = new ResolveInfo();
1703 ri.activityInfo = ai;
1704 list.add(ri);
1705 }
1706 return list;
1707 }
1708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001710 String pkgName = intent.getPackage();
1711 if (pkgName == null) {
1712 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1713 resolvedType, flags);
1714 }
1715 PackageParser.Package pkg = mPackages.get(pkgName);
1716 if (pkg != null) {
1717 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1718 resolvedType, flags, pkg.receivers);
1719 }
1720 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 }
1722 }
1723
1724 public ResolveInfo resolveService(Intent intent, String resolvedType,
1725 int flags) {
1726 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1727 flags);
1728 if (query != null) {
1729 if (query.size() >= 1) {
1730 // If there is more than one service with the same priority,
1731 // just arbitrarily pick the first one.
1732 return query.get(0);
1733 }
1734 }
1735 return null;
1736 }
1737
1738 public List<ResolveInfo> queryIntentServices(Intent intent,
1739 String resolvedType, int flags) {
1740 ComponentName comp = intent.getComponent();
1741 if (comp != null) {
1742 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1743 ServiceInfo si = getServiceInfo(comp, flags);
1744 if (si != null) {
1745 ResolveInfo ri = new ResolveInfo();
1746 ri.serviceInfo = si;
1747 list.add(ri);
1748 }
1749 return list;
1750 }
1751
1752 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001753 String pkgName = intent.getPackage();
1754 if (pkgName == null) {
1755 return (List<ResolveInfo>)mServices.queryIntent(intent,
1756 resolvedType, flags);
1757 }
1758 PackageParser.Package pkg = mPackages.get(pkgName);
1759 if (pkg != null) {
1760 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1761 resolvedType, flags, pkg.services);
1762 }
1763 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 }
1765 }
1766
1767 public List<PackageInfo> getInstalledPackages(int flags) {
1768 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1769
1770 synchronized (mPackages) {
1771 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1772 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1773 while (i.hasNext()) {
1774 final PackageSetting ps = i.next();
1775 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1776 if(psPkg != null) {
1777 finalList.add(psPkg);
1778 }
1779 }
1780 }
1781 else {
1782 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1783 while (i.hasNext()) {
1784 final PackageParser.Package p = i.next();
1785 if (p.applicationInfo != null) {
1786 PackageInfo pi = generatePackageInfo(p, flags);
1787 if(pi != null) {
1788 finalList.add(pi);
1789 }
1790 }
1791 }
1792 }
1793 }
1794 return finalList;
1795 }
1796
1797 public List<ApplicationInfo> getInstalledApplications(int flags) {
1798 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1799 synchronized(mPackages) {
1800 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1801 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1802 while (i.hasNext()) {
1803 final PackageSetting ps = i.next();
1804 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1805 if(ai != null) {
1806 finalList.add(ai);
1807 }
1808 }
1809 }
1810 else {
1811 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1812 while (i.hasNext()) {
1813 final PackageParser.Package p = i.next();
1814 if (p.applicationInfo != null) {
1815 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1816 if(ai != null) {
1817 finalList.add(ai);
1818 }
1819 }
1820 }
1821 }
1822 }
1823 return finalList;
1824 }
1825
1826 public List<ApplicationInfo> getPersistentApplications(int flags) {
1827 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1828
1829 synchronized (mPackages) {
1830 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1831 while (i.hasNext()) {
1832 PackageParser.Package p = i.next();
1833 if (p.applicationInfo != null
1834 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
1835 && (!mSafeMode || (p.applicationInfo.flags
1836 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1837 finalList.add(p.applicationInfo);
1838 }
1839 }
1840 }
1841
1842 return finalList;
1843 }
1844
1845 public ProviderInfo resolveContentProvider(String name, int flags) {
1846 synchronized (mPackages) {
1847 final PackageParser.Provider provider = mProviders.get(name);
1848 return provider != null
1849 && mSettings.isEnabledLP(provider.info, flags)
1850 && (!mSafeMode || (provider.info.applicationInfo.flags
1851 &ApplicationInfo.FLAG_SYSTEM) != 0)
1852 ? PackageParser.generateProviderInfo(provider, flags)
1853 : null;
1854 }
1855 }
1856
Fred Quintana718d8a22009-04-29 17:53:20 -07001857 /**
1858 * @deprecated
1859 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 public void querySyncProviders(List outNames, List outInfo) {
1861 synchronized (mPackages) {
1862 Iterator<Map.Entry<String, PackageParser.Provider>> i
1863 = mProviders.entrySet().iterator();
1864
1865 while (i.hasNext()) {
1866 Map.Entry<String, PackageParser.Provider> entry = i.next();
1867 PackageParser.Provider p = entry.getValue();
1868
1869 if (p.syncable
1870 && (!mSafeMode || (p.info.applicationInfo.flags
1871 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1872 outNames.add(entry.getKey());
1873 outInfo.add(PackageParser.generateProviderInfo(p, 0));
1874 }
1875 }
1876 }
1877 }
1878
1879 public List<ProviderInfo> queryContentProviders(String processName,
1880 int uid, int flags) {
1881 ArrayList<ProviderInfo> finalList = null;
1882
1883 synchronized (mPackages) {
1884 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
1885 while (i.hasNext()) {
1886 PackageParser.Provider p = i.next();
1887 if (p.info.authority != null
1888 && (processName == null ||
1889 (p.info.processName.equals(processName)
1890 && p.info.applicationInfo.uid == uid))
1891 && mSettings.isEnabledLP(p.info, flags)
1892 && (!mSafeMode || (p.info.applicationInfo.flags
1893 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1894 if (finalList == null) {
1895 finalList = new ArrayList<ProviderInfo>(3);
1896 }
1897 finalList.add(PackageParser.generateProviderInfo(p,
1898 flags));
1899 }
1900 }
1901 }
1902
1903 if (finalList != null) {
1904 Collections.sort(finalList, mProviderInitOrderSorter);
1905 }
1906
1907 return finalList;
1908 }
1909
1910 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
1911 int flags) {
1912 synchronized (mPackages) {
1913 final PackageParser.Instrumentation i = mInstrumentation.get(name);
1914 return PackageParser.generateInstrumentationInfo(i, flags);
1915 }
1916 }
1917
1918 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
1919 int flags) {
1920 ArrayList<InstrumentationInfo> finalList =
1921 new ArrayList<InstrumentationInfo>();
1922
1923 synchronized (mPackages) {
1924 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
1925 while (i.hasNext()) {
1926 PackageParser.Instrumentation p = i.next();
1927 if (targetPackage == null
1928 || targetPackage.equals(p.info.targetPackage)) {
1929 finalList.add(PackageParser.generateInstrumentationInfo(p,
1930 flags));
1931 }
1932 }
1933 }
1934
1935 return finalList;
1936 }
1937
1938 private void scanDirLI(File dir, int flags, int scanMode) {
1939 Log.d(TAG, "Scanning app dir " + dir);
1940
1941 String[] files = dir.list();
1942
1943 int i;
1944 for (i=0; i<files.length; i++) {
1945 File file = new File(dir, files[i]);
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07001946 File resFile = file;
1947 // Pick up the resource path from settings for fwd locked apps
1948 if ((scanMode & SCAN_FORWARD_LOCKED) != 0) {
1949 resFile = null;
1950 }
1951 PackageParser.Package pkg = scanPackageLI(file, file, resFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
1953 }
1954 }
1955
1956 private static void reportSettingsProblem(int priority, String msg) {
1957 try {
1958 File dataDir = Environment.getDataDirectory();
1959 File systemDir = new File(dataDir, "system");
1960 File fname = new File(systemDir, "uiderrors.txt");
1961 FileOutputStream out = new FileOutputStream(fname, true);
1962 PrintWriter pw = new PrintWriter(out);
1963 pw.println(msg);
1964 pw.close();
1965 FileUtils.setPermissions(
1966 fname.toString(),
1967 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
1968 -1, -1);
1969 } catch (java.io.IOException e) {
1970 }
1971 Log.println(priority, TAG, msg);
1972 }
1973
1974 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
1975 PackageParser.Package pkg, File srcFile, int parseFlags) {
1976 if (GET_CERTIFICATES) {
1977 if (ps == null || !ps.codePath.equals(srcFile)
1978 || ps.getTimeStamp() != srcFile.lastModified()) {
1979 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
1980 if (!pp.collectCertificates(pkg, parseFlags)) {
1981 mLastScanError = pp.getParseError();
1982 return false;
1983 }
1984 }
1985 }
1986 return true;
1987 }
1988
1989 /*
1990 * Scan a package and return the newly parsed package.
1991 * Returns null in case of errors and the error code is stored in mLastScanError
1992 */
1993 private PackageParser.Package scanPackageLI(File scanFile,
1994 File destCodeFile, File destResourceFile, int parseFlags,
1995 int scanMode) {
1996 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
1997 parseFlags |= mDefParseFlags;
1998 PackageParser pp = new PackageParser(scanFile.getPath());
1999 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 final PackageParser.Package pkg = pp.parsePackage(scanFile,
2001 destCodeFile.getAbsolutePath(), mMetrics, parseFlags);
2002 if (pkg == null) {
2003 mLastScanError = pp.getParseError();
2004 return null;
2005 }
2006 PackageSetting ps;
2007 PackageSetting updatedPkg;
2008 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002009 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
2011 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002012 // Verify certificates first
2013 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2014 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2015 return null;
2016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 if (updatedPkg != null) {
2018 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2019 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2020 }
2021 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2022 // Check for updated system applications here
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002023 if ((ps != null) && (!ps.codePath.equals(scanFile))) {
2024 if (pkg.mVersionCode < ps.versionCode) {
2025 // The system package has been updated and the code path does not match
2026 // Ignore entry. Just return
2027 Log.w(TAG, "Package:" + pkg.packageName +
2028 " has been updated. Ignoring the one from path:"+scanFile);
2029 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2030 return null;
2031 } else {
2032 // Delete the older apk pointed to by ps
2033 // At this point, its safely assumed that package installation for
2034 // apps in system partition will go through. If not there won't be a working
2035 // version of the app
2036 synchronized (mPackages) {
2037 // Just remove the loaded entries from package lists.
2038 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002039 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002040 deletePackageResourcesLI(ps.name, ps.codePathString, ps.resourcePathString);
2041 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
2044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 // The apk is forward locked (not public) if its code and resources
2046 // are kept in different files.
2047 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
2048 scanMode |= SCAN_FORWARD_LOCKED;
2049 }
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002050 File resFile = destResourceFile;
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07002051 if (ps != null && ((scanMode & SCAN_FORWARD_LOCKED) != 0)) {
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002052 resFile = getFwdLockedResource(ps.name);
2053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002055 return scanPackageLI(scanFile, destCodeFile, resFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
2057 }
2058
2059 private static String fixProcessName(String defProcessName,
2060 String processName, int uid) {
2061 if (processName == null) {
2062 return defProcessName;
2063 }
2064 return processName;
2065 }
2066
2067 private boolean verifySignaturesLP(PackageSetting pkgSetting,
2068 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2069 if (pkg.mSignatures != null) {
2070 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2071 updateSignature)) {
2072 Log.e(TAG, "Package " + pkg.packageName
2073 + " signatures do not match the previously installed version; ignoring!");
2074 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2075 return false;
2076 }
2077
2078 if (pkgSetting.sharedUser != null) {
2079 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2080 pkg.mSignatures, updateSignature)) {
2081 Log.e(TAG, "Package " + pkg.packageName
2082 + " has no signatures that match those in shared user "
2083 + pkgSetting.sharedUser.name + "; ignoring!");
2084 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2085 return false;
2086 }
2087 }
2088 } else {
2089 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2090 }
2091 return true;
2092 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002093
2094 public boolean performDexOpt(String packageName) {
2095 if (!mNoDexOpt) {
2096 return false;
2097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002099 PackageParser.Package p;
2100 synchronized (mPackages) {
2101 p = mPackages.get(packageName);
2102 if (p == null || p.mDidDexOpt) {
2103 return false;
2104 }
2105 }
2106 synchronized (mInstallLock) {
2107 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2108 }
2109 }
2110
2111 static final int DEX_OPT_SKIPPED = 0;
2112 static final int DEX_OPT_PERFORMED = 1;
2113 static final int DEX_OPT_FAILED = -1;
2114
2115 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2116 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002117 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002118 String path = pkg.mScanPath;
2119 int ret = 0;
2120 try {
2121 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
2122 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
2123 !pkg.mForwardLocked);
2124 pkg.mDidDexOpt = true;
2125 performed = true;
2126 }
2127 } catch (FileNotFoundException e) {
2128 Log.w(TAG, "Apk not found for dexopt: " + path);
2129 ret = -1;
2130 } catch (IOException e) {
2131 Log.w(TAG, "Exception reading apk: " + path, e);
2132 ret = -1;
2133 }
2134 if (ret < 0) {
2135 //error from installer
2136 return DEX_OPT_FAILED;
2137 }
2138 }
2139
2140 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2141 }
2142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 private PackageParser.Package scanPackageLI(
2144 File scanFile, File destCodeFile, File destResourceFile,
2145 PackageParser.Package pkg, int parseFlags, int scanMode) {
2146
2147 mScanningPath = scanFile;
2148 if (pkg == null) {
2149 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2150 return null;
2151 }
2152
2153 final String pkgName = pkg.applicationInfo.packageName;
2154 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2155 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2156 }
2157
2158 if (pkgName.equals("android")) {
2159 synchronized (mPackages) {
2160 if (mAndroidApplication != null) {
2161 Log.w(TAG, "*************************************************");
2162 Log.w(TAG, "Core android package being redefined. Skipping.");
2163 Log.w(TAG, " file=" + mScanningPath);
2164 Log.w(TAG, "*************************************************");
2165 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2166 return null;
2167 }
2168
2169 // Set up information for our fall-back user intent resolution
2170 // activity.
2171 mPlatformPackage = pkg;
2172 pkg.mVersionCode = mSdkVersion;
2173 mAndroidApplication = pkg.applicationInfo;
2174 mResolveActivity.applicationInfo = mAndroidApplication;
2175 mResolveActivity.name = ResolverActivity.class.getName();
2176 mResolveActivity.packageName = mAndroidApplication.packageName;
2177 mResolveActivity.processName = mAndroidApplication.processName;
2178 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2179 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2180 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2181 mResolveActivity.exported = true;
2182 mResolveActivity.enabled = true;
2183 mResolveInfo.activityInfo = mResolveActivity;
2184 mResolveInfo.priority = 0;
2185 mResolveInfo.preferredOrder = 0;
2186 mResolveInfo.match = 0;
2187 mResolveComponentName = new ComponentName(
2188 mAndroidApplication.packageName, mResolveActivity.name);
2189 }
2190 }
2191
2192 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2193 TAG, "Scanning package " + pkgName);
2194 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2195 Log.w(TAG, "*************************************************");
2196 Log.w(TAG, "Application package " + pkgName
2197 + " already installed. Skipping duplicate.");
2198 Log.w(TAG, "*************************************************");
2199 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2200 return null;
2201 }
2202
2203 SharedUserSetting suid = null;
2204 PackageSetting pkgSetting = null;
2205
2206 boolean removeExisting = false;
2207
2208 synchronized (mPackages) {
2209 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002210 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2211 if (mTmpSharedLibraries == null ||
2212 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2213 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2214 }
2215 int num = 0;
2216 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2217 for (int i=0; i<N; i++) {
2218 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 if (file == null) {
2220 Log.e(TAG, "Package " + pkg.packageName
2221 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002222 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2224 return null;
2225 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002226 mTmpSharedLibraries[num] = file;
2227 num++;
2228 }
2229 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2230 for (int i=0; i<N; i++) {
2231 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2232 if (file == null) {
2233 Log.w(TAG, "Package " + pkg.packageName
2234 + " desires unavailable shared library "
2235 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2236 } else {
2237 mTmpSharedLibraries[num] = file;
2238 num++;
2239 }
2240 }
2241 if (num > 0) {
2242 pkg.usesLibraryFiles = new String[num];
2243 System.arraycopy(mTmpSharedLibraries, 0,
2244 pkg.usesLibraryFiles, 0, num);
2245 }
2246
2247 if (pkg.reqFeatures != null) {
2248 N = pkg.reqFeatures.size();
2249 for (int i=0; i<N; i++) {
2250 FeatureInfo fi = pkg.reqFeatures.get(i);
2251 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2252 // Don't care.
2253 continue;
2254 }
2255
2256 if (fi.name != null) {
2257 if (mAvailableFeatures.get(fi.name) == null) {
2258 Log.e(TAG, "Package " + pkg.packageName
2259 + " requires unavailable feature "
2260 + fi.name + "; failing!");
2261 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2262 return null;
2263 }
2264 }
2265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002266 }
2267 }
2268
2269 if (pkg.mSharedUserId != null) {
2270 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2271 pkg.applicationInfo.flags, true);
2272 if (suid == null) {
2273 Log.w(TAG, "Creating application package " + pkgName
2274 + " for shared user failed");
2275 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2276 return null;
2277 }
2278 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2279 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2280 + suid.userId + "): packages=" + suid.packages);
2281 }
2282 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002283
2284 // Just create the setting, don't add it yet. For already existing packages
2285 // the PkgSetting exists already and doesn't have to be created.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile,
2287 destResourceFile, pkg.applicationInfo.flags, true, false);
2288 if (pkgSetting == null) {
2289 Log.w(TAG, "Creating application package " + pkgName + " failed");
2290 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2291 return null;
2292 }
2293 if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
2294 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2295 }
2296
2297 pkg.applicationInfo.uid = pkgSetting.userId;
2298 pkg.mExtras = pkgSetting;
2299
2300 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
2301 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2302 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2303 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2304 return null;
2305 }
2306 // The signature has changed, but this package is in the system
2307 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002308 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 // However... if this package is part of a shared user, but it
2310 // doesn't match the signature of the shared user, let's fail.
2311 // What this means is that you can't change the signatures
2312 // associated with an overall shared user, which doesn't seem all
2313 // that unreasonable.
2314 if (pkgSetting.sharedUser != null) {
2315 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2316 pkg.mSignatures, false)) {
2317 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2318 return null;
2319 }
2320 }
2321 removeExisting = true;
2322 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002323
2324 // Verify that this new package doesn't have any content providers
2325 // that conflict with existing packages. Only do this if the
2326 // package isn't already installed, since we don't want to break
2327 // things that are installed.
2328 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2329 int N = pkg.providers.size();
2330 int i;
2331 for (i=0; i<N; i++) {
2332 PackageParser.Provider p = pkg.providers.get(i);
2333 String names[] = p.info.authority.split(";");
2334 for (int j = 0; j < names.length; j++) {
2335 if (mProviders.containsKey(names[j])) {
2336 PackageParser.Provider other = mProviders.get(names[j]);
2337 Log.w(TAG, "Can't install because provider name " + names[j] +
2338 " (in package " + pkg.applicationInfo.packageName +
2339 ") is already used by "
2340 + ((other != null && other.component != null)
2341 ? other.component.getPackageName() : "?"));
2342 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2343 return null;
2344 }
2345 }
2346 }
2347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002348 }
2349
2350 if (removeExisting) {
2351 if (mInstaller != null) {
2352 int ret = mInstaller.remove(pkgName);
2353 if (ret != 0) {
2354 String msg = "System package " + pkg.packageName
2355 + " could not have data directory erased after signature change.";
2356 reportSettingsProblem(Log.WARN, msg);
2357 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2358 return null;
2359 }
2360 }
2361 Log.w(TAG, "System package " + pkg.packageName
2362 + " signature changed: existing data removed.");
2363 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2364 }
2365
2366 long scanFileTime = scanFile.lastModified();
2367 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2368 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2369 pkg.applicationInfo.processName = fixProcessName(
2370 pkg.applicationInfo.packageName,
2371 pkg.applicationInfo.processName,
2372 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002373 pkg.applicationInfo.publicSourceDir = destResourceFile.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374
2375 File dataPath;
2376 if (mPlatformPackage == pkg) {
2377 // The system package is special.
2378 dataPath = new File (Environment.getDataDirectory(), "system");
2379 pkg.applicationInfo.dataDir = dataPath.getPath();
2380 } else {
2381 // This is a normal package, need to make its data directory.
2382 dataPath = new File(mAppDataDir, pkgName);
2383 if (dataPath.exists()) {
2384 mOutPermissions[1] = 0;
2385 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2386 if (mOutPermissions[1] == pkg.applicationInfo.uid
2387 || !Process.supportsProcesses()) {
2388 pkg.applicationInfo.dataDir = dataPath.getPath();
2389 } else {
2390 boolean recovered = false;
2391 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2392 // If this is a system app, we can at least delete its
2393 // current data so the application will still work.
2394 if (mInstaller != null) {
2395 int ret = mInstaller.remove(pkgName);
2396 if(ret >= 0) {
2397 // Old data gone!
2398 String msg = "System package " + pkg.packageName
2399 + " has changed from uid: "
2400 + mOutPermissions[1] + " to "
2401 + pkg.applicationInfo.uid + "; old data erased";
2402 reportSettingsProblem(Log.WARN, msg);
2403 recovered = true;
2404
2405 // And now re-install the app.
2406 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2407 pkg.applicationInfo.uid);
2408 if (ret == -1) {
2409 // Ack should not happen!
2410 msg = "System package " + pkg.packageName
2411 + " could not have data directory re-created after delete.";
2412 reportSettingsProblem(Log.WARN, msg);
2413 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2414 return null;
2415 }
2416 }
2417 }
2418 if (!recovered) {
2419 mHasSystemUidErrors = true;
2420 }
2421 }
2422 if (!recovered) {
2423 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2424 + pkg.applicationInfo.uid + "/fs_"
2425 + mOutPermissions[1];
2426 String msg = "Package " + pkg.packageName
2427 + " has mismatched uid: "
2428 + mOutPermissions[1] + " on disk, "
2429 + pkg.applicationInfo.uid + " in settings";
2430 synchronized (mPackages) {
2431 if (!mReportedUidError) {
2432 mReportedUidError = true;
2433 msg = msg + "; read messages:\n"
2434 + mSettings.getReadMessagesLP();
2435 }
2436 reportSettingsProblem(Log.ERROR, msg);
2437 }
2438 }
2439 }
2440 pkg.applicationInfo.dataDir = dataPath.getPath();
2441 } else {
2442 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2443 Log.v(TAG, "Want this data dir: " + dataPath);
2444 //invoke installer to do the actual installation
2445 if (mInstaller != null) {
2446 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2447 pkg.applicationInfo.uid);
2448 if(ret < 0) {
2449 // Error from installer
2450 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2451 return null;
2452 }
2453 } else {
2454 dataPath.mkdirs();
2455 if (dataPath.exists()) {
2456 FileUtils.setPermissions(
2457 dataPath.toString(),
2458 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2459 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2460 }
2461 }
2462 if (dataPath.exists()) {
2463 pkg.applicationInfo.dataDir = dataPath.getPath();
2464 } else {
2465 Log.w(TAG, "Unable to create data directory: " + dataPath);
2466 pkg.applicationInfo.dataDir = null;
2467 }
2468 }
2469 }
2470
2471 // Perform shared library installation and dex validation and
2472 // optimization, if this is not a system app.
2473 if (mInstaller != null) {
2474 String path = scanFile.getPath();
2475 if (scanFileNewer) {
2476 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002477 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2478 if (err != PackageManager.INSTALL_SUCCEEDED) {
2479 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 return null;
2481 }
2482 }
2483
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002484 pkg.mForwardLocked = (scanMode&SCAN_FORWARD_LOCKED) != 0;
2485 pkg.mScanPath = path;
2486
2487 if ((scanMode&SCAN_NO_DEX) == 0) {
2488 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2490 return null;
2491 }
2492 }
2493 }
2494
2495 if (mFactoryTest && pkg.requestedPermissions.contains(
2496 android.Manifest.permission.FACTORY_TEST)) {
2497 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2498 }
2499
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002500 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 if ((scanMode&SCAN_MONITOR) != 0) {
2502 pkg.mPath = destCodeFile.getAbsolutePath();
2503 mAppDirs.put(pkg.mPath, pkg);
2504 }
2505
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002506 // Request the ActivityManager to kill the process(only for existing packages)
2507 // so that we do not end up in a confused state while the user is still using the older
2508 // version of the application while the new one gets installed.
2509 IActivityManager am = ActivityManagerNative.getDefault();
2510 if ((am != null) && ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0)) {
2511 try {
2512 am.killApplicationWithUid(pkg.applicationInfo.packageName,
2513 pkg.applicationInfo.uid);
2514 } catch (RemoteException e) {
2515 }
2516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 // Add the new setting to mSettings
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002519 mSettings.insertPackageSettingLP(pkgSetting, pkg, destCodeFile, destResourceFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002521 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 int N = pkg.providers.size();
2523 StringBuilder r = null;
2524 int i;
2525 for (i=0; i<N; i++) {
2526 PackageParser.Provider p = pkg.providers.get(i);
2527 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2528 p.info.processName, pkg.applicationInfo.uid);
2529 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2530 p.info.name), p);
2531 p.syncable = p.info.isSyncable;
2532 String names[] = p.info.authority.split(";");
2533 p.info.authority = null;
2534 for (int j = 0; j < names.length; j++) {
2535 if (j == 1 && p.syncable) {
2536 // We only want the first authority for a provider to possibly be
2537 // syncable, so if we already added this provider using a different
2538 // authority clear the syncable flag. We copy the provider before
2539 // changing it because the mProviders object contains a reference
2540 // to a provider that we don't want to change.
2541 // Only do this for the second authority since the resulting provider
2542 // object can be the same for all future authorities for this provider.
2543 p = new PackageParser.Provider(p);
2544 p.syncable = false;
2545 }
2546 if (!mProviders.containsKey(names[j])) {
2547 mProviders.put(names[j], p);
2548 if (p.info.authority == null) {
2549 p.info.authority = names[j];
2550 } else {
2551 p.info.authority = p.info.authority + ";" + names[j];
2552 }
2553 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2554 Log.d(TAG, "Registered content provider: " + names[j] +
2555 ", className = " + p.info.name +
2556 ", isSyncable = " + p.info.isSyncable);
2557 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002558 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 Log.w(TAG, "Skipping provider name " + names[j] +
2560 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002561 "): name already used by "
2562 + ((other != null && other.component != null)
2563 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 }
2565 }
2566 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2567 if (r == null) {
2568 r = new StringBuilder(256);
2569 } else {
2570 r.append(' ');
2571 }
2572 r.append(p.info.name);
2573 }
2574 }
2575 if (r != null) {
2576 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2577 }
2578
2579 N = pkg.services.size();
2580 r = null;
2581 for (i=0; i<N; i++) {
2582 PackageParser.Service s = pkg.services.get(i);
2583 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2584 s.info.processName, pkg.applicationInfo.uid);
2585 mServices.addService(s);
2586 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2587 if (r == null) {
2588 r = new StringBuilder(256);
2589 } else {
2590 r.append(' ');
2591 }
2592 r.append(s.info.name);
2593 }
2594 }
2595 if (r != null) {
2596 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2597 }
2598
2599 N = pkg.receivers.size();
2600 r = null;
2601 for (i=0; i<N; i++) {
2602 PackageParser.Activity a = pkg.receivers.get(i);
2603 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2604 a.info.processName, pkg.applicationInfo.uid);
2605 mReceivers.addActivity(a, "receiver");
2606 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2607 if (r == null) {
2608 r = new StringBuilder(256);
2609 } else {
2610 r.append(' ');
2611 }
2612 r.append(a.info.name);
2613 }
2614 }
2615 if (r != null) {
2616 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2617 }
2618
2619 N = pkg.activities.size();
2620 r = null;
2621 for (i=0; i<N; i++) {
2622 PackageParser.Activity a = pkg.activities.get(i);
2623 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2624 a.info.processName, pkg.applicationInfo.uid);
2625 mActivities.addActivity(a, "activity");
2626 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2627 if (r == null) {
2628 r = new StringBuilder(256);
2629 } else {
2630 r.append(' ');
2631 }
2632 r.append(a.info.name);
2633 }
2634 }
2635 if (r != null) {
2636 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2637 }
2638
2639 N = pkg.permissionGroups.size();
2640 r = null;
2641 for (i=0; i<N; i++) {
2642 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2643 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2644 if (cur == null) {
2645 mPermissionGroups.put(pg.info.name, pg);
2646 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2647 if (r == null) {
2648 r = new StringBuilder(256);
2649 } else {
2650 r.append(' ');
2651 }
2652 r.append(pg.info.name);
2653 }
2654 } else {
2655 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2656 + pg.info.packageName + " ignored: original from "
2657 + cur.info.packageName);
2658 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2659 if (r == null) {
2660 r = new StringBuilder(256);
2661 } else {
2662 r.append(' ');
2663 }
2664 r.append("DUP:");
2665 r.append(pg.info.name);
2666 }
2667 }
2668 }
2669 if (r != null) {
2670 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2671 }
2672
2673 N = pkg.permissions.size();
2674 r = null;
2675 for (i=0; i<N; i++) {
2676 PackageParser.Permission p = pkg.permissions.get(i);
2677 HashMap<String, BasePermission> permissionMap =
2678 p.tree ? mSettings.mPermissionTrees
2679 : mSettings.mPermissions;
2680 p.group = mPermissionGroups.get(p.info.group);
2681 if (p.info.group == null || p.group != null) {
2682 BasePermission bp = permissionMap.get(p.info.name);
2683 if (bp == null) {
2684 bp = new BasePermission(p.info.name, p.info.packageName,
2685 BasePermission.TYPE_NORMAL);
2686 permissionMap.put(p.info.name, bp);
2687 }
2688 if (bp.perm == null) {
2689 if (bp.sourcePackage == null
2690 || bp.sourcePackage.equals(p.info.packageName)) {
2691 BasePermission tree = findPermissionTreeLP(p.info.name);
2692 if (tree == null
2693 || tree.sourcePackage.equals(p.info.packageName)) {
2694 bp.perm = p;
2695 bp.uid = pkg.applicationInfo.uid;
2696 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2697 if (r == null) {
2698 r = new StringBuilder(256);
2699 } else {
2700 r.append(' ');
2701 }
2702 r.append(p.info.name);
2703 }
2704 } else {
2705 Log.w(TAG, "Permission " + p.info.name + " from package "
2706 + p.info.packageName + " ignored: base tree "
2707 + tree.name + " is from package "
2708 + tree.sourcePackage);
2709 }
2710 } else {
2711 Log.w(TAG, "Permission " + p.info.name + " from package "
2712 + p.info.packageName + " ignored: original from "
2713 + bp.sourcePackage);
2714 }
2715 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2716 if (r == null) {
2717 r = new StringBuilder(256);
2718 } else {
2719 r.append(' ');
2720 }
2721 r.append("DUP:");
2722 r.append(p.info.name);
2723 }
2724 } else {
2725 Log.w(TAG, "Permission " + p.info.name + " from package "
2726 + p.info.packageName + " ignored: no group "
2727 + p.group);
2728 }
2729 }
2730 if (r != null) {
2731 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2732 }
2733
2734 N = pkg.instrumentation.size();
2735 r = null;
2736 for (i=0; i<N; i++) {
2737 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2738 a.info.packageName = pkg.applicationInfo.packageName;
2739 a.info.sourceDir = pkg.applicationInfo.sourceDir;
2740 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
2741 a.info.dataDir = pkg.applicationInfo.dataDir;
2742 mInstrumentation.put(a.component, a);
2743 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2744 if (r == null) {
2745 r = new StringBuilder(256);
2746 } else {
2747 r.append(' ');
2748 }
2749 r.append(a.info.name);
2750 }
2751 }
2752 if (r != null) {
2753 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2754 }
2755
Dianne Hackborn854060af2009-07-09 18:14:31 -07002756 if (pkg.protectedBroadcasts != null) {
2757 N = pkg.protectedBroadcasts.size();
2758 for (i=0; i<N; i++) {
2759 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
2760 }
2761 }
2762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 pkgSetting.setTimeStamp(scanFileTime);
2764 }
2765
2766 return pkg;
2767 }
2768
Dianne Hackbornb1811182009-05-21 15:45:42 -07002769 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
2770 File dataPath, File scanFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002772 final String sharedLibraryABI = Build.CPU_ABI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 final String apkLibraryDirectory = "lib/" + sharedLibraryABI + "/";
2774 final String apkSharedLibraryPrefix = apkLibraryDirectory + "lib";
2775 final String sharedLibrarySuffix = ".so";
Dianne Hackbornb1811182009-05-21 15:45:42 -07002776 boolean hasNativeCode = false;
2777 boolean installedNativeCode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 try {
2779 ZipFile zipFile = new ZipFile(scanFile);
2780 Enumeration<ZipEntry> entries =
2781 (Enumeration<ZipEntry>) zipFile.entries();
2782
2783 while (entries.hasMoreElements()) {
2784 ZipEntry entry = entries.nextElement();
2785 if (entry.isDirectory()) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07002786 if (!hasNativeCode && entry.getName().startsWith("lib")) {
2787 hasNativeCode = true;
2788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 continue;
2790 }
2791 String entryName = entry.getName();
Dianne Hackbornb1811182009-05-21 15:45:42 -07002792 if (entryName.startsWith("lib/")) {
2793 hasNativeCode = true;
2794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 if (! (entryName.startsWith(apkSharedLibraryPrefix)
2796 && entryName.endsWith(sharedLibrarySuffix))) {
2797 continue;
2798 }
2799 String libFileName = entryName.substring(
2800 apkLibraryDirectory.length());
2801 if (libFileName.contains("/")
2802 || (!FileUtils.isFilenameSafe(new File(libFileName)))) {
2803 continue;
2804 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07002805
2806 installedNativeCode = true;
2807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
2809 File.separator + libFileName;
2810 File sharedLibraryFile = new File(sharedLibraryFilePath);
2811 if (! sharedLibraryFile.exists() ||
2812 sharedLibraryFile.length() != entry.getSize() ||
2813 sharedLibraryFile.lastModified() != entry.getTime()) {
2814 if (Config.LOGD) {
2815 Log.d(TAG, "Caching shared lib " + entry.getName());
2816 }
2817 if (mInstaller == null) {
2818 sharedLibraryDir.mkdir();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
2820 cacheSharedLibLI(pkg, zipFile, entry, sharedLibraryDir,
2821 sharedLibraryFile);
2822 }
2823 }
2824 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07002825 Log.w(TAG, "Failed to cache package shared libs", e);
2826 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07002828
2829 if (hasNativeCode && !installedNativeCode) {
2830 Log.w(TAG, "Install failed: .apk has native code but none for arch "
2831 + Build.CPU_ABI);
2832 return PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
2833 }
2834
2835 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 }
2837
2838 private void cacheSharedLibLI(PackageParser.Package pkg,
2839 ZipFile zipFile, ZipEntry entry,
2840 File sharedLibraryDir,
2841 File sharedLibraryFile) throws IOException {
2842 InputStream inputStream = zipFile.getInputStream(entry);
2843 try {
2844 File tempFile = File.createTempFile("tmp", "tmp", sharedLibraryDir);
2845 String tempFilePath = tempFile.getPath();
2846 // XXX package manager can't change owner, so the lib files for
2847 // now need to be left as world readable and owned by the system.
2848 if (! FileUtils.copyToFile(inputStream, tempFile) ||
2849 ! tempFile.setLastModified(entry.getTime()) ||
2850 FileUtils.setPermissions(tempFilePath,
2851 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
2852 |FileUtils.S_IROTH, -1, -1) != 0 ||
2853 ! tempFile.renameTo(sharedLibraryFile)) {
2854 // Failed to properly write file.
2855 tempFile.delete();
2856 throw new IOException("Couldn't create cached shared lib "
2857 + sharedLibraryFile + " in " + sharedLibraryDir);
2858 }
2859 } finally {
2860 inputStream.close();
2861 }
2862 }
2863
2864 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
2865 if (chatty && Config.LOGD) Log.d(
2866 TAG, "Removing package " + pkg.applicationInfo.packageName );
2867
2868 synchronized (mPackages) {
2869 if (pkg.mPreferredOrder > 0) {
2870 mSettings.mPreferredPackages.remove(pkg);
2871 pkg.mPreferredOrder = 0;
2872 updatePreferredIndicesLP();
2873 }
2874
2875 clearPackagePreferredActivitiesLP(pkg.packageName);
2876
2877 mPackages.remove(pkg.applicationInfo.packageName);
2878 if (pkg.mPath != null) {
2879 mAppDirs.remove(pkg.mPath);
2880 }
2881
2882 PackageSetting ps = (PackageSetting)pkg.mExtras;
2883 if (ps != null && ps.sharedUser != null) {
2884 // XXX don't do this until the data is removed.
2885 if (false) {
2886 ps.sharedUser.packages.remove(ps);
2887 if (ps.sharedUser.packages.size() == 0) {
2888 // Remove.
2889 }
2890 }
2891 }
2892
2893 int N = pkg.providers.size();
2894 StringBuilder r = null;
2895 int i;
2896 for (i=0; i<N; i++) {
2897 PackageParser.Provider p = pkg.providers.get(i);
2898 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
2899 p.info.name));
2900 if (p.info.authority == null) {
2901
2902 /* The is another ContentProvider with this authority when
2903 * this app was installed so this authority is null,
2904 * Ignore it as we don't have to unregister the provider.
2905 */
2906 continue;
2907 }
2908 String names[] = p.info.authority.split(";");
2909 for (int j = 0; j < names.length; j++) {
2910 if (mProviders.get(names[j]) == p) {
2911 mProviders.remove(names[j]);
2912 if (chatty && Config.LOGD) Log.d(
2913 TAG, "Unregistered content provider: " + names[j] +
2914 ", className = " + p.info.name +
2915 ", isSyncable = " + p.info.isSyncable);
2916 }
2917 }
2918 if (chatty) {
2919 if (r == null) {
2920 r = new StringBuilder(256);
2921 } else {
2922 r.append(' ');
2923 }
2924 r.append(p.info.name);
2925 }
2926 }
2927 if (r != null) {
2928 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2929 }
2930
2931 N = pkg.services.size();
2932 r = null;
2933 for (i=0; i<N; i++) {
2934 PackageParser.Service s = pkg.services.get(i);
2935 mServices.removeService(s);
2936 if (chatty) {
2937 if (r == null) {
2938 r = new StringBuilder(256);
2939 } else {
2940 r.append(' ');
2941 }
2942 r.append(s.info.name);
2943 }
2944 }
2945 if (r != null) {
2946 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2947 }
2948
2949 N = pkg.receivers.size();
2950 r = null;
2951 for (i=0; i<N; i++) {
2952 PackageParser.Activity a = pkg.receivers.get(i);
2953 mReceivers.removeActivity(a, "receiver");
2954 if (chatty) {
2955 if (r == null) {
2956 r = new StringBuilder(256);
2957 } else {
2958 r.append(' ');
2959 }
2960 r.append(a.info.name);
2961 }
2962 }
2963 if (r != null) {
2964 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2965 }
2966
2967 N = pkg.activities.size();
2968 r = null;
2969 for (i=0; i<N; i++) {
2970 PackageParser.Activity a = pkg.activities.get(i);
2971 mActivities.removeActivity(a, "activity");
2972 if (chatty) {
2973 if (r == null) {
2974 r = new StringBuilder(256);
2975 } else {
2976 r.append(' ');
2977 }
2978 r.append(a.info.name);
2979 }
2980 }
2981 if (r != null) {
2982 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2983 }
2984
2985 N = pkg.permissions.size();
2986 r = null;
2987 for (i=0; i<N; i++) {
2988 PackageParser.Permission p = pkg.permissions.get(i);
2989 boolean tree = false;
2990 BasePermission bp = mSettings.mPermissions.get(p.info.name);
2991 if (bp == null) {
2992 tree = true;
2993 bp = mSettings.mPermissionTrees.get(p.info.name);
2994 }
2995 if (bp != null && bp.perm == p) {
2996 if (bp.type != BasePermission.TYPE_BUILTIN) {
2997 if (tree) {
2998 mSettings.mPermissionTrees.remove(p.info.name);
2999 } else {
3000 mSettings.mPermissions.remove(p.info.name);
3001 }
3002 } else {
3003 bp.perm = null;
3004 }
3005 if (chatty) {
3006 if (r == null) {
3007 r = new StringBuilder(256);
3008 } else {
3009 r.append(' ');
3010 }
3011 r.append(p.info.name);
3012 }
3013 }
3014 }
3015 if (r != null) {
3016 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3017 }
3018
3019 N = pkg.instrumentation.size();
3020 r = null;
3021 for (i=0; i<N; i++) {
3022 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3023 mInstrumentation.remove(a.component);
3024 if (chatty) {
3025 if (r == null) {
3026 r = new StringBuilder(256);
3027 } else {
3028 r.append(' ');
3029 }
3030 r.append(a.info.name);
3031 }
3032 }
3033 if (r != null) {
3034 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3035 }
3036 }
3037 }
3038
3039 private static final boolean isPackageFilename(String name) {
3040 return name != null && name.endsWith(".apk");
3041 }
3042
3043 private void updatePermissionsLP() {
3044 // Make sure there are no dangling permission trees.
3045 Iterator<BasePermission> it = mSettings.mPermissionTrees
3046 .values().iterator();
3047 while (it.hasNext()) {
3048 BasePermission bp = it.next();
3049 if (bp.perm == null) {
3050 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3051 + " from package " + bp.sourcePackage);
3052 it.remove();
3053 }
3054 }
3055
3056 // Make sure all dynamic permissions have been assigned to a package,
3057 // and make sure there are no dangling permissions.
3058 it = mSettings.mPermissions.values().iterator();
3059 while (it.hasNext()) {
3060 BasePermission bp = it.next();
3061 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3062 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3063 + bp.name + " pkg=" + bp.sourcePackage
3064 + " info=" + bp.pendingInfo);
3065 if (bp.perm == null && bp.pendingInfo != null) {
3066 BasePermission tree = findPermissionTreeLP(bp.name);
3067 if (tree != null) {
3068 bp.perm = new PackageParser.Permission(tree.perm.owner,
3069 new PermissionInfo(bp.pendingInfo));
3070 bp.perm.info.packageName = tree.perm.info.packageName;
3071 bp.perm.info.name = bp.name;
3072 bp.uid = tree.uid;
3073 }
3074 }
3075 }
3076 if (bp.perm == null) {
3077 Log.w(TAG, "Removing dangling permission: " + bp.name
3078 + " from package " + bp.sourcePackage);
3079 it.remove();
3080 }
3081 }
3082
3083 // Now update the permissions for all packages, in particular
3084 // replace the granted permissions of the system packages.
3085 for (PackageParser.Package pkg : mPackages.values()) {
3086 grantPermissionsLP(pkg, false);
3087 }
3088 }
3089
3090 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3091 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3092 if (ps == null) {
3093 return;
3094 }
3095 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3096 boolean addedPermission = false;
3097
3098 if (replace) {
3099 ps.permissionsFixed = false;
3100 if (gp == ps) {
3101 gp.grantedPermissions.clear();
3102 gp.gids = mGlobalGids;
3103 }
3104 }
3105
3106 if (gp.gids == null) {
3107 gp.gids = mGlobalGids;
3108 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07003109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 final int N = pkg.requestedPermissions.size();
3111 for (int i=0; i<N; i++) {
3112 String name = pkg.requestedPermissions.get(i);
3113 BasePermission bp = mSettings.mPermissions.get(name);
3114 PackageParser.Permission p = bp != null ? bp.perm : null;
3115 if (false) {
3116 if (gp != ps) {
3117 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3118 + ": " + p);
3119 }
3120 }
3121 if (p != null) {
3122 final String perm = p.info.name;
3123 boolean allowed;
3124 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3125 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3126 allowed = true;
3127 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3128 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003129 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003131 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 == PackageManager.SIGNATURE_MATCH);
3133 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3134 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3135 // For updated system applications, the signatureOrSystem permission
3136 // is granted only if it had been defined by the original application.
3137 if ((pkg.applicationInfo.flags
3138 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3139 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3140 if(sysPs.grantedPermissions.contains(perm)) {
3141 allowed = true;
3142 } else {
3143 allowed = false;
3144 }
3145 } else {
3146 allowed = true;
3147 }
3148 }
3149 }
3150 } else {
3151 allowed = false;
3152 }
3153 if (false) {
3154 if (gp != ps) {
3155 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3156 }
3157 }
3158 if (allowed) {
3159 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3160 && ps.permissionsFixed) {
3161 // If this is an existing, non-system package, then
3162 // we can't add any new permissions to it.
3163 if (!gp.loadedPermissions.contains(perm)) {
3164 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003165 // Except... if this is a permission that was added
3166 // to the platform (note: need to only do this when
3167 // updating the platform).
3168 final int NP = PackageParser.NEW_PERMISSIONS.length;
3169 for (int ip=0; ip<NP; ip++) {
3170 final PackageParser.NewPermissionInfo npi
3171 = PackageParser.NEW_PERMISSIONS[ip];
3172 if (npi.name.equals(perm)
3173 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3174 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003175 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003176 + pkg.packageName);
3177 break;
3178 }
3179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 }
3181 }
3182 if (allowed) {
3183 if (!gp.grantedPermissions.contains(perm)) {
3184 addedPermission = true;
3185 gp.grantedPermissions.add(perm);
3186 gp.gids = appendInts(gp.gids, bp.gids);
3187 }
3188 } else {
3189 Log.w(TAG, "Not granting permission " + perm
3190 + " to package " + pkg.packageName
3191 + " because it was previously installed without");
3192 }
3193 } else {
3194 Log.w(TAG, "Not granting permission " + perm
3195 + " to package " + pkg.packageName
3196 + " (protectionLevel=" + p.info.protectionLevel
3197 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3198 + ")");
3199 }
3200 } else {
3201 Log.w(TAG, "Unknown permission " + name
3202 + " in package " + pkg.packageName);
3203 }
3204 }
3205
3206 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003207 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3208 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 // This is the first that we have heard about this package, so the
3210 // permissions we have now selected are fixed until explicitly
3211 // changed.
3212 ps.permissionsFixed = true;
3213 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3214 }
3215 }
3216
3217 private final class ActivityIntentResolver
3218 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003219 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003221 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 }
3223
Mihai Preda074edef2009-05-18 17:13:31 +02003224 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003226 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3228 }
3229
Mihai Predaeae850c2009-05-13 10:13:48 +02003230 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3231 ArrayList<PackageParser.Activity> packageActivities) {
3232 if (packageActivities == null) {
3233 return null;
3234 }
3235 mFlags = flags;
3236 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3237 int N = packageActivities.size();
3238 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3239 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003240
3241 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003242 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003243 intentFilters = packageActivities.get(i).intents;
3244 if (intentFilters != null && intentFilters.size() > 0) {
3245 listCut.add(intentFilters);
3246 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003247 }
3248 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3249 }
3250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 public final void addActivity(PackageParser.Activity a, String type) {
3252 mActivities.put(a.component, a);
3253 if (SHOW_INFO || Config.LOGV) Log.v(
3254 TAG, " " + type + " " +
3255 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3256 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3257 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003258 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3260 if (SHOW_INFO || Config.LOGV) {
3261 Log.v(TAG, " IntentFilter:");
3262 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3263 }
3264 if (!intent.debugCheck()) {
3265 Log.w(TAG, "==> For Activity " + a.info.name);
3266 }
3267 addFilter(intent);
3268 }
3269 }
3270
3271 public final void removeActivity(PackageParser.Activity a, String type) {
3272 mActivities.remove(a.component);
3273 if (SHOW_INFO || Config.LOGV) Log.v(
3274 TAG, " " + type + " " +
3275 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3276 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3277 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003278 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3280 if (SHOW_INFO || Config.LOGV) {
3281 Log.v(TAG, " IntentFilter:");
3282 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3283 }
3284 removeFilter(intent);
3285 }
3286 }
3287
3288 @Override
3289 protected boolean allowFilterResult(
3290 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3291 ActivityInfo filterAi = filter.activity.info;
3292 for (int i=dest.size()-1; i>=0; i--) {
3293 ActivityInfo destAi = dest.get(i).activityInfo;
3294 if (destAi.name == filterAi.name
3295 && destAi.packageName == filterAi.packageName) {
3296 return false;
3297 }
3298 }
3299 return true;
3300 }
3301
3302 @Override
3303 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3304 int match) {
3305 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3306 return null;
3307 }
3308 final PackageParser.Activity activity = info.activity;
3309 if (mSafeMode && (activity.info.applicationInfo.flags
3310 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3311 return null;
3312 }
3313 final ResolveInfo res = new ResolveInfo();
3314 res.activityInfo = PackageParser.generateActivityInfo(activity,
3315 mFlags);
3316 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3317 res.filter = info;
3318 }
3319 res.priority = info.getPriority();
3320 res.preferredOrder = activity.owner.mPreferredOrder;
3321 //System.out.println("Result: " + res.activityInfo.className +
3322 // " = " + res.priority);
3323 res.match = match;
3324 res.isDefault = info.hasDefault;
3325 res.labelRes = info.labelRes;
3326 res.nonLocalizedLabel = info.nonLocalizedLabel;
3327 res.icon = info.icon;
3328 return res;
3329 }
3330
3331 @Override
3332 protected void sortResults(List<ResolveInfo> results) {
3333 Collections.sort(results, mResolvePrioritySorter);
3334 }
3335
3336 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003337 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003339 out.print(prefix); out.print(
3340 Integer.toHexString(System.identityHashCode(filter.activity)));
3341 out.print(' ');
3342 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 }
3344
3345// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3346// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3347// final List<ResolveInfo> retList = Lists.newArrayList();
3348// while (i.hasNext()) {
3349// final ResolveInfo resolveInfo = i.next();
3350// if (isEnabledLP(resolveInfo.activityInfo)) {
3351// retList.add(resolveInfo);
3352// }
3353// }
3354// return retList;
3355// }
3356
3357 // Keys are String (activity class name), values are Activity.
3358 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3359 = new HashMap<ComponentName, PackageParser.Activity>();
3360 private int mFlags;
3361 }
3362
3363 private final class ServiceIntentResolver
3364 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003365 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003367 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 }
3369
Mihai Preda074edef2009-05-18 17:13:31 +02003370 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003372 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3374 }
3375
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003376 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3377 ArrayList<PackageParser.Service> packageServices) {
3378 if (packageServices == null) {
3379 return null;
3380 }
3381 mFlags = flags;
3382 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3383 int N = packageServices.size();
3384 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3385 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3386
3387 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3388 for (int i = 0; i < N; ++i) {
3389 intentFilters = packageServices.get(i).intents;
3390 if (intentFilters != null && intentFilters.size() > 0) {
3391 listCut.add(intentFilters);
3392 }
3393 }
3394 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3395 }
3396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 public final void addService(PackageParser.Service s) {
3398 mServices.put(s.component, s);
3399 if (SHOW_INFO || Config.LOGV) Log.v(
3400 TAG, " " + (s.info.nonLocalizedLabel != null
3401 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3402 if (SHOW_INFO || Config.LOGV) Log.v(
3403 TAG, " Class=" + s.info.name);
3404 int NI = s.intents.size();
3405 int j;
3406 for (j=0; j<NI; j++) {
3407 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3408 if (SHOW_INFO || Config.LOGV) {
3409 Log.v(TAG, " IntentFilter:");
3410 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3411 }
3412 if (!intent.debugCheck()) {
3413 Log.w(TAG, "==> For Service " + s.info.name);
3414 }
3415 addFilter(intent);
3416 }
3417 }
3418
3419 public final void removeService(PackageParser.Service s) {
3420 mServices.remove(s.component);
3421 if (SHOW_INFO || Config.LOGV) Log.v(
3422 TAG, " " + (s.info.nonLocalizedLabel != null
3423 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3424 if (SHOW_INFO || Config.LOGV) Log.v(
3425 TAG, " Class=" + s.info.name);
3426 int NI = s.intents.size();
3427 int j;
3428 for (j=0; j<NI; j++) {
3429 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3430 if (SHOW_INFO || Config.LOGV) {
3431 Log.v(TAG, " IntentFilter:");
3432 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3433 }
3434 removeFilter(intent);
3435 }
3436 }
3437
3438 @Override
3439 protected boolean allowFilterResult(
3440 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3441 ServiceInfo filterSi = filter.service.info;
3442 for (int i=dest.size()-1; i>=0; i--) {
3443 ServiceInfo destAi = dest.get(i).serviceInfo;
3444 if (destAi.name == filterSi.name
3445 && destAi.packageName == filterSi.packageName) {
3446 return false;
3447 }
3448 }
3449 return true;
3450 }
3451
3452 @Override
3453 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3454 int match) {
3455 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3456 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3457 return null;
3458 }
3459 final PackageParser.Service service = info.service;
3460 if (mSafeMode && (service.info.applicationInfo.flags
3461 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3462 return null;
3463 }
3464 final ResolveInfo res = new ResolveInfo();
3465 res.serviceInfo = PackageParser.generateServiceInfo(service,
3466 mFlags);
3467 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3468 res.filter = filter;
3469 }
3470 res.priority = info.getPriority();
3471 res.preferredOrder = service.owner.mPreferredOrder;
3472 //System.out.println("Result: " + res.activityInfo.className +
3473 // " = " + res.priority);
3474 res.match = match;
3475 res.isDefault = info.hasDefault;
3476 res.labelRes = info.labelRes;
3477 res.nonLocalizedLabel = info.nonLocalizedLabel;
3478 res.icon = info.icon;
3479 return res;
3480 }
3481
3482 @Override
3483 protected void sortResults(List<ResolveInfo> results) {
3484 Collections.sort(results, mResolvePrioritySorter);
3485 }
3486
3487 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003488 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003490 out.print(prefix); out.print(
3491 Integer.toHexString(System.identityHashCode(filter.service)));
3492 out.print(' ');
3493 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 }
3495
3496// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3497// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3498// final List<ResolveInfo> retList = Lists.newArrayList();
3499// while (i.hasNext()) {
3500// final ResolveInfo resolveInfo = (ResolveInfo) i;
3501// if (isEnabledLP(resolveInfo.serviceInfo)) {
3502// retList.add(resolveInfo);
3503// }
3504// }
3505// return retList;
3506// }
3507
3508 // Keys are String (activity class name), values are Activity.
3509 private final HashMap<ComponentName, PackageParser.Service> mServices
3510 = new HashMap<ComponentName, PackageParser.Service>();
3511 private int mFlags;
3512 };
3513
3514 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3515 new Comparator<ResolveInfo>() {
3516 public int compare(ResolveInfo r1, ResolveInfo r2) {
3517 int v1 = r1.priority;
3518 int v2 = r2.priority;
3519 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3520 if (v1 != v2) {
3521 return (v1 > v2) ? -1 : 1;
3522 }
3523 v1 = r1.preferredOrder;
3524 v2 = r2.preferredOrder;
3525 if (v1 != v2) {
3526 return (v1 > v2) ? -1 : 1;
3527 }
3528 if (r1.isDefault != r2.isDefault) {
3529 return r1.isDefault ? -1 : 1;
3530 }
3531 v1 = r1.match;
3532 v2 = r2.match;
3533 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3534 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3535 }
3536 };
3537
3538 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3539 new Comparator<ProviderInfo>() {
3540 public int compare(ProviderInfo p1, ProviderInfo p2) {
3541 final int v1 = p1.initOrder;
3542 final int v2 = p2.initOrder;
3543 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3544 }
3545 };
3546
3547 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3548 IActivityManager am = ActivityManagerNative.getDefault();
3549 if (am != null) {
3550 try {
3551 final Intent intent = new Intent(action,
3552 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3553 if (extras != null) {
3554 intent.putExtras(extras);
3555 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07003556 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 am.broadcastIntent(
3558 null, intent,
3559 null, null, 0, null, null, null, false, false);
3560 } catch (RemoteException ex) {
3561 }
3562 }
3563 }
3564
3565 private final class AppDirObserver extends FileObserver {
3566 public AppDirObserver(String path, int mask, boolean isrom) {
3567 super(path, mask);
3568 mRootDir = path;
3569 mIsRom = isrom;
3570 }
3571
3572 public void onEvent(int event, String path) {
3573 String removedPackage = null;
3574 int removedUid = -1;
3575 String addedPackage = null;
3576 int addedUid = -1;
3577
3578 synchronized (mInstallLock) {
3579 String fullPathStr = null;
3580 File fullPath = null;
3581 if (path != null) {
3582 fullPath = new File(mRootDir, path);
3583 fullPathStr = fullPath.getPath();
3584 }
3585
3586 if (Config.LOGV) Log.v(
3587 TAG, "File " + fullPathStr + " changed: "
3588 + Integer.toHexString(event));
3589
3590 if (!isPackageFilename(path)) {
3591 if (Config.LOGV) Log.v(
3592 TAG, "Ignoring change of non-package file: " + fullPathStr);
3593 return;
3594 }
3595
3596 if ((event&REMOVE_EVENTS) != 0) {
3597 synchronized (mInstallLock) {
3598 PackageParser.Package p = mAppDirs.get(fullPathStr);
3599 if (p != null) {
3600 removePackageLI(p, true);
3601 removedPackage = p.applicationInfo.packageName;
3602 removedUid = p.applicationInfo.uid;
3603 }
3604 }
3605 }
3606
3607 if ((event&ADD_EVENTS) != 0) {
3608 PackageParser.Package p = mAppDirs.get(fullPathStr);
3609 if (p == null) {
3610 p = scanPackageLI(fullPath, fullPath, fullPath,
3611 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3612 PackageParser.PARSE_CHATTY |
3613 PackageParser.PARSE_MUST_BE_APK,
3614 SCAN_MONITOR);
3615 if (p != null) {
3616 synchronized (mPackages) {
3617 grantPermissionsLP(p, false);
3618 }
3619 addedPackage = p.applicationInfo.packageName;
3620 addedUid = p.applicationInfo.uid;
3621 }
3622 }
3623 }
3624
3625 synchronized (mPackages) {
3626 mSettings.writeLP();
3627 }
3628 }
3629
3630 if (removedPackage != null) {
3631 Bundle extras = new Bundle(1);
3632 extras.putInt(Intent.EXTRA_UID, removedUid);
3633 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3634 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3635 }
3636 if (addedPackage != null) {
3637 Bundle extras = new Bundle(1);
3638 extras.putInt(Intent.EXTRA_UID, addedUid);
3639 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3640 }
3641 }
3642
3643 private final String mRootDir;
3644 private final boolean mIsRom;
3645 }
Jacek Surazski65e13172009-04-28 15:26:38 +02003646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 /* Called when a downloaded package installation has been confirmed by the user */
3648 public void installPackage(
3649 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02003650 installPackage(packageURI, observer, flags, null);
3651 }
3652
3653 /* Called when a downloaded package installation has been confirmed by the user */
3654 public void installPackage(
3655 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3656 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 mContext.enforceCallingOrSelfPermission(
3658 android.Manifest.permission.INSTALL_PACKAGES, null);
Jacek Surazski65e13172009-04-28 15:26:38 +02003659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 // Queue up an async operation since the package installation may take a little while.
3661 mHandler.post(new Runnable() {
3662 public void run() {
3663 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003664 // Result object to be returned
3665 PackageInstalledInfo res = new PackageInstalledInfo();
3666 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3667 res.uid = -1;
3668 res.pkg = null;
3669 res.removedInfo = new PackageRemovedInfo();
3670 // Make a temporary copy of file from given packageURI
3671 File tmpPackageFile = copyTempInstallFile(packageURI, res);
3672 if (tmpPackageFile != null) {
3673 synchronized (mInstallLock) {
3674 installPackageLI(packageURI, flags, true, installerPackageName, tmpPackageFile, res);
3675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 }
3677 if (observer != null) {
3678 try {
3679 observer.packageInstalled(res.name, res.returnCode);
3680 } catch (RemoteException e) {
3681 Log.i(TAG, "Observer no longer exists.");
3682 }
3683 }
3684 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
3685 // call appears in the synchronized block above.
3686 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3687 res.removedInfo.sendBroadcast(false, true);
3688 Bundle extras = new Bundle(1);
3689 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003690 final boolean update = res.removedInfo.removedPackage != null;
3691 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 extras.putBoolean(Intent.EXTRA_REPLACING, true);
3693 }
3694 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
3695 res.pkg.applicationInfo.packageName,
3696 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003697 if (update) {
3698 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
3699 res.pkg.applicationInfo.packageName,
3700 extras);
3701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 }
3703 Runtime.getRuntime().gc();
3704 }
3705 });
3706 }
3707
3708 class PackageInstalledInfo {
3709 String name;
3710 int uid;
3711 PackageParser.Package pkg;
3712 int returnCode;
3713 PackageRemovedInfo removedInfo;
3714 }
3715
3716 /*
3717 * Install a non-existing package.
3718 */
3719 private void installNewPackageLI(String pkgName,
3720 File tmpPackageFile,
3721 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003722 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003723 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 // Remember this for later, in case we need to rollback this install
3725 boolean dataDirExists = (new File(mAppDataDir, pkgName)).exists();
3726 res.name = pkgName;
3727 synchronized(mPackages) {
3728 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(destFilePath)) {
3729 // Don't allow installation over an existing package with the same name.
3730 Log.w(TAG, "Attempt to re-install " + pkgName
3731 + " without first uninstalling.");
3732 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
3733 return;
3734 }
3735 }
3736 if (destPackageFile.exists()) {
3737 // It's safe to do this because we know (from the above check) that the file
3738 // isn't currently used for an installed package.
3739 destPackageFile.delete();
3740 }
3741 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3742 PackageParser.Package newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3743 destResourceFile, pkg, 0,
3744 SCAN_MONITOR | SCAN_FORCE_DEX
3745 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003746 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3747 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 if (newPackage == null) {
3749 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3750 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3751 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3752 }
3753 } else {
3754 updateSettingsLI(pkgName, tmpPackageFile,
3755 destFilePath, destPackageFile,
3756 destResourceFile, pkg,
3757 newPackage,
3758 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02003759 forwardLocked,
3760 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 res);
3762 // delete the partially installed application. the data directory will have to be
3763 // restored if it was already existing
3764 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3765 // remove package from internal structures. Note that we want deletePackageX to
3766 // delete the package data and cache directories that it created in
3767 // scanPackageLocked, unless those directories existed before we even tried to
3768 // install.
3769 deletePackageLI(
3770 pkgName, true,
3771 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
3772 res.removedInfo);
3773 }
3774 }
3775 }
3776
3777 private void replacePackageLI(String pkgName,
3778 File tmpPackageFile,
3779 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003780 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003781 String installerPackageName, PackageInstalledInfo res) {
3782
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003783 PackageParser.Package oldPackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 // First find the old package info and check signatures
3785 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003786 oldPackage = mPackages.get(pkgName);
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003787 if(checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
3788 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3790 return;
3791 }
3792 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003793 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 if(sysPkg) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003795 replaceSystemPackageLI(oldPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796 tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003797 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003798 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 } else {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003800 replaceNonSystemPackageLI(oldPackage, tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003801 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003802 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003803 }
3804 }
3805
3806 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
3807 File tmpPackageFile,
3808 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003809 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003810 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 PackageParser.Package newPackage = null;
3812 String pkgName = deletedPackage.packageName;
3813 boolean deletedPkg = true;
3814 boolean updatedSettings = false;
Jacek Surazski65e13172009-04-28 15:26:38 +02003815
3816 String oldInstallerPackageName = null;
3817 synchronized (mPackages) {
3818 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
3819 }
3820
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003821 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 // First delete the existing package while retaining the data directory
3823 if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
3824 res.removedInfo)) {
3825 // If the existing package was'nt successfully deleted
3826 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3827 deletedPkg = false;
3828 } else {
3829 // Successfully deleted the old package. Now proceed with re-installation
3830 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3831 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3832 destResourceFile, pkg, parseFlags,
3833 SCAN_MONITOR | SCAN_FORCE_DEX
3834 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003835 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3836 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 if (newPackage == null) {
3838 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3839 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3840 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3841 }
3842 } else {
3843 updateSettingsLI(pkgName, tmpPackageFile,
3844 destFilePath, destPackageFile,
3845 destResourceFile, pkg,
3846 newPackage,
3847 true,
3848 forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003849 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 res);
3851 updatedSettings = true;
3852 }
3853 }
3854
3855 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3856 // If we deleted an exisiting package, the old source and resource files that we
3857 // were keeping around in case we needed them (see below) can now be deleted
3858 final ApplicationInfo deletedPackageAppInfo = deletedPackage.applicationInfo;
3859 final ApplicationInfo installedPackageAppInfo =
3860 newPackage.applicationInfo;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07003861 deletePackageResourcesLI(pkgName,
3862 !deletedPackageAppInfo.sourceDir
3863 .equals(installedPackageAppInfo.sourceDir)
3864 ? deletedPackageAppInfo.sourceDir : null,
3865 !deletedPackageAppInfo.publicSourceDir
3866 .equals(installedPackageAppInfo.publicSourceDir)
3867 ? deletedPackageAppInfo.publicSourceDir : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 //update signature on the new package setting
3869 //this should always succeed, since we checked the
3870 //signature earlier.
3871 synchronized(mPackages) {
3872 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
3873 parseFlags, true);
3874 }
3875 } else {
3876 // remove package from internal structures. Note that we want deletePackageX to
3877 // delete the package data and cache directories that it created in
3878 // scanPackageLocked, unless those directories existed before we even tried to
3879 // install.
3880 if(updatedSettings) {
3881 deletePackageLI(
3882 pkgName, true,
3883 PackageManager.DONT_DELETE_DATA,
3884 res.removedInfo);
3885 }
3886 // Since we failed to install the new package we need to restore the old
3887 // package that we deleted.
3888 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003889 File restoreFile = new File(deletedPackage.mPath);
3890 if (restoreFile == null) {
3891 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
3892 return;
3893 }
3894 File restoreTmpFile = createTempPackageFile();
3895 if (restoreTmpFile == null) {
3896 Log.e(TAG, "Failed creating temp file when restoring pkg : " + pkgName);
3897 return;
3898 }
3899 if (!FileUtils.copyFile(restoreFile, restoreTmpFile)) {
3900 Log.e(TAG, "Failed copying temp file when restoring pkg : " + pkgName);
3901 return;
3902 }
3903 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
3904 restoreRes.removedInfo = new PackageRemovedInfo();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 installPackageLI(
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003906 Uri.fromFile(restoreFile),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 isForwardLocked(deletedPackage)
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003908 ? PackageManager.INSTALL_FORWARD_LOCK
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07003909 : 0, false, oldInstallerPackageName, restoreTmpFile, restoreRes);
3910 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3911 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
3912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 }
3914 }
3915 }
3916
3917 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
3918 File tmpPackageFile,
3919 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003920 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003921 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 PackageParser.Package newPackage = null;
3923 boolean updatedSettings = false;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003924 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 PackageParser.PARSE_IS_SYSTEM;
3926 String packageName = deletedPackage.packageName;
3927 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3928 if (packageName == null) {
3929 Log.w(TAG, "Attempt to delete null packageName.");
3930 return;
3931 }
3932 PackageParser.Package oldPkg;
3933 PackageSetting oldPkgSetting;
3934 synchronized (mPackages) {
3935 oldPkg = mPackages.get(packageName);
3936 oldPkgSetting = mSettings.mPackages.get(packageName);
3937 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
3938 (oldPkgSetting == null)) {
3939 Log.w(TAG, "Could'nt find package:"+packageName+" information");
3940 return;
3941 }
3942 }
3943 res.removedInfo.uid = oldPkg.applicationInfo.uid;
3944 res.removedInfo.removedPackage = packageName;
3945 // Remove existing system package
3946 removePackageLI(oldPkg, true);
3947 synchronized (mPackages) {
3948 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
3949 }
3950
3951 // Successfully disabled the old package. Now proceed with re-installation
3952 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3953 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3954 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3955 destResourceFile, pkg, parseFlags,
3956 SCAN_MONITOR | SCAN_FORCE_DEX
3957 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003958 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3959 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 if (newPackage == null) {
3961 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3962 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3963 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3964 }
3965 } else {
3966 updateSettingsLI(packageName, tmpPackageFile,
3967 destFilePath, destPackageFile,
3968 destResourceFile, pkg,
3969 newPackage,
3970 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02003971 forwardLocked,
3972 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 res);
3974 updatedSettings = true;
3975 }
3976
3977 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3978 //update signature on the new package setting
3979 //this should always succeed, since we checked the
3980 //signature earlier.
3981 synchronized(mPackages) {
3982 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
3983 parseFlags, true);
3984 }
3985 } else {
3986 // Re installation failed. Restore old information
3987 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07003988 if (newPackage != null) {
3989 removePackageLI(newPackage, true);
3990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 // Add back the old system package
3992 scanPackageLI(oldPkgSetting.codePath, oldPkgSetting.codePath,
3993 oldPkgSetting.resourcePath,
3994 oldPkg, parseFlags,
3995 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07003996 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 // Restore the old system information in Settings
3998 synchronized(mPackages) {
3999 if(updatedSettings) {
4000 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02004001 mSettings.setInstallerPackageName(packageName,
4002 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 }
4004 mSettings.writeLP();
4005 }
4006 }
4007 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 private void updateSettingsLI(String pkgName, File tmpPackageFile,
4010 String destFilePath, File destPackageFile,
4011 File destResourceFile,
4012 PackageParser.Package pkg,
4013 PackageParser.Package newPackage,
4014 boolean replacingExistingPackage,
4015 boolean forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02004016 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 synchronized (mPackages) {
4018 //write settings. the installStatus will be incomplete at this stage.
4019 //note that the new package setting would have already been
4020 //added to mPackages. It hasn't been persisted yet.
4021 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
4022 mSettings.writeLP();
4023 }
4024
4025 int retCode = 0;
4026 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4027 retCode = mInstaller.movedex(tmpPackageFile.toString(),
4028 destPackageFile.toString());
4029 if (retCode != 0) {
4030 Log.e(TAG, "Couldn't rename dex file: " + destPackageFile);
4031 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4032 return;
4033 }
4034 }
4035 // XXX There are probably some big issues here: upon doing
4036 // the rename, we have reached the point of no return (the
4037 // original .apk is gone!), so we can't fail. Yet... we can.
4038 if (!tmpPackageFile.renameTo(destPackageFile)) {
4039 Log.e(TAG, "Couldn't move package file to: " + destPackageFile);
4040 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4041 } else {
4042 res.returnCode = setPermissionsLI(pkgName, newPackage, destFilePath,
4043 destResourceFile,
4044 forwardLocked);
4045 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4046 return;
4047 } else {
4048 Log.d(TAG, "New package installed in " + destPackageFile);
4049 }
4050 }
4051 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4052 if (mInstaller != null) {
4053 mInstaller.rmdex(tmpPackageFile.getPath());
4054 }
4055 }
4056
4057 synchronized (mPackages) {
4058 grantPermissionsLP(newPackage, true);
4059 res.name = pkgName;
4060 res.uid = newPackage.applicationInfo.uid;
4061 res.pkg = newPackage;
4062 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02004063 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4065 //to update install status
4066 mSettings.writeLP();
4067 }
4068 }
4069
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07004070 private File getFwdLockedResource(String pkgName) {
4071 final String publicZipFileName = pkgName + ".zip";
4072 return new File(mAppInstallDir, publicZipFileName);
4073 }
4074
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004075 private File copyTempInstallFile(Uri pPackageURI,
4076 PackageInstalledInfo res) {
4077 File tmpPackageFile = createTempPackageFile();
4078 int retCode = PackageManager.INSTALL_SUCCEEDED;
4079 if (tmpPackageFile == null) {
4080 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4081 return null;
4082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004084 if (pPackageURI.getScheme().equals("file")) {
4085 final File srcPackageFile = new File(pPackageURI.getPath());
4086 // We copy the source package file to a temp file and then rename it to the
4087 // destination file in order to eliminate a window where the package directory
4088 // scanner notices the new package file but it's not completely copied yet.
4089 if (!FileUtils.copyFile(srcPackageFile, tmpPackageFile)) {
4090 Log.e(TAG, "Couldn't copy package file to temp file.");
4091 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004093 } else if (pPackageURI.getScheme().equals("content")) {
4094 ParcelFileDescriptor fd = null;
4095 try {
4096 fd = mContext.getContentResolver().openFileDescriptor(pPackageURI, "r");
4097 } catch (FileNotFoundException e) {
4098 Log.e(TAG, "Couldn't open file descriptor from download service. Failed with exception " + e);
4099 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4100 }
4101 if (fd == null) {
4102 Log.e(TAG, "Couldn't open file descriptor from download service (null).");
4103 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4104 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 if (Config.LOGV) {
4106 Log.v(TAG, "Opened file descriptor from download service.");
4107 }
4108 ParcelFileDescriptor.AutoCloseInputStream
4109 dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
4110 // We copy the source package file to a temp file and then rename it to the
4111 // destination file in order to eliminate a window where the package directory
4112 // scanner notices the new package file but it's not completely copied yet.
4113 if (!FileUtils.copyToFile(dlStream, tmpPackageFile)) {
4114 Log.e(TAG, "Couldn't copy package stream to temp file.");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004115 retCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004118 } else {
4119 Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
4120 retCode = PackageManager.INSTALL_FAILED_INVALID_URI;
4121 }
4122
4123 res.returnCode = retCode;
4124 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
4125 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4126 tmpPackageFile.delete();
4127 }
4128 return null;
4129 }
4130 return tmpPackageFile;
4131 }
4132
4133 private void installPackageLI(Uri pPackageURI,
4134 int pFlags, boolean newInstall, String installerPackageName,
4135 File tmpPackageFile, PackageInstalledInfo res) {
4136 String pkgName = null;
4137 boolean forwardLocked = false;
4138 boolean replacingExistingPackage = false;
4139 // Result object to be returned
4140 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
4141
4142 main_flow: try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 pkgName = PackageParser.parsePackageName(
4144 tmpPackageFile.getAbsolutePath(), 0);
4145 if (pkgName == null) {
4146 Log.e(TAG, "Couldn't find a package name in : " + tmpPackageFile);
4147 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4148 break main_flow;
4149 }
4150 res.name = pkgName;
4151 //initialize some variables before installing pkg
4152 final String pkgFileName = pkgName + ".apk";
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004153 final File destDir = ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 ? mDrmAppPrivateInstallDir
4155 : mAppInstallDir;
4156 final File destPackageFile = new File(destDir, pkgFileName);
4157 final String destFilePath = destPackageFile.getAbsolutePath();
4158 File destResourceFile;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004159 if ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0) {
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07004160 destResourceFile = getFwdLockedResource(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004161 forwardLocked = true;
4162 } else {
4163 destResourceFile = destPackageFile;
4164 }
4165 // Retrieve PackageSettings and parse package
4166 int parseFlags = PackageParser.PARSE_CHATTY;
4167 parseFlags |= mDefParseFlags;
4168 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
4169 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
4171 destPackageFile.getAbsolutePath(), mMetrics, parseFlags);
4172 if (pkg == null) {
4173 res.returnCode = pp.getParseError();
4174 break main_flow;
4175 }
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004176 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
4177 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
4178 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
4179 break main_flow;
4180 }
4181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
4183 res.returnCode = pp.getParseError();
4184 break main_flow;
4185 }
4186
4187 synchronized (mPackages) {
4188 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07004189 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 && mPackages.containsKey(pkgName)) {
4191 replacingExistingPackage = true;
4192 }
4193 }
4194
4195 if(replacingExistingPackage) {
4196 replacePackageLI(pkgName,
4197 tmpPackageFile,
4198 destFilePath, destPackageFile, destResourceFile,
Jacek Surazski65e13172009-04-28 15:26:38 +02004199 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 res);
4201 } else {
4202 installNewPackageLI(pkgName,
4203 tmpPackageFile,
4204 destFilePath, destPackageFile, destResourceFile,
Jacek Surazski65e13172009-04-28 15:26:38 +02004205 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 res);
4207 }
4208 } finally {
4209 if (tmpPackageFile != null && tmpPackageFile.exists()) {
4210 tmpPackageFile.delete();
4211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 }
4213 }
4214
4215 private int setPermissionsLI(String pkgName,
4216 PackageParser.Package newPackage,
4217 String destFilePath,
4218 File destResourceFile,
4219 boolean forwardLocked) {
4220 int retCode;
4221 if (forwardLocked) {
4222 try {
4223 extractPublicFiles(newPackage, destResourceFile);
4224 } catch (IOException e) {
4225 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
4226 " forward-locked app.");
4227 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4228 } finally {
4229 //TODO clean up the extracted public files
4230 }
4231 if (mInstaller != null) {
4232 retCode = mInstaller.setForwardLockPerm(pkgName,
4233 newPackage.applicationInfo.uid);
4234 } else {
4235 final int filePermissions =
4236 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
4237 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1,
4238 newPackage.applicationInfo.uid);
4239 }
4240 } else {
4241 final int filePermissions =
4242 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4243 |FileUtils.S_IROTH;
4244 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1, -1);
4245 }
4246 if (retCode != 0) {
4247 Log.e(TAG, "Couldn't set new package file permissions for " + destFilePath
4248 + ". The return code was: " + retCode);
4249 }
4250 return PackageManager.INSTALL_SUCCEEDED;
4251 }
4252
4253 private boolean isForwardLocked(PackageParser.Package deletedPackage) {
4254 final ApplicationInfo applicationInfo = deletedPackage.applicationInfo;
4255 return applicationInfo.sourceDir.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath());
4256 }
4257
4258 private void extractPublicFiles(PackageParser.Package newPackage,
4259 File publicZipFile) throws IOException {
4260 final ZipOutputStream publicZipOutStream =
4261 new ZipOutputStream(new FileOutputStream(publicZipFile));
4262 final ZipFile privateZip = new ZipFile(newPackage.mPath);
4263
4264 // Copy manifest, resources.arsc and res directory to public zip
4265
4266 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
4267 while (privateZipEntries.hasMoreElements()) {
4268 final ZipEntry zipEntry = privateZipEntries.nextElement();
4269 final String zipEntryName = zipEntry.getName();
4270 if ("AndroidManifest.xml".equals(zipEntryName)
4271 || "resources.arsc".equals(zipEntryName)
4272 || zipEntryName.startsWith("res/")) {
4273 try {
4274 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
4275 } catch (IOException e) {
4276 try {
4277 publicZipOutStream.close();
4278 throw e;
4279 } finally {
4280 publicZipFile.delete();
4281 }
4282 }
4283 }
4284 }
4285
4286 publicZipOutStream.close();
4287 FileUtils.setPermissions(
4288 publicZipFile.getAbsolutePath(),
4289 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
4290 -1, -1);
4291 }
4292
4293 private static void copyZipEntry(ZipEntry zipEntry,
4294 ZipFile inZipFile,
4295 ZipOutputStream outZipStream) throws IOException {
4296 byte[] buffer = new byte[4096];
4297 int num;
4298
4299 ZipEntry newEntry;
4300 if (zipEntry.getMethod() == ZipEntry.STORED) {
4301 // Preserve the STORED method of the input entry.
4302 newEntry = new ZipEntry(zipEntry);
4303 } else {
4304 // Create a new entry so that the compressed len is recomputed.
4305 newEntry = new ZipEntry(zipEntry.getName());
4306 }
4307 outZipStream.putNextEntry(newEntry);
4308
4309 InputStream data = inZipFile.getInputStream(zipEntry);
4310 while ((num = data.read(buffer)) > 0) {
4311 outZipStream.write(buffer, 0, num);
4312 }
4313 outZipStream.flush();
4314 }
4315
4316 private void deleteTempPackageFiles() {
4317 FilenameFilter filter = new FilenameFilter() {
4318 public boolean accept(File dir, String name) {
4319 return name.startsWith("vmdl") && name.endsWith(".tmp");
4320 }
4321 };
4322 String tmpFilesList[] = mAppInstallDir.list(filter);
4323 if(tmpFilesList == null) {
4324 return;
4325 }
4326 for(int i = 0; i < tmpFilesList.length; i++) {
4327 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
4328 tmpFile.delete();
4329 }
4330 }
4331
4332 private File createTempPackageFile() {
4333 File tmpPackageFile;
4334 try {
4335 tmpPackageFile = File.createTempFile("vmdl", ".tmp", mAppInstallDir);
4336 } catch (IOException e) {
4337 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
4338 return null;
4339 }
4340 try {
4341 FileUtils.setPermissions(
4342 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
4343 -1, -1);
4344 } catch (IOException e) {
4345 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
4346 return null;
4347 }
4348 return tmpPackageFile;
4349 }
4350
4351 public void deletePackage(final String packageName,
4352 final IPackageDeleteObserver observer,
4353 final int flags) {
4354 mContext.enforceCallingOrSelfPermission(
4355 android.Manifest.permission.DELETE_PACKAGES, null);
4356 // Queue up an async operation since the package deletion may take a little while.
4357 mHandler.post(new Runnable() {
4358 public void run() {
4359 mHandler.removeCallbacks(this);
4360 final boolean succeded = deletePackageX(packageName, true, true, flags);
4361 if (observer != null) {
4362 try {
4363 observer.packageDeleted(succeded);
4364 } catch (RemoteException e) {
4365 Log.i(TAG, "Observer no longer exists.");
4366 } //end catch
4367 } //end if
4368 } //end run
4369 });
4370 }
4371
4372 /**
4373 * This method is an internal method that could be get invoked either
4374 * to delete an installed package or to clean up a failed installation.
4375 * After deleting an installed package, a broadcast is sent to notify any
4376 * listeners that the package has been installed. For cleaning up a failed
4377 * installation, the broadcast is not necessary since the package's
4378 * installation wouldn't have sent the initial broadcast either
4379 * The key steps in deleting a package are
4380 * deleting the package information in internal structures like mPackages,
4381 * deleting the packages base directories through installd
4382 * updating mSettings to reflect current status
4383 * persisting settings for later use
4384 * sending a broadcast if necessary
4385 */
4386
4387 private boolean deletePackageX(String packageName, boolean sendBroadCast,
4388 boolean deleteCodeAndResources, int flags) {
4389 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07004390 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391
4392 synchronized (mInstallLock) {
4393 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
4394 }
4395
4396 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004397 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4398 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4399
4400 // If the removed package was a system update, the old system packaged
4401 // was re-enabled; we need to broadcast this information
4402 if (systemUpdate) {
4403 Bundle extras = new Bundle(1);
4404 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4405 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4406
4407 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4408 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410 }
4411 return res;
4412 }
4413
4414 static class PackageRemovedInfo {
4415 String removedPackage;
4416 int uid = -1;
4417 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004418 boolean isRemovedPackageSystemUpdate = false;
4419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420 void sendBroadcast(boolean fullRemove, boolean replacing) {
4421 Bundle extras = new Bundle(1);
4422 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4423 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4424 if (replacing) {
4425 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4426 }
4427 if (removedPackage != null) {
4428 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4429 }
4430 if (removedUid >= 0) {
4431 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
4432 }
4433 }
4434 }
4435
4436 /*
4437 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
4438 * flag is not set, the data directory is removed as well.
4439 * make sure this flag is set for partially installed apps. If not its meaningless to
4440 * delete a partially installed application.
4441 */
4442 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
4443 int flags) {
4444 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004445 if (outInfo != null) {
4446 outInfo.removedPackage = packageName;
4447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004448 removePackageLI(p, true);
4449 // Retrieve object to delete permissions for shared user later on
4450 PackageSetting deletedPs;
4451 synchronized (mPackages) {
4452 deletedPs = mSettings.mPackages.get(packageName);
4453 }
4454 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
4455 if (mInstaller != null) {
4456 int retCode = mInstaller.remove(packageName);
4457 if (retCode < 0) {
4458 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
4459 + packageName + ", retcode=" + retCode);
4460 // we don't consider this to be a failure of the core package deletion
4461 }
4462 } else {
4463 //for emulator
4464 PackageParser.Package pkg = mPackages.get(packageName);
4465 File dataDir = new File(pkg.applicationInfo.dataDir);
4466 dataDir.delete();
4467 }
4468 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004469 if (outInfo != null) {
4470 outInfo.removedUid = mSettings.removePackageLP(packageName);
4471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004472 }
4473 }
4474 synchronized (mPackages) {
4475 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
4476 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07004477 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 }
4479 // Save settings now
4480 mSettings.writeLP ();
4481 }
4482 }
4483
4484 /*
4485 * Tries to delete system package.
4486 */
4487 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004488 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 ApplicationInfo applicationInfo = p.applicationInfo;
4490 //applicable for non-partially installed applications only
4491 if (applicationInfo == null) {
4492 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4493 return false;
4494 }
4495 PackageSetting ps = null;
4496 // Confirm if the system package has been updated
4497 // An updated system app can be deleted. This will also have to restore
4498 // the system pkg from system partition
4499 synchronized (mPackages) {
4500 ps = mSettings.getDisabledSystemPkg(p.packageName);
4501 }
4502 if (ps == null) {
4503 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
4504 return false;
4505 } else {
4506 Log.i(TAG, "Deleting system pkg from data partition");
4507 }
4508 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07004509 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004510 boolean deleteCodeAndResources = false;
4511 if (ps.versionCode < p.mVersionCode) {
4512 // Delete code and resources for downgrades
4513 deleteCodeAndResources = true;
4514 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4515 flags &= ~PackageManager.DONT_DELETE_DATA;
4516 }
4517 } else {
4518 // Preserve data by setting flag
4519 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4520 flags |= PackageManager.DONT_DELETE_DATA;
4521 }
4522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
4524 if (!ret) {
4525 return false;
4526 }
4527 synchronized (mPackages) {
4528 // Reinstate the old system package
4529 mSettings.enableSystemPackageLP(p.packageName);
4530 }
4531 // Install the system package
4532 PackageParser.Package newPkg = scanPackageLI(ps.codePath, ps.codePath, ps.resourcePath,
4533 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
4534 SCAN_MONITOR);
4535
4536 if (newPkg == null) {
4537 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
4538 return false;
4539 }
4540 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07004541 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004542 mSettings.writeLP();
4543 }
4544 return true;
4545 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004546
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004547 private void deletePackageResourcesLI(String packageName,
4548 String sourceDir, String publicSourceDir) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004549 if (sourceDir != null) {
4550 File sourceFile = new File(sourceDir);
4551 if (!sourceFile.exists()) {
4552 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4553 }
4554 // Delete application's code and resources
4555 sourceFile.delete();
4556 if (mInstaller != null) {
4557 int retCode = mInstaller.rmdex(sourceFile.toString());
4558 if (retCode < 0) {
4559 Log.w(TAG, "Couldn't remove dex file for package: "
4560 + packageName + " at location "
4561 + sourceFile.toString() + ", retcode=" + retCode);
4562 // we don't consider this to be a failure of the core package deletion
4563 }
4564 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004565 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07004566 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4567 final File publicSourceFile = new File(publicSourceDir);
4568 if (!publicSourceFile.exists()) {
4569 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4570 }
4571 if (publicSourceFile.exists()) {
4572 publicSourceFile.delete();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004573 }
4574 }
4575 }
4576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 private boolean deleteInstalledPackageLI(PackageParser.Package p,
4578 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4579 ApplicationInfo applicationInfo = p.applicationInfo;
4580 if (applicationInfo == null) {
4581 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4582 return false;
4583 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004584 if (outInfo != null) {
4585 outInfo.uid = applicationInfo.uid;
4586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587
4588 // Delete package data from internal structures and also remove data if flag is set
4589 removePackageDataLI(p, outInfo, flags);
4590
4591 // Delete application code and resources
4592 if (deleteCodeAndResources) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004593 deletePackageResourcesLI(applicationInfo.packageName,
4594 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 }
4596 return true;
4597 }
4598
4599 /*
4600 * This method handles package deletion in general
4601 */
4602 private boolean deletePackageLI(String packageName,
4603 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4604 if (packageName == null) {
4605 Log.w(TAG, "Attempt to delete null packageName.");
4606 return false;
4607 }
4608 PackageParser.Package p;
4609 boolean dataOnly = false;
4610 synchronized (mPackages) {
4611 p = mPackages.get(packageName);
4612 if (p == null) {
4613 //this retrieves partially installed apps
4614 dataOnly = true;
4615 PackageSetting ps = mSettings.mPackages.get(packageName);
4616 if (ps == null) {
4617 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4618 return false;
4619 }
4620 p = ps.pkg;
4621 }
4622 }
4623 if (p == null) {
4624 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4625 return false;
4626 }
4627
4628 if (dataOnly) {
4629 // Delete application data first
4630 removePackageDataLI(p, outInfo, flags);
4631 return true;
4632 }
4633 // At this point the package should have ApplicationInfo associated with it
4634 if (p.applicationInfo == null) {
4635 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4636 return false;
4637 }
4638 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4639 Log.i(TAG, "Removing system package:"+p.packageName);
4640 // When an updated system application is deleted we delete the existing resources as well and
4641 // fall back to existing code in system partition
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004642 return deleteSystemPackageLI(p, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004643 }
4644 Log.i(TAG, "Removing non-system package:"+p.packageName);
4645 return deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
4646 }
4647
4648 public void clearApplicationUserData(final String packageName,
4649 final IPackageDataObserver observer) {
4650 mContext.enforceCallingOrSelfPermission(
4651 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4652 // Queue up an async operation since the package deletion may take a little while.
4653 mHandler.post(new Runnable() {
4654 public void run() {
4655 mHandler.removeCallbacks(this);
4656 final boolean succeeded;
4657 synchronized (mInstallLock) {
4658 succeeded = clearApplicationUserDataLI(packageName);
4659 }
4660 if (succeeded) {
4661 // invoke DeviceStorageMonitor's update method to clear any notifications
4662 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4663 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4664 if (dsm != null) {
4665 dsm.updateMemory();
4666 }
4667 }
4668 if(observer != null) {
4669 try {
4670 observer.onRemoveCompleted(packageName, succeeded);
4671 } catch (RemoteException e) {
4672 Log.i(TAG, "Observer no longer exists.");
4673 }
4674 } //end if observer
4675 } //end run
4676 });
4677 }
4678
4679 private boolean clearApplicationUserDataLI(String packageName) {
4680 if (packageName == null) {
4681 Log.w(TAG, "Attempt to delete null packageName.");
4682 return false;
4683 }
4684 PackageParser.Package p;
4685 boolean dataOnly = false;
4686 synchronized (mPackages) {
4687 p = mPackages.get(packageName);
4688 if(p == null) {
4689 dataOnly = true;
4690 PackageSetting ps = mSettings.mPackages.get(packageName);
4691 if((ps == null) || (ps.pkg == null)) {
4692 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4693 return false;
4694 }
4695 p = ps.pkg;
4696 }
4697 }
4698 if(!dataOnly) {
4699 //need to check this only for fully installed applications
4700 if (p == null) {
4701 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4702 return false;
4703 }
4704 final ApplicationInfo applicationInfo = p.applicationInfo;
4705 if (applicationInfo == null) {
4706 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4707 return false;
4708 }
4709 }
4710 if (mInstaller != null) {
4711 int retCode = mInstaller.clearUserData(packageName);
4712 if (retCode < 0) {
4713 Log.w(TAG, "Couldn't remove cache files for package: "
4714 + packageName);
4715 return false;
4716 }
4717 }
4718 return true;
4719 }
4720
4721 public void deleteApplicationCacheFiles(final String packageName,
4722 final IPackageDataObserver observer) {
4723 mContext.enforceCallingOrSelfPermission(
4724 android.Manifest.permission.DELETE_CACHE_FILES, null);
4725 // Queue up an async operation since the package deletion may take a little while.
4726 mHandler.post(new Runnable() {
4727 public void run() {
4728 mHandler.removeCallbacks(this);
4729 final boolean succeded;
4730 synchronized (mInstallLock) {
4731 succeded = deleteApplicationCacheFilesLI(packageName);
4732 }
4733 if(observer != null) {
4734 try {
4735 observer.onRemoveCompleted(packageName, succeded);
4736 } catch (RemoteException e) {
4737 Log.i(TAG, "Observer no longer exists.");
4738 }
4739 } //end if observer
4740 } //end run
4741 });
4742 }
4743
4744 private boolean deleteApplicationCacheFilesLI(String packageName) {
4745 if (packageName == null) {
4746 Log.w(TAG, "Attempt to delete null packageName.");
4747 return false;
4748 }
4749 PackageParser.Package p;
4750 synchronized (mPackages) {
4751 p = mPackages.get(packageName);
4752 }
4753 if (p == null) {
4754 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4755 return false;
4756 }
4757 final ApplicationInfo applicationInfo = p.applicationInfo;
4758 if (applicationInfo == null) {
4759 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4760 return false;
4761 }
4762 if (mInstaller != null) {
4763 int retCode = mInstaller.deleteCacheFiles(packageName);
4764 if (retCode < 0) {
4765 Log.w(TAG, "Couldn't remove cache files for package: "
4766 + packageName);
4767 return false;
4768 }
4769 }
4770 return true;
4771 }
4772
4773 public void getPackageSizeInfo(final String packageName,
4774 final IPackageStatsObserver observer) {
4775 mContext.enforceCallingOrSelfPermission(
4776 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4777 // Queue up an async operation since the package deletion may take a little while.
4778 mHandler.post(new Runnable() {
4779 public void run() {
4780 mHandler.removeCallbacks(this);
4781 PackageStats lStats = new PackageStats(packageName);
4782 final boolean succeded;
4783 synchronized (mInstallLock) {
4784 succeded = getPackageSizeInfoLI(packageName, lStats);
4785 }
4786 if(observer != null) {
4787 try {
4788 observer.onGetStatsCompleted(lStats, succeded);
4789 } catch (RemoteException e) {
4790 Log.i(TAG, "Observer no longer exists.");
4791 }
4792 } //end if observer
4793 } //end run
4794 });
4795 }
4796
4797 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4798 if (packageName == null) {
4799 Log.w(TAG, "Attempt to get size of null packageName.");
4800 return false;
4801 }
4802 PackageParser.Package p;
4803 boolean dataOnly = false;
4804 synchronized (mPackages) {
4805 p = mPackages.get(packageName);
4806 if(p == null) {
4807 dataOnly = true;
4808 PackageSetting ps = mSettings.mPackages.get(packageName);
4809 if((ps == null) || (ps.pkg == null)) {
4810 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4811 return false;
4812 }
4813 p = ps.pkg;
4814 }
4815 }
4816 String publicSrcDir = null;
4817 if(!dataOnly) {
4818 final ApplicationInfo applicationInfo = p.applicationInfo;
4819 if (applicationInfo == null) {
4820 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4821 return false;
4822 }
4823 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4824 }
4825 if (mInstaller != null) {
4826 int res = mInstaller.getSizeInfo(packageName, p.mPath,
4827 publicSrcDir, pStats);
4828 if (res < 0) {
4829 return false;
4830 } else {
4831 return true;
4832 }
4833 }
4834 return true;
4835 }
4836
4837
4838 public void addPackageToPreferred(String packageName) {
4839 mContext.enforceCallingOrSelfPermission(
4840 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4841
4842 synchronized (mPackages) {
4843 PackageParser.Package p = mPackages.get(packageName);
4844 if (p == null) {
4845 return;
4846 }
4847 PackageSetting ps = (PackageSetting)p.mExtras;
4848 if (ps != null) {
4849 mSettings.mPreferredPackages.remove(ps);
4850 mSettings.mPreferredPackages.add(0, ps);
4851 updatePreferredIndicesLP();
4852 mSettings.writeLP();
4853 }
4854 }
4855 }
4856
4857 public void removePackageFromPreferred(String packageName) {
4858 mContext.enforceCallingOrSelfPermission(
4859 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4860
4861 synchronized (mPackages) {
4862 PackageParser.Package p = mPackages.get(packageName);
4863 if (p == null) {
4864 return;
4865 }
4866 if (p.mPreferredOrder > 0) {
4867 PackageSetting ps = (PackageSetting)p.mExtras;
4868 if (ps != null) {
4869 mSettings.mPreferredPackages.remove(ps);
4870 p.mPreferredOrder = 0;
4871 updatePreferredIndicesLP();
4872 mSettings.writeLP();
4873 }
4874 }
4875 }
4876 }
4877
4878 private void updatePreferredIndicesLP() {
4879 final ArrayList<PackageSetting> pkgs
4880 = mSettings.mPreferredPackages;
4881 final int N = pkgs.size();
4882 for (int i=0; i<N; i++) {
4883 pkgs.get(i).pkg.mPreferredOrder = N - i;
4884 }
4885 }
4886
4887 public List<PackageInfo> getPreferredPackages(int flags) {
4888 synchronized (mPackages) {
4889 final ArrayList<PackageInfo> res = new ArrayList<PackageInfo>();
4890 final ArrayList<PackageSetting> pref = mSettings.mPreferredPackages;
4891 final int N = pref.size();
4892 for (int i=0; i<N; i++) {
4893 res.add(generatePackageInfo(pref.get(i).pkg, flags));
4894 }
4895 return res;
4896 }
4897 }
4898
4899 public void addPreferredActivity(IntentFilter filter, int match,
4900 ComponentName[] set, ComponentName activity) {
4901 mContext.enforceCallingOrSelfPermission(
4902 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4903
4904 synchronized (mPackages) {
4905 Log.i(TAG, "Adding preferred activity " + activity + ":");
4906 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4907 mSettings.mPreferredActivities.addFilter(
4908 new PreferredActivity(filter, match, set, activity));
4909 mSettings.writeLP();
4910 }
4911 }
4912
Satish Sampath8dbe6122009-06-02 23:35:54 +01004913 public void replacePreferredActivity(IntentFilter filter, int match,
4914 ComponentName[] set, ComponentName activity) {
4915 mContext.enforceCallingOrSelfPermission(
4916 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4917 if (filter.countActions() != 1) {
4918 throw new IllegalArgumentException(
4919 "replacePreferredActivity expects filter to have only 1 action.");
4920 }
4921 if (filter.countCategories() != 1) {
4922 throw new IllegalArgumentException(
4923 "replacePreferredActivity expects filter to have only 1 category.");
4924 }
4925 if (filter.countDataAuthorities() != 0
4926 || filter.countDataPaths() != 0
4927 || filter.countDataSchemes() != 0
4928 || filter.countDataTypes() != 0) {
4929 throw new IllegalArgumentException(
4930 "replacePreferredActivity expects filter to have no data authorities, " +
4931 "paths, schemes or types.");
4932 }
4933 synchronized (mPackages) {
4934 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4935 String action = filter.getAction(0);
4936 String category = filter.getCategory(0);
4937 while (it.hasNext()) {
4938 PreferredActivity pa = it.next();
4939 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
4940 it.remove();
4941 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
4942 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4943 }
4944 }
4945 addPreferredActivity(filter, match, set, activity);
4946 }
4947 }
4948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004949 public void clearPackagePreferredActivities(String packageName) {
4950 mContext.enforceCallingOrSelfPermission(
4951 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4952
4953 synchronized (mPackages) {
4954 if (clearPackagePreferredActivitiesLP(packageName)) {
4955 mSettings.writeLP();
4956 }
4957 }
4958 }
4959
4960 boolean clearPackagePreferredActivitiesLP(String packageName) {
4961 boolean changed = false;
4962 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4963 while (it.hasNext()) {
4964 PreferredActivity pa = it.next();
4965 if (pa.mActivity.getPackageName().equals(packageName)) {
4966 it.remove();
4967 changed = true;
4968 }
4969 }
4970 return changed;
4971 }
4972
4973 public int getPreferredActivities(List<IntentFilter> outFilters,
4974 List<ComponentName> outActivities, String packageName) {
4975
4976 int num = 0;
4977 synchronized (mPackages) {
4978 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4979 while (it.hasNext()) {
4980 PreferredActivity pa = it.next();
4981 if (packageName == null
4982 || pa.mActivity.getPackageName().equals(packageName)) {
4983 if (outFilters != null) {
4984 outFilters.add(new IntentFilter(pa));
4985 }
4986 if (outActivities != null) {
4987 outActivities.add(pa.mActivity);
4988 }
4989 }
4990 }
4991 }
4992
4993 return num;
4994 }
4995
4996 public void setApplicationEnabledSetting(String appPackageName,
4997 int newState, int flags) {
4998 setEnabledSetting(appPackageName, null, newState, flags);
4999 }
5000
5001 public void setComponentEnabledSetting(ComponentName componentName,
5002 int newState, int flags) {
5003 setEnabledSetting(componentName.getPackageName(),
5004 componentName.getClassName(), newState, flags);
5005 }
5006
5007 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005008 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005009 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5010 || newState == COMPONENT_ENABLED_STATE_ENABLED
5011 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5012 throw new IllegalArgumentException("Invalid new component state: "
5013 + newState);
5014 }
5015 PackageSetting pkgSetting;
5016 final int uid = Binder.getCallingUid();
5017 final int permission = mContext.checkCallingPermission(
5018 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5019 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005020 boolean sendNow = false;
5021 boolean isApp = (className == null);
5022 String key = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 int packageUid = -1;
5024 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005025 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005026 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005027 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005028 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005029 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005030 }
5031 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005032 "Unknown component: " + packageName
5033 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005034 }
5035 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5036 throw new SecurityException(
5037 "Permission Denial: attempt to change component state from pid="
5038 + Binder.getCallingPid()
5039 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5040 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005041 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005042 // We're dealing with an application/package level state change
5043 pkgSetting.enabled = newState;
5044 } else {
5045 // We're dealing with a component level state change
5046 switch (newState) {
5047 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005048 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005049 break;
5050 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005051 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005052 break;
5053 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005054 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005055 break;
5056 default:
5057 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005058 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005059 }
5060 }
5061 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005062 packageUid = pkgSetting.userId;
5063 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
5064 sendNow = true;
5065 // Purge entry from pending broadcast list if another one exists already
5066 // since we are sending one right away.
5067 if (mPendingBroadcasts.get(key) != null) {
5068 mPendingBroadcasts.remove(key);
5069 // Can ignore empty list since its handled in the handler anyway
5070 }
5071 } else {
5072 if (mPendingBroadcasts.get(key) == null) {
5073 mPendingBroadcasts.put(key, packageName);
5074 }
5075 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
5076 // Schedule a message
5077 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
5078 }
5079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 long callingId = Binder.clearCallingIdentity();
5083 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005084 if (sendNow) {
5085 sendPackageChangedBroadcast(packageName,
5086 (flags&PackageManager.DONT_KILL_APP) != 0, key, packageUid);
5087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 } finally {
5089 Binder.restoreCallingIdentity(callingId);
5090 }
5091 }
5092
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005093 private void sendPackageChangedBroadcast(String packageName,
5094 boolean killFlag, String componentName, int packageUid) {
5095 Bundle extras = new Bundle(2);
5096 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentName);
5097 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
5098 extras.putInt(Intent.EXTRA_UID, packageUid);
5099 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
5100 }
5101
Jacek Surazski65e13172009-04-28 15:26:38 +02005102 public String getInstallerPackageName(String packageName) {
5103 synchronized (mPackages) {
5104 PackageSetting pkg = mSettings.mPackages.get(packageName);
5105 if (pkg == null) {
5106 throw new IllegalArgumentException("Unknown package: " + packageName);
5107 }
5108 return pkg.installerPackageName;
5109 }
5110 }
5111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 public int getApplicationEnabledSetting(String appPackageName) {
5113 synchronized (mPackages) {
5114 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
5115 if (pkg == null) {
5116 throw new IllegalArgumentException("Unknown package: " + appPackageName);
5117 }
5118 return pkg.enabled;
5119 }
5120 }
5121
5122 public int getComponentEnabledSetting(ComponentName componentName) {
5123 synchronized (mPackages) {
5124 final String packageNameStr = componentName.getPackageName();
5125 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
5126 if (pkg == null) {
5127 throw new IllegalArgumentException("Unknown component: " + componentName);
5128 }
5129 final String classNameStr = componentName.getClassName();
5130 return pkg.currentEnabledStateLP(classNameStr);
5131 }
5132 }
5133
5134 public void enterSafeMode() {
5135 if (!mSystemReady) {
5136 mSafeMode = true;
5137 }
5138 }
5139
5140 public void systemReady() {
5141 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005142
5143 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005144 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005145 mContext.getContentResolver(),
5146 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005147 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005148 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07005149 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07005150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005151 }
5152
5153 public boolean isSafeMode() {
5154 return mSafeMode;
5155 }
5156
5157 public boolean hasSystemUidErrors() {
5158 return mHasSystemUidErrors;
5159 }
5160
5161 static String arrayToString(int[] array) {
5162 StringBuffer buf = new StringBuffer(128);
5163 buf.append('[');
5164 if (array != null) {
5165 for (int i=0; i<array.length; i++) {
5166 if (i > 0) buf.append(", ");
5167 buf.append(array[i]);
5168 }
5169 }
5170 buf.append(']');
5171 return buf.toString();
5172 }
5173
5174 @Override
5175 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5176 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5177 != PackageManager.PERMISSION_GRANTED) {
5178 pw.println("Permission Denial: can't dump ActivityManager from from pid="
5179 + Binder.getCallingPid()
5180 + ", uid=" + Binder.getCallingUid()
5181 + " without permission "
5182 + android.Manifest.permission.DUMP);
5183 return;
5184 }
5185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 synchronized (mPackages) {
5187 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005188 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005189 pw.println(" ");
5190 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005191 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005192 pw.println(" ");
5193 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005194 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005195 pw.println(" ");
5196 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005197 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 pw.println(" ");
5199 pw.println("Preferred Packages:");
5200 {
5201 for (PackageSetting ps : mSettings.mPreferredPackages) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005202 pw.print(" "); pw.println(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 }
5204 }
5205 pw.println(" ");
5206 pw.println("Permissions:");
5207 {
5208 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005209 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
5210 pw.print(Integer.toHexString(System.identityHashCode(p)));
5211 pw.println("):");
5212 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
5213 pw.print(" uid="); pw.print(p.uid);
5214 pw.print(" gids="); pw.print(arrayToString(p.gids));
5215 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005216 }
5217 }
5218 pw.println(" ");
5219 pw.println("Packages:");
5220 {
5221 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005222 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
5223 pw.print(Integer.toHexString(System.identityHashCode(ps)));
5224 pw.println("):");
5225 pw.print(" userId="); pw.print(ps.userId);
5226 pw.print(" gids="); pw.println(arrayToString(ps.gids));
5227 pw.print(" sharedUser="); pw.println(ps.sharedUser);
5228 pw.print(" pkg="); pw.println(ps.pkg);
5229 pw.print(" codePath="); pw.println(ps.codePathString);
5230 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005231 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005232 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005233 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005234 pw.print(" supportsScreens=[");
5235 boolean first = true;
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005236 if ((ps.pkg.applicationInfo.flags &
5237 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005238 if (!first) pw.print(", ");
5239 first = false;
5240 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005241 }
5242 if ((ps.pkg.applicationInfo.flags &
5243 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005244 if (!first) pw.print(", ");
5245 first = false;
5246 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005247 }
5248 if ((ps.pkg.applicationInfo.flags &
5249 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005250 if (!first) pw.print(", ");
5251 first = false;
5252 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07005253 }
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005254 if ((ps.pkg.applicationInfo.flags &
5255 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005256 if (!first) pw.print(", ");
5257 first = false;
5258 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07005259 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005260 if ((ps.pkg.applicationInfo.flags &
5261 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
5262 if (!first) pw.print(", ");
5263 first = false;
5264 pw.print("anyDensity");
5265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005266 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07005267 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005268 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
5269 pw.print(" signatures="); pw.println(ps.signatures);
5270 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
5271 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
5272 pw.print(" installStatus="); pw.print(ps.installStatus);
5273 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005274 if (ps.disabledComponents.size() > 0) {
5275 pw.println(" disabledComponents:");
5276 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005277 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005278 }
5279 }
5280 if (ps.enabledComponents.size() > 0) {
5281 pw.println(" enabledComponents:");
5282 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005283 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005284 }
5285 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005286 if (ps.grantedPermissions.size() > 0) {
5287 pw.println(" grantedPermissions:");
5288 for (String s : ps.grantedPermissions) {
5289 pw.print(" "); pw.println(s);
5290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005292 if (ps.loadedPermissions.size() > 0) {
5293 pw.println(" loadedPermissions:");
5294 for (String s : ps.loadedPermissions) {
5295 pw.print(" "); pw.println(s);
5296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 }
5298 }
5299 }
5300 pw.println(" ");
5301 pw.println("Shared Users:");
5302 {
5303 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005304 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
5305 pw.print(Integer.toHexString(System.identityHashCode(su)));
5306 pw.println("):");
5307 pw.print(" userId="); pw.print(su.userId);
5308 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005309 pw.println(" grantedPermissions:");
5310 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005311 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 }
5313 pw.println(" loadedPermissions:");
5314 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005315 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005316 }
5317 }
5318 }
5319 pw.println(" ");
5320 pw.println("Settings parse messages:");
5321 pw.println(mSettings.mReadMessages.toString());
5322 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05005323
5324 synchronized (mProviders) {
5325 pw.println(" ");
5326 pw.println("Registered ContentProviders:");
5327 for (PackageParser.Provider p : mProviders.values()) {
5328 pw.println(" ["); pw.println(p.info.authority); pw.println("]: ");
5329 pw.println(p.toString());
5330 }
5331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 }
5333
5334 static final class BasePermission {
5335 final static int TYPE_NORMAL = 0;
5336 final static int TYPE_BUILTIN = 1;
5337 final static int TYPE_DYNAMIC = 2;
5338
5339 final String name;
5340 final String sourcePackage;
5341 final int type;
5342 PackageParser.Permission perm;
5343 PermissionInfo pendingInfo;
5344 int uid;
5345 int[] gids;
5346
5347 BasePermission(String _name, String _sourcePackage, int _type) {
5348 name = _name;
5349 sourcePackage = _sourcePackage;
5350 type = _type;
5351 }
5352 }
5353
5354 static class PackageSignatures {
5355 private Signature[] mSignatures;
5356
5357 PackageSignatures(Signature[] sigs) {
5358 assignSignatures(sigs);
5359 }
5360
5361 PackageSignatures() {
5362 }
5363
5364 void writeXml(XmlSerializer serializer, String tagName,
5365 ArrayList<Signature> pastSignatures) throws IOException {
5366 if (mSignatures == null) {
5367 return;
5368 }
5369 serializer.startTag(null, tagName);
5370 serializer.attribute(null, "count",
5371 Integer.toString(mSignatures.length));
5372 for (int i=0; i<mSignatures.length; i++) {
5373 serializer.startTag(null, "cert");
5374 final Signature sig = mSignatures[i];
5375 final int sigHash = sig.hashCode();
5376 final int numPast = pastSignatures.size();
5377 int j;
5378 for (j=0; j<numPast; j++) {
5379 Signature pastSig = pastSignatures.get(j);
5380 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5381 serializer.attribute(null, "index", Integer.toString(j));
5382 break;
5383 }
5384 }
5385 if (j >= numPast) {
5386 pastSignatures.add(sig);
5387 serializer.attribute(null, "index", Integer.toString(numPast));
5388 serializer.attribute(null, "key", sig.toCharsString());
5389 }
5390 serializer.endTag(null, "cert");
5391 }
5392 serializer.endTag(null, tagName);
5393 }
5394
5395 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5396 throws IOException, XmlPullParserException {
5397 String countStr = parser.getAttributeValue(null, "count");
5398 if (countStr == null) {
5399 reportSettingsProblem(Log.WARN,
5400 "Error in package manager settings: <signatures> has"
5401 + " no count at " + parser.getPositionDescription());
5402 XmlUtils.skipCurrentTag(parser);
5403 }
5404 final int count = Integer.parseInt(countStr);
5405 mSignatures = new Signature[count];
5406 int pos = 0;
5407
5408 int outerDepth = parser.getDepth();
5409 int type;
5410 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5411 && (type != XmlPullParser.END_TAG
5412 || parser.getDepth() > outerDepth)) {
5413 if (type == XmlPullParser.END_TAG
5414 || type == XmlPullParser.TEXT) {
5415 continue;
5416 }
5417
5418 String tagName = parser.getName();
5419 if (tagName.equals("cert")) {
5420 if (pos < count) {
5421 String index = parser.getAttributeValue(null, "index");
5422 if (index != null) {
5423 try {
5424 int idx = Integer.parseInt(index);
5425 String key = parser.getAttributeValue(null, "key");
5426 if (key == null) {
5427 if (idx >= 0 && idx < pastSignatures.size()) {
5428 Signature sig = pastSignatures.get(idx);
5429 if (sig != null) {
5430 mSignatures[pos] = pastSignatures.get(idx);
5431 pos++;
5432 } else {
5433 reportSettingsProblem(Log.WARN,
5434 "Error in package manager settings: <cert> "
5435 + "index " + index + " is not defined at "
5436 + parser.getPositionDescription());
5437 }
5438 } else {
5439 reportSettingsProblem(Log.WARN,
5440 "Error in package manager settings: <cert> "
5441 + "index " + index + " is out of bounds at "
5442 + parser.getPositionDescription());
5443 }
5444 } else {
5445 while (pastSignatures.size() <= idx) {
5446 pastSignatures.add(null);
5447 }
5448 Signature sig = new Signature(key);
5449 pastSignatures.set(idx, sig);
5450 mSignatures[pos] = sig;
5451 pos++;
5452 }
5453 } catch (NumberFormatException e) {
5454 reportSettingsProblem(Log.WARN,
5455 "Error in package manager settings: <cert> "
5456 + "index " + index + " is not a number at "
5457 + parser.getPositionDescription());
5458 }
5459 } else {
5460 reportSettingsProblem(Log.WARN,
5461 "Error in package manager settings: <cert> has"
5462 + " no index at " + parser.getPositionDescription());
5463 }
5464 } else {
5465 reportSettingsProblem(Log.WARN,
5466 "Error in package manager settings: too "
5467 + "many <cert> tags, expected " + count
5468 + " at " + parser.getPositionDescription());
5469 }
5470 } else {
5471 reportSettingsProblem(Log.WARN,
5472 "Unknown element under <cert>: "
5473 + parser.getName());
5474 }
5475 XmlUtils.skipCurrentTag(parser);
5476 }
5477
5478 if (pos < count) {
5479 // Should never happen -- there is an error in the written
5480 // settings -- but if it does we don't want to generate
5481 // a bad array.
5482 Signature[] newSigs = new Signature[pos];
5483 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
5484 mSignatures = newSigs;
5485 }
5486 }
5487
5488 /**
5489 * If any of the given 'sigs' is contained in the existing signatures,
5490 * then completely replace the current signatures with the ones in
5491 * 'sigs'. This is used for updating an existing package to a newly
5492 * installed version.
5493 */
5494 boolean updateSignatures(Signature[] sigs, boolean update) {
5495 if (mSignatures == null) {
5496 if (update) {
5497 assignSignatures(sigs);
5498 }
5499 return true;
5500 }
5501 if (sigs == null) {
5502 return false;
5503 }
5504
5505 for (int i=0; i<sigs.length; i++) {
5506 Signature sig = sigs[i];
5507 for (int j=0; j<mSignatures.length; j++) {
5508 if (mSignatures[j].equals(sig)) {
5509 if (update) {
5510 assignSignatures(sigs);
5511 }
5512 return true;
5513 }
5514 }
5515 }
5516 return false;
5517 }
5518
5519 /**
5520 * If any of the given 'sigs' is contained in the existing signatures,
5521 * then add in any new signatures found in 'sigs'. This is used for
5522 * including a new package into an existing shared user id.
5523 */
5524 boolean mergeSignatures(Signature[] sigs, boolean update) {
5525 if (mSignatures == null) {
5526 if (update) {
5527 assignSignatures(sigs);
5528 }
5529 return true;
5530 }
5531 if (sigs == null) {
5532 return false;
5533 }
5534
5535 Signature[] added = null;
5536 int addedCount = 0;
5537 boolean haveMatch = false;
5538 for (int i=0; i<sigs.length; i++) {
5539 Signature sig = sigs[i];
5540 boolean found = false;
5541 for (int j=0; j<mSignatures.length; j++) {
5542 if (mSignatures[j].equals(sig)) {
5543 found = true;
5544 haveMatch = true;
5545 break;
5546 }
5547 }
5548
5549 if (!found) {
5550 if (added == null) {
5551 added = new Signature[sigs.length];
5552 }
5553 added[i] = sig;
5554 addedCount++;
5555 }
5556 }
5557
5558 if (!haveMatch) {
5559 // Nothing matched -- reject the new signatures.
5560 return false;
5561 }
5562 if (added == null) {
5563 // Completely matched -- nothing else to do.
5564 return true;
5565 }
5566
5567 // Add additional signatures in.
5568 if (update) {
5569 Signature[] total = new Signature[addedCount+mSignatures.length];
5570 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5571 int j = mSignatures.length;
5572 for (int i=0; i<added.length; i++) {
5573 if (added[i] != null) {
5574 total[j] = added[i];
5575 j++;
5576 }
5577 }
5578 mSignatures = total;
5579 }
5580 return true;
5581 }
5582
5583 private void assignSignatures(Signature[] sigs) {
5584 if (sigs == null) {
5585 mSignatures = null;
5586 return;
5587 }
5588 mSignatures = new Signature[sigs.length];
5589 for (int i=0; i<sigs.length; i++) {
5590 mSignatures[i] = sigs[i];
5591 }
5592 }
5593
5594 @Override
5595 public String toString() {
5596 StringBuffer buf = new StringBuffer(128);
5597 buf.append("PackageSignatures{");
5598 buf.append(Integer.toHexString(System.identityHashCode(this)));
5599 buf.append(" [");
5600 if (mSignatures != null) {
5601 for (int i=0; i<mSignatures.length; i++) {
5602 if (i > 0) buf.append(", ");
5603 buf.append(Integer.toHexString(
5604 System.identityHashCode(mSignatures[i])));
5605 }
5606 }
5607 buf.append("]}");
5608 return buf.toString();
5609 }
5610 }
5611
5612 static class PreferredActivity extends IntentFilter {
5613 final int mMatch;
5614 final String[] mSetPackages;
5615 final String[] mSetClasses;
5616 final String[] mSetComponents;
5617 final ComponentName mActivity;
5618 final String mShortActivity;
5619 String mParseError;
5620
5621 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5622 ComponentName activity) {
5623 super(filter);
5624 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5625 mActivity = activity;
5626 mShortActivity = activity.flattenToShortString();
5627 mParseError = null;
5628 if (set != null) {
5629 final int N = set.length;
5630 String[] myPackages = new String[N];
5631 String[] myClasses = new String[N];
5632 String[] myComponents = new String[N];
5633 for (int i=0; i<N; i++) {
5634 ComponentName cn = set[i];
5635 if (cn == null) {
5636 mSetPackages = null;
5637 mSetClasses = null;
5638 mSetComponents = null;
5639 return;
5640 }
5641 myPackages[i] = cn.getPackageName().intern();
5642 myClasses[i] = cn.getClassName().intern();
5643 myComponents[i] = cn.flattenToShortString().intern();
5644 }
5645 mSetPackages = myPackages;
5646 mSetClasses = myClasses;
5647 mSetComponents = myComponents;
5648 } else {
5649 mSetPackages = null;
5650 mSetClasses = null;
5651 mSetComponents = null;
5652 }
5653 }
5654
5655 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5656 IOException {
5657 mShortActivity = parser.getAttributeValue(null, "name");
5658 mActivity = ComponentName.unflattenFromString(mShortActivity);
5659 if (mActivity == null) {
5660 mParseError = "Bad activity name " + mShortActivity;
5661 }
5662 String matchStr = parser.getAttributeValue(null, "match");
5663 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5664 String setCountStr = parser.getAttributeValue(null, "set");
5665 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5666
5667 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5668 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5669 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5670
5671 int setPos = 0;
5672
5673 int outerDepth = parser.getDepth();
5674 int type;
5675 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5676 && (type != XmlPullParser.END_TAG
5677 || parser.getDepth() > outerDepth)) {
5678 if (type == XmlPullParser.END_TAG
5679 || type == XmlPullParser.TEXT) {
5680 continue;
5681 }
5682
5683 String tagName = parser.getName();
5684 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5685 // + parser.getDepth() + " tag=" + tagName);
5686 if (tagName.equals("set")) {
5687 String name = parser.getAttributeValue(null, "name");
5688 if (name == null) {
5689 if (mParseError == null) {
5690 mParseError = "No name in set tag in preferred activity "
5691 + mShortActivity;
5692 }
5693 } else if (setPos >= setCount) {
5694 if (mParseError == null) {
5695 mParseError = "Too many set tags in preferred activity "
5696 + mShortActivity;
5697 }
5698 } else {
5699 ComponentName cn = ComponentName.unflattenFromString(name);
5700 if (cn == null) {
5701 if (mParseError == null) {
5702 mParseError = "Bad set name " + name + " in preferred activity "
5703 + mShortActivity;
5704 }
5705 } else {
5706 myPackages[setPos] = cn.getPackageName();
5707 myClasses[setPos] = cn.getClassName();
5708 myComponents[setPos] = name;
5709 setPos++;
5710 }
5711 }
5712 XmlUtils.skipCurrentTag(parser);
5713 } else if (tagName.equals("filter")) {
5714 //Log.i(TAG, "Starting to parse filter...");
5715 readFromXml(parser);
5716 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5717 // + parser.getDepth() + " tag=" + parser.getName());
5718 } else {
5719 reportSettingsProblem(Log.WARN,
5720 "Unknown element under <preferred-activities>: "
5721 + parser.getName());
5722 XmlUtils.skipCurrentTag(parser);
5723 }
5724 }
5725
5726 if (setPos != setCount) {
5727 if (mParseError == null) {
5728 mParseError = "Not enough set tags (expected " + setCount
5729 + " but found " + setPos + ") in " + mShortActivity;
5730 }
5731 }
5732
5733 mSetPackages = myPackages;
5734 mSetClasses = myClasses;
5735 mSetComponents = myComponents;
5736 }
5737
5738 public void writeToXml(XmlSerializer serializer) throws IOException {
5739 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5740 serializer.attribute(null, "name", mShortActivity);
5741 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5742 serializer.attribute(null, "set", Integer.toString(NS));
5743 for (int s=0; s<NS; s++) {
5744 serializer.startTag(null, "set");
5745 serializer.attribute(null, "name", mSetComponents[s]);
5746 serializer.endTag(null, "set");
5747 }
5748 serializer.startTag(null, "filter");
5749 super.writeToXml(serializer);
5750 serializer.endTag(null, "filter");
5751 }
5752
5753 boolean sameSet(List<ResolveInfo> query, int priority) {
5754 if (mSetPackages == null) return false;
5755 final int NQ = query.size();
5756 final int NS = mSetPackages.length;
5757 int numMatch = 0;
5758 for (int i=0; i<NQ; i++) {
5759 ResolveInfo ri = query.get(i);
5760 if (ri.priority != priority) continue;
5761 ActivityInfo ai = ri.activityInfo;
5762 boolean good = false;
5763 for (int j=0; j<NS; j++) {
5764 if (mSetPackages[j].equals(ai.packageName)
5765 && mSetClasses[j].equals(ai.name)) {
5766 numMatch++;
5767 good = true;
5768 break;
5769 }
5770 }
5771 if (!good) return false;
5772 }
5773 return numMatch == NS;
5774 }
5775 }
5776
5777 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07005778 int pkgFlags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779
5780 HashSet<String> grantedPermissions = new HashSet<String>();
5781 int[] gids;
5782
5783 HashSet<String> loadedPermissions = new HashSet<String>();
5784
5785 GrantedPermissions(int pkgFlags) {
5786 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5787 }
5788 }
5789
5790 /**
5791 * Settings base class for pending and resolved classes.
5792 */
5793 static class PackageSettingBase extends GrantedPermissions {
5794 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005795 File codePath;
5796 String codePathString;
5797 File resourcePath;
5798 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 private long timeStamp;
5800 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005801 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802
5803 PackageSignatures signatures = new PackageSignatures();
5804
5805 boolean permissionsFixed;
5806
5807 /* Explicitly disabled components */
5808 HashSet<String> disabledComponents = new HashSet<String>(0);
5809 /* Explicitly enabled components */
5810 HashSet<String> enabledComponents = new HashSet<String>(0);
5811 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5812 int installStatus = PKG_INSTALL_COMPLETE;
Jacek Surazski65e13172009-04-28 15:26:38 +02005813
5814 /* package name of the app that installed this package */
5815 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816
5817 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005818 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 super(pkgFlags);
5820 this.name = name;
5821 this.codePath = codePath;
5822 this.codePathString = codePath.toString();
5823 this.resourcePath = resourcePath;
5824 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005825 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 }
5827
Jacek Surazski65e13172009-04-28 15:26:38 +02005828 public void setInstallerPackageName(String packageName) {
5829 installerPackageName = packageName;
5830 }
5831
5832 String getInstallerPackageName() {
5833 return installerPackageName;
5834 }
5835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 public void setInstallStatus(int newStatus) {
5837 installStatus = newStatus;
5838 }
5839
5840 public int getInstallStatus() {
5841 return installStatus;
5842 }
5843
5844 public void setTimeStamp(long newStamp) {
5845 if (newStamp != timeStamp) {
5846 timeStamp = newStamp;
5847 timeStampString = Long.toString(newStamp);
5848 }
5849 }
5850
5851 public void setTimeStamp(long newStamp, String newStampStr) {
5852 timeStamp = newStamp;
5853 timeStampString = newStampStr;
5854 }
5855
5856 public long getTimeStamp() {
5857 return timeStamp;
5858 }
5859
5860 public String getTimeStampStr() {
5861 return timeStampString;
5862 }
5863
5864 public void copyFrom(PackageSettingBase base) {
5865 grantedPermissions = base.grantedPermissions;
5866 gids = base.gids;
5867 loadedPermissions = base.loadedPermissions;
5868
5869 timeStamp = base.timeStamp;
5870 timeStampString = base.timeStampString;
5871 signatures = base.signatures;
5872 permissionsFixed = base.permissionsFixed;
5873 disabledComponents = base.disabledComponents;
5874 enabledComponents = base.enabledComponents;
5875 enabled = base.enabled;
5876 installStatus = base.installStatus;
5877 }
5878
5879 void enableComponentLP(String componentClassName) {
5880 disabledComponents.remove(componentClassName);
5881 enabledComponents.add(componentClassName);
5882 }
5883
5884 void disableComponentLP(String componentClassName) {
5885 enabledComponents.remove(componentClassName);
5886 disabledComponents.add(componentClassName);
5887 }
5888
5889 void restoreComponentLP(String componentClassName) {
5890 enabledComponents.remove(componentClassName);
5891 disabledComponents.remove(componentClassName);
5892 }
5893
5894 int currentEnabledStateLP(String componentName) {
5895 if (enabledComponents.contains(componentName)) {
5896 return COMPONENT_ENABLED_STATE_ENABLED;
5897 } else if (disabledComponents.contains(componentName)) {
5898 return COMPONENT_ENABLED_STATE_DISABLED;
5899 } else {
5900 return COMPONENT_ENABLED_STATE_DEFAULT;
5901 }
5902 }
5903 }
5904
5905 /**
5906 * Settings data for a particular package we know about.
5907 */
5908 static final class PackageSetting extends PackageSettingBase {
5909 int userId;
5910 PackageParser.Package pkg;
5911 SharedUserSetting sharedUser;
5912
5913 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005914 int pVersionCode, int pkgFlags) {
5915 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 }
5917
5918 @Override
5919 public String toString() {
5920 return "PackageSetting{"
5921 + Integer.toHexString(System.identityHashCode(this))
5922 + " " + name + "/" + userId + "}";
5923 }
5924 }
5925
5926 /**
5927 * Settings data for a particular shared user ID we know about.
5928 */
5929 static final class SharedUserSetting extends GrantedPermissions {
5930 final String name;
5931 int userId;
5932 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
5933 final PackageSignatures signatures = new PackageSignatures();
5934
5935 SharedUserSetting(String _name, int _pkgFlags) {
5936 super(_pkgFlags);
5937 name = _name;
5938 }
5939
5940 @Override
5941 public String toString() {
5942 return "SharedUserSetting{"
5943 + Integer.toHexString(System.identityHashCode(this))
5944 + " " + name + "/" + userId + "}";
5945 }
5946 }
5947
5948 /**
5949 * Holds information about dynamic settings.
5950 */
5951 private static final class Settings {
5952 private final File mSettingsFilename;
5953 private final File mBackupSettingsFilename;
5954 private final HashMap<String, PackageSetting> mPackages =
5955 new HashMap<String, PackageSetting>();
5956 // The user's preferred packages/applications, in order of preference.
5957 // First is the most preferred.
5958 private final ArrayList<PackageSetting> mPreferredPackages =
5959 new ArrayList<PackageSetting>();
5960 // List of replaced system applications
5961 final HashMap<String, PackageSetting> mDisabledSysPackages =
5962 new HashMap<String, PackageSetting>();
5963
5964 // The user's preferred activities associated with particular intent
5965 // filters.
5966 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
5967 new IntentResolver<PreferredActivity, PreferredActivity>() {
5968 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005969 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005971 out.print(prefix); out.print(
5972 Integer.toHexString(System.identityHashCode(filter)));
5973 out.print(' ');
5974 out.print(filter.mActivity.flattenToShortString());
5975 out.print(" match=0x");
5976 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005978 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005979 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005980 out.print(prefix); out.print(" ");
5981 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 }
5983 }
5984 }
5985 };
5986 private final HashMap<String, SharedUserSetting> mSharedUsers =
5987 new HashMap<String, SharedUserSetting>();
5988 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
5989 private final SparseArray<Object> mOtherUserIds =
5990 new SparseArray<Object>();
5991
5992 // For reading/writing settings file.
5993 private final ArrayList<Signature> mPastSignatures =
5994 new ArrayList<Signature>();
5995
5996 // Mapping from permission names to info about them.
5997 final HashMap<String, BasePermission> mPermissions =
5998 new HashMap<String, BasePermission>();
5999
6000 // Mapping from permission tree names to info about them.
6001 final HashMap<String, BasePermission> mPermissionTrees =
6002 new HashMap<String, BasePermission>();
6003
6004 private final ArrayList<String> mPendingPreferredPackages
6005 = new ArrayList<String>();
6006
6007 private final StringBuilder mReadMessages = new StringBuilder();
6008
6009 private static final class PendingPackage extends PackageSettingBase {
6010 final int sharedId;
6011
6012 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006013 int sharedId, int pVersionCode, int pkgFlags) {
6014 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 this.sharedId = sharedId;
6016 }
6017 }
6018 private final ArrayList<PendingPackage> mPendingPackages
6019 = new ArrayList<PendingPackage>();
6020
6021 Settings() {
6022 File dataDir = Environment.getDataDirectory();
6023 File systemDir = new File(dataDir, "system");
6024 systemDir.mkdirs();
6025 FileUtils.setPermissions(systemDir.toString(),
6026 FileUtils.S_IRWXU|FileUtils.S_IRWXG
6027 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
6028 -1, -1);
6029 mSettingsFilename = new File(systemDir, "packages.xml");
6030 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
6031 }
6032
6033 PackageSetting getPackageLP(PackageParser.Package pkg,
6034 SharedUserSetting sharedUser, File codePath, File resourcePath,
6035 int pkgFlags, boolean create, boolean add) {
6036 final String name = pkg.packageName;
6037 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006038 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 return p;
6040 }
6041
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006042 PackageSetting peekPackageLP(String name) {
6043 return mPackages.get(name);
6044 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 PackageSetting p = mPackages.get(name);
6046 if (p != null && p.codePath.getPath().equals(codePath)) {
6047 return p;
6048 }
6049 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006050 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 }
6052
6053 void setInstallStatus(String pkgName, int status) {
6054 PackageSetting p = mPackages.get(pkgName);
6055 if(p != null) {
6056 if(p.getInstallStatus() != status) {
6057 p.setInstallStatus(status);
6058 }
6059 }
6060 }
6061
Jacek Surazski65e13172009-04-28 15:26:38 +02006062 void setInstallerPackageName(String pkgName,
6063 String installerPkgName) {
6064 PackageSetting p = mPackages.get(pkgName);
6065 if(p != null) {
6066 p.setInstallerPackageName(installerPkgName);
6067 }
6068 }
6069
6070 String getInstallerPackageName(String pkgName) {
6071 PackageSetting p = mPackages.get(pkgName);
6072 return (p == null) ? null : p.getInstallerPackageName();
6073 }
6074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006075 int getInstallStatus(String pkgName) {
6076 PackageSetting p = mPackages.get(pkgName);
6077 if(p != null) {
6078 return p.getInstallStatus();
6079 }
6080 return -1;
6081 }
6082
6083 SharedUserSetting getSharedUserLP(String name,
6084 int pkgFlags, boolean create) {
6085 SharedUserSetting s = mSharedUsers.get(name);
6086 if (s == null) {
6087 if (!create) {
6088 return null;
6089 }
6090 s = new SharedUserSetting(name, pkgFlags);
6091 if (MULTIPLE_APPLICATION_UIDS) {
6092 s.userId = newUserIdLP(s);
6093 } else {
6094 s.userId = FIRST_APPLICATION_UID;
6095 }
6096 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
6097 // < 0 means we couldn't assign a userid; fall out and return
6098 // s, which is currently null
6099 if (s.userId >= 0) {
6100 mSharedUsers.put(name, s);
6101 }
6102 }
6103
6104 return s;
6105 }
6106
6107 int disableSystemPackageLP(String name) {
6108 PackageSetting p = mPackages.get(name);
6109 if(p == null) {
6110 Log.w(TAG, "Package:"+name+" is not an installed package");
6111 return -1;
6112 }
6113 PackageSetting dp = mDisabledSysPackages.get(name);
6114 // always make sure the system package code and resource paths dont change
6115 if(dp == null) {
6116 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6117 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6118 }
6119 mDisabledSysPackages.put(name, p);
6120 }
6121 return removePackageLP(name);
6122 }
6123
6124 PackageSetting enableSystemPackageLP(String name) {
6125 PackageSetting p = mDisabledSysPackages.get(name);
6126 if(p == null) {
6127 Log.w(TAG, "Package:"+name+" is not disabled");
6128 return null;
6129 }
6130 // Reset flag in ApplicationInfo object
6131 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
6132 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6133 }
6134 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006135 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006136 mDisabledSysPackages.remove(name);
6137 return ret;
6138 }
6139
6140 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006141 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 PackageSetting p = mPackages.get(name);
6143 if (p != null) {
6144 if (p.userId == uid) {
6145 return p;
6146 }
6147 reportSettingsProblem(Log.ERROR,
6148 "Adding duplicate package, keeping first: " + name);
6149 return null;
6150 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006151 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 p.userId = uid;
6153 if (addUserIdLP(uid, p, name)) {
6154 mPackages.put(name, p);
6155 return p;
6156 }
6157 return null;
6158 }
6159
6160 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
6161 SharedUserSetting s = mSharedUsers.get(name);
6162 if (s != null) {
6163 if (s.userId == uid) {
6164 return s;
6165 }
6166 reportSettingsProblem(Log.ERROR,
6167 "Adding duplicate shared user, keeping first: " + name);
6168 return null;
6169 }
6170 s = new SharedUserSetting(name, pkgFlags);
6171 s.userId = uid;
6172 if (addUserIdLP(uid, s, name)) {
6173 mSharedUsers.put(name, s);
6174 return s;
6175 }
6176 return null;
6177 }
6178
6179 private PackageSetting getPackageLP(String name,
6180 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006181 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 PackageSetting p = mPackages.get(name);
6183 if (p != null) {
6184 if (!p.codePath.equals(codePath)) {
6185 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006186 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006187 // This is an updated system app with versions in both system
6188 // and data partition. Just let the most recent version
6189 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006190 Log.w(TAG, "Trying to update system app code path from " +
6191 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006192 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07006193 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07006194 reportSettingsProblem(Log.WARN,
6195 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006196 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006198 }
6199 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 reportSettingsProblem(Log.WARN,
6201 "Package " + name + " shared user changed from "
6202 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
6203 + " to "
6204 + (sharedUser != null ? sharedUser.name : "<nothing>")
6205 + "; replacing with new");
6206 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006207 } else {
6208 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6209 // If what we are scanning is a system package, then
6210 // make it so, regardless of whether it was previously
6211 // installed only in the data partition.
6212 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 }
6215 }
6216 if (p == null) {
6217 // Create a new PackageSettings entry. this can end up here because
6218 // of code path mismatch or user id mismatch of an updated system partition
6219 if (!create) {
6220 return null;
6221 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006222 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07006224 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 if (sharedUser != null) {
6226 p.userId = sharedUser.userId;
6227 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006228 // Clone the setting here for disabled system packages
6229 PackageSetting dis = mDisabledSysPackages.get(name);
6230 if (dis != null) {
6231 // For disabled packages a new setting is created
6232 // from the existing user id. This still has to be
6233 // added to list of user id's
6234 // Copy signatures from previous setting
6235 if (dis.signatures.mSignatures != null) {
6236 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
6237 }
6238 p.userId = dis.userId;
6239 // Clone permissions
6240 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
6241 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
6242 // Clone component info
6243 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
6244 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
6245 // Add new setting to list of user ids
6246 addUserIdLP(p.userId, p, name);
6247 } else {
6248 // Assign new user id
6249 p.userId = newUserIdLP(p);
6250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 } else {
6252 p.userId = FIRST_APPLICATION_UID;
6253 }
6254 if (p.userId < 0) {
6255 reportSettingsProblem(Log.WARN,
6256 "Package " + name + " could not be assigned a valid uid");
6257 return null;
6258 }
6259 if (add) {
6260 // Finish adding new package by adding it and updating shared
6261 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006262 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 }
6264 }
6265 return p;
6266 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006267
6268 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg,
6269 File codePath, File resourcePath) {
6270 p.pkg = pkg;
6271 // Update code path if needed
6272 if (!codePath.toString().equalsIgnoreCase(p.codePathString)) {
6273 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006274 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006275 p.codePath = codePath;
6276 p.codePathString = codePath.toString();
6277 }
6278 //Update resource path if needed
6279 if (!resourcePath.toString().equalsIgnoreCase(p.resourcePathString)) {
6280 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006281 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006282 p.resourcePath = resourcePath;
6283 p.resourcePathString = resourcePath.toString();
6284 }
6285 // Update version code if needed
6286 if (pkg.mVersionCode != p.versionCode) {
6287 p.versionCode = pkg.mVersionCode;
6288 }
6289 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
6290 }
6291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 // Utility method that adds a PackageSetting to mPackages and
6293 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006294 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 SharedUserSetting sharedUser) {
6296 mPackages.put(name, p);
6297 if (sharedUser != null) {
6298 if (p.sharedUser != null && p.sharedUser != sharedUser) {
6299 reportSettingsProblem(Log.ERROR,
6300 "Package " + p.name + " was user "
6301 + p.sharedUser + " but is now " + sharedUser
6302 + "; I am not changing its files so it will probably fail!");
6303 p.sharedUser.packages.remove(p);
6304 } else if (p.userId != sharedUser.userId) {
6305 reportSettingsProblem(Log.ERROR,
6306 "Package " + p.name + " was user id " + p.userId
6307 + " but is now user " + sharedUser
6308 + " with id " + sharedUser.userId
6309 + "; I am not changing its files so it will probably fail!");
6310 }
6311
6312 sharedUser.packages.add(p);
6313 p.sharedUser = sharedUser;
6314 p.userId = sharedUser.userId;
6315 }
6316 }
6317
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006318 /*
6319 * Update the shared user setting when a package using
6320 * specifying the shared user id is removed. The gids
6321 * associated with each permission of the deleted package
6322 * are removed from the shared user's gid list only if its
6323 * not in use by other permissions of packages in the
6324 * shared user setting.
6325 */
6326 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
6328 Log.i(TAG, "Trying to update info for null package. Just ignoring");
6329 return;
6330 }
6331 // No sharedUserId
6332 if (deletedPs.sharedUser == null) {
6333 return;
6334 }
6335 SharedUserSetting sus = deletedPs.sharedUser;
6336 // Update permissions
6337 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
6338 boolean used = false;
6339 if (!sus.grantedPermissions.contains (eachPerm)) {
6340 continue;
6341 }
6342 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapub97b8f82009-06-19 15:09:18 -07006343 if (pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 used = true;
6345 break;
6346 }
6347 }
6348 if (!used) {
6349 // can safely delete this permission from list
6350 sus.grantedPermissions.remove(eachPerm);
6351 sus.loadedPermissions.remove(eachPerm);
6352 }
6353 }
6354 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006355 int newGids[] = globalGids;
6356 for (String eachPerm : sus.grantedPermissions) {
6357 BasePermission bp = mPermissions.get(eachPerm);
6358 newGids = appendInts(newGids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 }
6360 sus.gids = newGids;
6361 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07006362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 private int removePackageLP(String name) {
6364 PackageSetting p = mPackages.get(name);
6365 if (p != null) {
6366 mPackages.remove(name);
6367 if (p.sharedUser != null) {
6368 p.sharedUser.packages.remove(p);
6369 if (p.sharedUser.packages.size() == 0) {
6370 mSharedUsers.remove(p.sharedUser.name);
6371 removeUserIdLP(p.sharedUser.userId);
6372 return p.sharedUser.userId;
6373 }
6374 } else {
6375 removeUserIdLP(p.userId);
6376 return p.userId;
6377 }
6378 }
6379 return -1;
6380 }
6381
6382 private boolean addUserIdLP(int uid, Object obj, Object name) {
6383 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
6384 return false;
6385 }
6386
6387 if (uid >= FIRST_APPLICATION_UID) {
6388 int N = mUserIds.size();
6389 final int index = uid - FIRST_APPLICATION_UID;
6390 while (index >= N) {
6391 mUserIds.add(null);
6392 N++;
6393 }
6394 if (mUserIds.get(index) != null) {
6395 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006396 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 + " name=" + name);
6398 return false;
6399 }
6400 mUserIds.set(index, obj);
6401 } else {
6402 if (mOtherUserIds.get(uid) != null) {
6403 reportSettingsProblem(Log.ERROR,
6404 "Adding duplicate shared id: " + uid
6405 + " name=" + name);
6406 return false;
6407 }
6408 mOtherUserIds.put(uid, obj);
6409 }
6410 return true;
6411 }
6412
6413 public Object getUserIdLP(int uid) {
6414 if (uid >= FIRST_APPLICATION_UID) {
6415 int N = mUserIds.size();
6416 final int index = uid - FIRST_APPLICATION_UID;
6417 return index < N ? mUserIds.get(index) : null;
6418 } else {
6419 return mOtherUserIds.get(uid);
6420 }
6421 }
6422
6423 private void removeUserIdLP(int uid) {
6424 if (uid >= FIRST_APPLICATION_UID) {
6425 int N = mUserIds.size();
6426 final int index = uid - FIRST_APPLICATION_UID;
6427 if (index < N) mUserIds.set(index, null);
6428 } else {
6429 mOtherUserIds.remove(uid);
6430 }
6431 }
6432
6433 void writeLP() {
6434 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6435
6436 // Keep the old settings around until we know the new ones have
6437 // been successfully written.
6438 if (mSettingsFilename.exists()) {
6439 if (mBackupSettingsFilename.exists()) {
6440 mBackupSettingsFilename.delete();
6441 }
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07006442 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
6443 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
6444 return;
6445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 }
6447
6448 mPastSignatures.clear();
6449
6450 try {
6451 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6452
6453 //XmlSerializer serializer = XmlUtils.serializerInstance();
6454 XmlSerializer serializer = new FastXmlSerializer();
6455 serializer.setOutput(str, "utf-8");
6456 serializer.startDocument(null, true);
6457 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6458
6459 serializer.startTag(null, "packages");
6460
6461 serializer.startTag(null, "permission-trees");
6462 for (BasePermission bp : mPermissionTrees.values()) {
6463 writePermission(serializer, bp);
6464 }
6465 serializer.endTag(null, "permission-trees");
6466
6467 serializer.startTag(null, "permissions");
6468 for (BasePermission bp : mPermissions.values()) {
6469 writePermission(serializer, bp);
6470 }
6471 serializer.endTag(null, "permissions");
6472
6473 for (PackageSetting pkg : mPackages.values()) {
6474 writePackage(serializer, pkg);
6475 }
6476
6477 for (PackageSetting pkg : mDisabledSysPackages.values()) {
6478 writeDisabledSysPackage(serializer, pkg);
6479 }
6480
6481 serializer.startTag(null, "preferred-packages");
6482 int N = mPreferredPackages.size();
6483 for (int i=0; i<N; i++) {
6484 PackageSetting pkg = mPreferredPackages.get(i);
6485 serializer.startTag(null, "item");
6486 serializer.attribute(null, "name", pkg.name);
6487 serializer.endTag(null, "item");
6488 }
6489 serializer.endTag(null, "preferred-packages");
6490
6491 serializer.startTag(null, "preferred-activities");
6492 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
6493 serializer.startTag(null, "item");
6494 pa.writeToXml(serializer);
6495 serializer.endTag(null, "item");
6496 }
6497 serializer.endTag(null, "preferred-activities");
6498
6499 for (SharedUserSetting usr : mSharedUsers.values()) {
6500 serializer.startTag(null, "shared-user");
6501 serializer.attribute(null, "name", usr.name);
6502 serializer.attribute(null, "userId",
6503 Integer.toString(usr.userId));
6504 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
6505 serializer.startTag(null, "perms");
6506 for (String name : usr.grantedPermissions) {
6507 serializer.startTag(null, "item");
6508 serializer.attribute(null, "name", name);
6509 serializer.endTag(null, "item");
6510 }
6511 serializer.endTag(null, "perms");
6512 serializer.endTag(null, "shared-user");
6513 }
6514
6515 serializer.endTag(null, "packages");
6516
6517 serializer.endDocument();
6518
6519 str.flush();
6520 str.close();
6521
6522 // New settings successfully written, old ones are no longer
6523 // needed.
6524 mBackupSettingsFilename.delete();
6525 FileUtils.setPermissions(mSettingsFilename.toString(),
6526 FileUtils.S_IRUSR|FileUtils.S_IWUSR
6527 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
6528 |FileUtils.S_IROTH,
6529 -1, -1);
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006530 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531
6532 } catch(XmlPullParserException e) {
6533 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 -08006534 } catch(java.io.IOException e) {
6535 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 -08006536 }
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07006537 // Clean up partially written file
6538 if (mSettingsFilename.exists()) {
6539 if (!mSettingsFilename.delete()) {
6540 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
6541 }
6542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 //Debug.stopMethodTracing();
6544 }
6545
6546 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
6547 throws java.io.IOException {
6548 serializer.startTag(null, "updated-package");
6549 serializer.attribute(null, "name", pkg.name);
6550 serializer.attribute(null, "codePath", pkg.codePathString);
6551 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006552 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006553 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6554 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6555 }
6556 if (pkg.sharedUser == null) {
6557 serializer.attribute(null, "userId",
6558 Integer.toString(pkg.userId));
6559 } else {
6560 serializer.attribute(null, "sharedUserId",
6561 Integer.toString(pkg.userId));
6562 }
6563 serializer.startTag(null, "perms");
6564 if (pkg.sharedUser == null) {
6565 // If this is a shared user, the permissions will
6566 // be written there. We still need to write an
6567 // empty permissions list so permissionsFixed will
6568 // be set.
6569 for (final String name : pkg.grantedPermissions) {
6570 BasePermission bp = mPermissions.get(name);
6571 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
6572 // We only need to write signature or system permissions but this wont
6573 // match the semantics of grantedPermissions. So write all permissions.
6574 serializer.startTag(null, "item");
6575 serializer.attribute(null, "name", name);
6576 serializer.endTag(null, "item");
6577 }
6578 }
6579 }
6580 serializer.endTag(null, "perms");
6581 serializer.endTag(null, "updated-package");
6582 }
6583
6584 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
6585 throws java.io.IOException {
6586 serializer.startTag(null, "package");
6587 serializer.attribute(null, "name", pkg.name);
6588 serializer.attribute(null, "codePath", pkg.codePathString);
6589 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6590 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6591 }
6592 serializer.attribute(null, "system",
6593 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6594 ? "true" : "false");
6595 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006596 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 if (pkg.sharedUser == null) {
6598 serializer.attribute(null, "userId",
6599 Integer.toString(pkg.userId));
6600 } else {
6601 serializer.attribute(null, "sharedUserId",
6602 Integer.toString(pkg.userId));
6603 }
6604 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6605 serializer.attribute(null, "enabled",
6606 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6607 ? "true" : "false");
6608 }
6609 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6610 serializer.attribute(null, "installStatus", "false");
6611 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006612 if (pkg.installerPackageName != null) {
6613 serializer.attribute(null, "installer", pkg.installerPackageName);
6614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6616 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6617 serializer.startTag(null, "perms");
6618 if (pkg.sharedUser == null) {
6619 // If this is a shared user, the permissions will
6620 // be written there. We still need to write an
6621 // empty permissions list so permissionsFixed will
6622 // be set.
6623 for (final String name : pkg.grantedPermissions) {
6624 serializer.startTag(null, "item");
6625 serializer.attribute(null, "name", name);
6626 serializer.endTag(null, "item");
6627 }
6628 }
6629 serializer.endTag(null, "perms");
6630 }
6631 if (pkg.disabledComponents.size() > 0) {
6632 serializer.startTag(null, "disabled-components");
6633 for (final String name : pkg.disabledComponents) {
6634 serializer.startTag(null, "item");
6635 serializer.attribute(null, "name", name);
6636 serializer.endTag(null, "item");
6637 }
6638 serializer.endTag(null, "disabled-components");
6639 }
6640 if (pkg.enabledComponents.size() > 0) {
6641 serializer.startTag(null, "enabled-components");
6642 for (final String name : pkg.enabledComponents) {
6643 serializer.startTag(null, "item");
6644 serializer.attribute(null, "name", name);
6645 serializer.endTag(null, "item");
6646 }
6647 serializer.endTag(null, "enabled-components");
6648 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 serializer.endTag(null, "package");
6651 }
6652
6653 void writePermission(XmlSerializer serializer, BasePermission bp)
6654 throws XmlPullParserException, java.io.IOException {
6655 if (bp.type != BasePermission.TYPE_BUILTIN
6656 && bp.sourcePackage != null) {
6657 serializer.startTag(null, "item");
6658 serializer.attribute(null, "name", bp.name);
6659 serializer.attribute(null, "package", bp.sourcePackage);
6660 if (DEBUG_SETTINGS) Log.v(TAG,
6661 "Writing perm: name=" + bp.name + " type=" + bp.type);
6662 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6663 PermissionInfo pi = bp.perm != null ? bp.perm.info
6664 : bp.pendingInfo;
6665 if (pi != null) {
6666 serializer.attribute(null, "type", "dynamic");
6667 if (pi.icon != 0) {
6668 serializer.attribute(null, "icon",
6669 Integer.toString(pi.icon));
6670 }
6671 if (pi.nonLocalizedLabel != null) {
6672 serializer.attribute(null, "label",
6673 pi.nonLocalizedLabel.toString());
6674 }
6675 if (pi.protectionLevel !=
6676 PermissionInfo.PROTECTION_NORMAL) {
6677 serializer.attribute(null, "protection",
6678 Integer.toString(pi.protectionLevel));
6679 }
6680 }
6681 }
6682 serializer.endTag(null, "item");
6683 }
6684 }
6685
6686 String getReadMessagesLP() {
6687 return mReadMessages.toString();
6688 }
6689
6690 ArrayList<String> getListOfIncompleteInstallPackages() {
6691 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6692 Iterator<String> its = kList.iterator();
6693 ArrayList<String> ret = new ArrayList<String>();
6694 while(its.hasNext()) {
6695 String key = its.next();
6696 PackageSetting ps = mPackages.get(key);
6697 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
6698 ret.add(key);
6699 }
6700 }
6701 return ret;
6702 }
6703
6704 boolean readLP() {
6705 FileInputStream str = null;
6706 if (mBackupSettingsFilename.exists()) {
6707 try {
6708 str = new FileInputStream(mBackupSettingsFilename);
6709 mReadMessages.append("Reading from backup settings file\n");
6710 Log.i(TAG, "Reading from backup settings file!");
6711 } catch (java.io.IOException e) {
6712 // We'll try for the normal settings file.
6713 }
6714 }
6715
6716 mPastSignatures.clear();
6717
6718 try {
6719 if (str == null) {
6720 if (!mSettingsFilename.exists()) {
6721 mReadMessages.append("No settings file found\n");
6722 Log.i(TAG, "No current settings file!");
6723 return false;
6724 }
6725 str = new FileInputStream(mSettingsFilename);
6726 }
6727 XmlPullParser parser = Xml.newPullParser();
6728 parser.setInput(str, null);
6729
6730 int type;
6731 while ((type=parser.next()) != XmlPullParser.START_TAG
6732 && type != XmlPullParser.END_DOCUMENT) {
6733 ;
6734 }
6735
6736 if (type != XmlPullParser.START_TAG) {
6737 mReadMessages.append("No start tag found in settings file\n");
6738 Log.e(TAG, "No start tag found in package manager settings");
6739 return false;
6740 }
6741
6742 int outerDepth = parser.getDepth();
6743 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6744 && (type != XmlPullParser.END_TAG
6745 || parser.getDepth() > outerDepth)) {
6746 if (type == XmlPullParser.END_TAG
6747 || type == XmlPullParser.TEXT) {
6748 continue;
6749 }
6750
6751 String tagName = parser.getName();
6752 if (tagName.equals("package")) {
6753 readPackageLP(parser);
6754 } else if (tagName.equals("permissions")) {
6755 readPermissionsLP(mPermissions, parser);
6756 } else if (tagName.equals("permission-trees")) {
6757 readPermissionsLP(mPermissionTrees, parser);
6758 } else if (tagName.equals("shared-user")) {
6759 readSharedUserLP(parser);
6760 } else if (tagName.equals("preferred-packages")) {
6761 readPreferredPackagesLP(parser);
6762 } else if (tagName.equals("preferred-activities")) {
6763 readPreferredActivitiesLP(parser);
6764 } else if(tagName.equals("updated-package")) {
6765 readDisabledSysPackageLP(parser);
6766 } else {
6767 Log.w(TAG, "Unknown element under <packages>: "
6768 + parser.getName());
6769 XmlUtils.skipCurrentTag(parser);
6770 }
6771 }
6772
6773 str.close();
6774
6775 } catch(XmlPullParserException e) {
6776 mReadMessages.append("Error reading: " + e.toString());
6777 Log.e(TAG, "Error reading package manager settings", e);
6778
6779 } catch(java.io.IOException e) {
6780 mReadMessages.append("Error reading: " + e.toString());
6781 Log.e(TAG, "Error reading package manager settings", e);
6782
6783 }
6784
6785 int N = mPendingPackages.size();
6786 for (int i=0; i<N; i++) {
6787 final PendingPackage pp = mPendingPackages.get(i);
6788 Object idObj = getUserIdLP(pp.sharedId);
6789 if (idObj != null && idObj instanceof SharedUserSetting) {
6790 PackageSetting p = getPackageLP(pp.name,
6791 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006792 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 if (p == null) {
6794 Log.w(TAG, "Unable to create application package for "
6795 + pp.name);
6796 continue;
6797 }
6798 p.copyFrom(pp);
6799 } else if (idObj != null) {
6800 String msg = "Bad package setting: package " + pp.name
6801 + " has shared uid " + pp.sharedId
6802 + " that is not a shared uid\n";
6803 mReadMessages.append(msg);
6804 Log.e(TAG, msg);
6805 } else {
6806 String msg = "Bad package setting: package " + pp.name
6807 + " has shared uid " + pp.sharedId
6808 + " that is not defined\n";
6809 mReadMessages.append(msg);
6810 Log.e(TAG, msg);
6811 }
6812 }
6813 mPendingPackages.clear();
6814
6815 N = mPendingPreferredPackages.size();
6816 mPreferredPackages.clear();
6817 for (int i=0; i<N; i++) {
6818 final String name = mPendingPreferredPackages.get(i);
6819 final PackageSetting p = mPackages.get(name);
6820 if (p != null) {
6821 mPreferredPackages.add(p);
6822 } else {
6823 Log.w(TAG, "Unknown preferred package: " + name);
6824 }
6825 }
6826 mPendingPreferredPackages.clear();
6827
6828 mReadMessages.append("Read completed successfully: "
6829 + mPackages.size() + " packages, "
6830 + mSharedUsers.size() + " shared uids\n");
6831
6832 return true;
6833 }
6834
6835 private int readInt(XmlPullParser parser, String ns, String name,
6836 int defValue) {
6837 String v = parser.getAttributeValue(ns, name);
6838 try {
6839 if (v == null) {
6840 return defValue;
6841 }
6842 return Integer.parseInt(v);
6843 } catch (NumberFormatException e) {
6844 reportSettingsProblem(Log.WARN,
6845 "Error in package manager settings: attribute " +
6846 name + " has bad integer value " + v + " at "
6847 + parser.getPositionDescription());
6848 }
6849 return defValue;
6850 }
6851
6852 private void readPermissionsLP(HashMap<String, BasePermission> out,
6853 XmlPullParser parser)
6854 throws IOException, XmlPullParserException {
6855 int outerDepth = parser.getDepth();
6856 int type;
6857 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6858 && (type != XmlPullParser.END_TAG
6859 || parser.getDepth() > outerDepth)) {
6860 if (type == XmlPullParser.END_TAG
6861 || type == XmlPullParser.TEXT) {
6862 continue;
6863 }
6864
6865 String tagName = parser.getName();
6866 if (tagName.equals("item")) {
6867 String name = parser.getAttributeValue(null, "name");
6868 String sourcePackage = parser.getAttributeValue(null, "package");
6869 String ptype = parser.getAttributeValue(null, "type");
6870 if (name != null && sourcePackage != null) {
6871 boolean dynamic = "dynamic".equals(ptype);
6872 BasePermission bp = new BasePermission(name, sourcePackage,
6873 dynamic
6874 ? BasePermission.TYPE_DYNAMIC
6875 : BasePermission.TYPE_NORMAL);
6876 if (dynamic) {
6877 PermissionInfo pi = new PermissionInfo();
6878 pi.packageName = sourcePackage.intern();
6879 pi.name = name.intern();
6880 pi.icon = readInt(parser, null, "icon", 0);
6881 pi.nonLocalizedLabel = parser.getAttributeValue(
6882 null, "label");
6883 pi.protectionLevel = readInt(parser, null, "protection",
6884 PermissionInfo.PROTECTION_NORMAL);
6885 bp.pendingInfo = pi;
6886 }
6887 out.put(bp.name, bp);
6888 } else {
6889 reportSettingsProblem(Log.WARN,
6890 "Error in package manager settings: permissions has"
6891 + " no name at " + parser.getPositionDescription());
6892 }
6893 } else {
6894 reportSettingsProblem(Log.WARN,
6895 "Unknown element reading permissions: "
6896 + parser.getName() + " at "
6897 + parser.getPositionDescription());
6898 }
6899 XmlUtils.skipCurrentTag(parser);
6900 }
6901 }
6902
6903 private void readDisabledSysPackageLP(XmlPullParser parser)
6904 throws XmlPullParserException, IOException {
6905 String name = parser.getAttributeValue(null, "name");
6906 String codePathStr = parser.getAttributeValue(null, "codePath");
6907 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6908 if(resourcePathStr == null) {
6909 resourcePathStr = codePathStr;
6910 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006911 String version = parser.getAttributeValue(null, "version");
6912 int versionCode = 0;
6913 if (version != null) {
6914 try {
6915 versionCode = Integer.parseInt(version);
6916 } catch (NumberFormatException e) {
6917 }
6918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006919
6920 int pkgFlags = 0;
6921 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6922 PackageSetting ps = new PackageSetting(name,
6923 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006924 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 String timeStampStr = parser.getAttributeValue(null, "ts");
6926 if (timeStampStr != null) {
6927 try {
6928 long timeStamp = Long.parseLong(timeStampStr);
6929 ps.setTimeStamp(timeStamp, timeStampStr);
6930 } catch (NumberFormatException e) {
6931 }
6932 }
6933 String idStr = parser.getAttributeValue(null, "userId");
6934 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
6935 if(ps.userId <= 0) {
6936 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6937 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
6938 }
6939 int outerDepth = parser.getDepth();
6940 int type;
6941 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6942 && (type != XmlPullParser.END_TAG
6943 || parser.getDepth() > outerDepth)) {
6944 if (type == XmlPullParser.END_TAG
6945 || type == XmlPullParser.TEXT) {
6946 continue;
6947 }
6948
6949 String tagName = parser.getName();
6950 if (tagName.equals("perms")) {
6951 readGrantedPermissionsLP(parser,
6952 ps.grantedPermissions);
6953 } else {
6954 reportSettingsProblem(Log.WARN,
6955 "Unknown element under <updated-package>: "
6956 + parser.getName());
6957 XmlUtils.skipCurrentTag(parser);
6958 }
6959 }
6960 mDisabledSysPackages.put(name, ps);
6961 }
6962
6963 private void readPackageLP(XmlPullParser parser)
6964 throws XmlPullParserException, IOException {
6965 String name = null;
6966 String idStr = null;
6967 String sharedIdStr = null;
6968 String codePathStr = null;
6969 String resourcePathStr = null;
6970 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02006971 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006972 int pkgFlags = 0;
6973 String timeStampStr;
6974 long timeStamp = 0;
6975 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006976 String version = null;
6977 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 try {
6979 name = parser.getAttributeValue(null, "name");
6980 idStr = parser.getAttributeValue(null, "userId");
6981 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6982 codePathStr = parser.getAttributeValue(null, "codePath");
6983 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006984 version = parser.getAttributeValue(null, "version");
6985 if (version != null) {
6986 try {
6987 versionCode = Integer.parseInt(version);
6988 } catch (NumberFormatException e) {
6989 }
6990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazski65e13172009-04-28 15:26:38 +02006992 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006993 if (systemStr != null) {
6994 if ("true".equals(systemStr)) {
6995 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6996 }
6997 } else {
6998 // Old settings that don't specify system... just treat
6999 // them as system, good enough.
7000 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7001 }
7002 timeStampStr = parser.getAttributeValue(null, "ts");
7003 if (timeStampStr != null) {
7004 try {
7005 timeStamp = Long.parseLong(timeStampStr);
7006 } catch (NumberFormatException e) {
7007 }
7008 }
7009 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
7010 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
7011 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7012 if (resourcePathStr == null) {
7013 resourcePathStr = codePathStr;
7014 }
7015 if (name == null) {
7016 reportSettingsProblem(Log.WARN,
7017 "Error in package manager settings: <package> has no name at "
7018 + parser.getPositionDescription());
7019 } else if (codePathStr == null) {
7020 reportSettingsProblem(Log.WARN,
7021 "Error in package manager settings: <package> has no codePath at "
7022 + parser.getPositionDescription());
7023 } else if (userId > 0) {
7024 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007025 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007026 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7027 + ": userId=" + userId + " pkg=" + packageSetting);
7028 if (packageSetting == null) {
7029 reportSettingsProblem(Log.ERROR,
7030 "Failure adding uid " + userId
7031 + " while parsing settings at "
7032 + parser.getPositionDescription());
7033 } else {
7034 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7035 }
7036 } else if (sharedIdStr != null) {
7037 userId = sharedIdStr != null
7038 ? Integer.parseInt(sharedIdStr) : 0;
7039 if (userId > 0) {
7040 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007041 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007042 packageSetting.setTimeStamp(timeStamp, timeStampStr);
7043 mPendingPackages.add((PendingPackage) packageSetting);
7044 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
7045 + ": sharedUserId=" + userId + " pkg="
7046 + packageSetting);
7047 } else {
7048 reportSettingsProblem(Log.WARN,
7049 "Error in package manager settings: package "
7050 + name + " has bad sharedId " + sharedIdStr
7051 + " at " + parser.getPositionDescription());
7052 }
7053 } else {
7054 reportSettingsProblem(Log.WARN,
7055 "Error in package manager settings: package "
7056 + name + " has bad userId " + idStr + " at "
7057 + parser.getPositionDescription());
7058 }
7059 } catch (NumberFormatException e) {
7060 reportSettingsProblem(Log.WARN,
7061 "Error in package manager settings: package "
7062 + name + " has bad userId " + idStr + " at "
7063 + parser.getPositionDescription());
7064 }
7065 if (packageSetting != null) {
Jacek Surazski65e13172009-04-28 15:26:38 +02007066 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007067 final String enabledStr = parser.getAttributeValue(null, "enabled");
7068 if (enabledStr != null) {
7069 if (enabledStr.equalsIgnoreCase("true")) {
7070 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
7071 } else if (enabledStr.equalsIgnoreCase("false")) {
7072 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
7073 } else if (enabledStr.equalsIgnoreCase("default")) {
7074 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7075 } else {
7076 reportSettingsProblem(Log.WARN,
7077 "Error in package manager settings: package "
7078 + name + " has bad enabled value: " + idStr
7079 + " at " + parser.getPositionDescription());
7080 }
7081 } else {
7082 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7083 }
7084 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
7085 if (installStatusStr != null) {
7086 if (installStatusStr.equalsIgnoreCase("false")) {
7087 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
7088 } else {
7089 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
7090 }
7091 }
7092
7093 int outerDepth = parser.getDepth();
7094 int type;
7095 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7096 && (type != XmlPullParser.END_TAG
7097 || parser.getDepth() > outerDepth)) {
7098 if (type == XmlPullParser.END_TAG
7099 || type == XmlPullParser.TEXT) {
7100 continue;
7101 }
7102
7103 String tagName = parser.getName();
7104 if (tagName.equals("disabled-components")) {
7105 readDisabledComponentsLP(packageSetting, parser);
7106 } else if (tagName.equals("enabled-components")) {
7107 readEnabledComponentsLP(packageSetting, parser);
7108 } else if (tagName.equals("sigs")) {
7109 packageSetting.signatures.readXml(parser, mPastSignatures);
7110 } else if (tagName.equals("perms")) {
7111 readGrantedPermissionsLP(parser,
7112 packageSetting.loadedPermissions);
7113 packageSetting.permissionsFixed = true;
7114 } else {
7115 reportSettingsProblem(Log.WARN,
7116 "Unknown element under <package>: "
7117 + parser.getName());
7118 XmlUtils.skipCurrentTag(parser);
7119 }
7120 }
7121 } else {
7122 XmlUtils.skipCurrentTag(parser);
7123 }
7124 }
7125
7126 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
7127 XmlPullParser parser)
7128 throws IOException, XmlPullParserException {
7129 int outerDepth = parser.getDepth();
7130 int type;
7131 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7132 && (type != XmlPullParser.END_TAG
7133 || parser.getDepth() > outerDepth)) {
7134 if (type == XmlPullParser.END_TAG
7135 || type == XmlPullParser.TEXT) {
7136 continue;
7137 }
7138
7139 String tagName = parser.getName();
7140 if (tagName.equals("item")) {
7141 String name = parser.getAttributeValue(null, "name");
7142 if (name != null) {
7143 packageSetting.disabledComponents.add(name.intern());
7144 } else {
7145 reportSettingsProblem(Log.WARN,
7146 "Error in package manager settings: <disabled-components> has"
7147 + " no name at " + parser.getPositionDescription());
7148 }
7149 } else {
7150 reportSettingsProblem(Log.WARN,
7151 "Unknown element under <disabled-components>: "
7152 + parser.getName());
7153 }
7154 XmlUtils.skipCurrentTag(parser);
7155 }
7156 }
7157
7158 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
7159 XmlPullParser parser)
7160 throws IOException, XmlPullParserException {
7161 int outerDepth = parser.getDepth();
7162 int type;
7163 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7164 && (type != XmlPullParser.END_TAG
7165 || parser.getDepth() > outerDepth)) {
7166 if (type == XmlPullParser.END_TAG
7167 || type == XmlPullParser.TEXT) {
7168 continue;
7169 }
7170
7171 String tagName = parser.getName();
7172 if (tagName.equals("item")) {
7173 String name = parser.getAttributeValue(null, "name");
7174 if (name != null) {
7175 packageSetting.enabledComponents.add(name.intern());
7176 } else {
7177 reportSettingsProblem(Log.WARN,
7178 "Error in package manager settings: <enabled-components> has"
7179 + " no name at " + parser.getPositionDescription());
7180 }
7181 } else {
7182 reportSettingsProblem(Log.WARN,
7183 "Unknown element under <enabled-components>: "
7184 + parser.getName());
7185 }
7186 XmlUtils.skipCurrentTag(parser);
7187 }
7188 }
7189
7190 private void readSharedUserLP(XmlPullParser parser)
7191 throws XmlPullParserException, IOException {
7192 String name = null;
7193 String idStr = null;
7194 int pkgFlags = 0;
7195 SharedUserSetting su = null;
7196 try {
7197 name = parser.getAttributeValue(null, "name");
7198 idStr = parser.getAttributeValue(null, "userId");
7199 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
7200 if ("true".equals(parser.getAttributeValue(null, "system"))) {
7201 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7202 }
7203 if (name == null) {
7204 reportSettingsProblem(Log.WARN,
7205 "Error in package manager settings: <shared-user> has no name at "
7206 + parser.getPositionDescription());
7207 } else if (userId == 0) {
7208 reportSettingsProblem(Log.WARN,
7209 "Error in package manager settings: shared-user "
7210 + name + " has bad userId " + idStr + " at "
7211 + parser.getPositionDescription());
7212 } else {
7213 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
7214 reportSettingsProblem(Log.ERROR,
7215 "Occurred while parsing settings at "
7216 + parser.getPositionDescription());
7217 }
7218 }
7219 } catch (NumberFormatException e) {
7220 reportSettingsProblem(Log.WARN,
7221 "Error in package manager settings: package "
7222 + name + " has bad userId " + idStr + " at "
7223 + parser.getPositionDescription());
7224 };
7225
7226 if (su != null) {
7227 int outerDepth = parser.getDepth();
7228 int type;
7229 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7230 && (type != XmlPullParser.END_TAG
7231 || parser.getDepth() > outerDepth)) {
7232 if (type == XmlPullParser.END_TAG
7233 || type == XmlPullParser.TEXT) {
7234 continue;
7235 }
7236
7237 String tagName = parser.getName();
7238 if (tagName.equals("sigs")) {
7239 su.signatures.readXml(parser, mPastSignatures);
7240 } else if (tagName.equals("perms")) {
7241 readGrantedPermissionsLP(parser, su.loadedPermissions);
7242 } else {
7243 reportSettingsProblem(Log.WARN,
7244 "Unknown element under <shared-user>: "
7245 + parser.getName());
7246 XmlUtils.skipCurrentTag(parser);
7247 }
7248 }
7249
7250 } else {
7251 XmlUtils.skipCurrentTag(parser);
7252 }
7253 }
7254
7255 private void readGrantedPermissionsLP(XmlPullParser parser,
7256 HashSet<String> outPerms) throws IOException, XmlPullParserException {
7257 int outerDepth = parser.getDepth();
7258 int type;
7259 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7260 && (type != XmlPullParser.END_TAG
7261 || parser.getDepth() > outerDepth)) {
7262 if (type == XmlPullParser.END_TAG
7263 || type == XmlPullParser.TEXT) {
7264 continue;
7265 }
7266
7267 String tagName = parser.getName();
7268 if (tagName.equals("item")) {
7269 String name = parser.getAttributeValue(null, "name");
7270 if (name != null) {
7271 outPerms.add(name.intern());
7272 } else {
7273 reportSettingsProblem(Log.WARN,
7274 "Error in package manager settings: <perms> has"
7275 + " no name at " + parser.getPositionDescription());
7276 }
7277 } else {
7278 reportSettingsProblem(Log.WARN,
7279 "Unknown element under <perms>: "
7280 + parser.getName());
7281 }
7282 XmlUtils.skipCurrentTag(parser);
7283 }
7284 }
7285
7286 private void readPreferredPackagesLP(XmlPullParser parser)
7287 throws XmlPullParserException, IOException {
7288 int outerDepth = parser.getDepth();
7289 int type;
7290 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7291 && (type != XmlPullParser.END_TAG
7292 || parser.getDepth() > outerDepth)) {
7293 if (type == XmlPullParser.END_TAG
7294 || type == XmlPullParser.TEXT) {
7295 continue;
7296 }
7297
7298 String tagName = parser.getName();
7299 if (tagName.equals("item")) {
7300 String name = parser.getAttributeValue(null, "name");
7301 if (name != null) {
7302 mPendingPreferredPackages.add(name);
7303 } else {
7304 reportSettingsProblem(Log.WARN,
7305 "Error in package manager settings: <preferred-package> has no name at "
7306 + parser.getPositionDescription());
7307 }
7308 } else {
7309 reportSettingsProblem(Log.WARN,
7310 "Unknown element under <preferred-packages>: "
7311 + parser.getName());
7312 }
7313 XmlUtils.skipCurrentTag(parser);
7314 }
7315 }
7316
7317 private void readPreferredActivitiesLP(XmlPullParser parser)
7318 throws XmlPullParserException, IOException {
7319 int outerDepth = parser.getDepth();
7320 int type;
7321 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7322 && (type != XmlPullParser.END_TAG
7323 || parser.getDepth() > outerDepth)) {
7324 if (type == XmlPullParser.END_TAG
7325 || type == XmlPullParser.TEXT) {
7326 continue;
7327 }
7328
7329 String tagName = parser.getName();
7330 if (tagName.equals("item")) {
7331 PreferredActivity pa = new PreferredActivity(parser);
7332 if (pa.mParseError == null) {
7333 mPreferredActivities.addFilter(pa);
7334 } else {
7335 reportSettingsProblem(Log.WARN,
7336 "Error in package manager settings: <preferred-activity> "
7337 + pa.mParseError + " at "
7338 + parser.getPositionDescription());
7339 }
7340 } else {
7341 reportSettingsProblem(Log.WARN,
7342 "Unknown element under <preferred-activities>: "
7343 + parser.getName());
7344 XmlUtils.skipCurrentTag(parser);
7345 }
7346 }
7347 }
7348
7349 // Returns -1 if we could not find an available UserId to assign
7350 private int newUserIdLP(Object obj) {
7351 // Let's be stupidly inefficient for now...
7352 final int N = mUserIds.size();
7353 for (int i=0; i<N; i++) {
7354 if (mUserIds.get(i) == null) {
7355 mUserIds.set(i, obj);
7356 return FIRST_APPLICATION_UID + i;
7357 }
7358 }
7359
7360 // None left?
7361 if (N >= MAX_APPLICATION_UIDS) {
7362 return -1;
7363 }
7364
7365 mUserIds.add(obj);
7366 return FIRST_APPLICATION_UID + N;
7367 }
7368
7369 public PackageSetting getDisabledSystemPkg(String name) {
7370 synchronized(mPackages) {
7371 PackageSetting ps = mDisabledSysPackages.get(name);
7372 return ps;
7373 }
7374 }
7375
7376 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
7377 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
7378 if (Config.LOGV) {
7379 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
7380 + " componentName = " + componentInfo.name);
7381 Log.v(TAG, "enabledComponents: "
7382 + Arrays.toString(packageSettings.enabledComponents.toArray()));
7383 Log.v(TAG, "disabledComponents: "
7384 + Arrays.toString(packageSettings.disabledComponents.toArray()));
7385 }
7386 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
7387 || ((componentInfo.enabled
7388 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
7389 || (componentInfo.applicationInfo.enabled
7390 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
7391 && !packageSettings.disabledComponents.contains(componentInfo.name))
7392 || packageSettings.enabledComponents.contains(componentInfo.name));
7393 }
7394 }
7395}