blob: 134fb6fb47e0b9e92becd8db0756df995ff47023 [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;
38import android.content.pm.IPackageDataObserver;
39import android.content.pm.IPackageDeleteObserver;
40import android.content.pm.IPackageInstallObserver;
41import android.content.pm.IPackageManager;
42import android.content.pm.IPackageStatsObserver;
43import android.content.pm.InstrumentationInfo;
44import android.content.pm.PackageInfo;
45import android.content.pm.PackageManager;
46import android.content.pm.PackageStats;
47import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
48import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
49import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
50import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
51import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
52import android.content.pm.PackageParser;
53import android.content.pm.PermissionInfo;
54import android.content.pm.PermissionGroupInfo;
55import android.content.pm.ProviderInfo;
56import android.content.pm.ResolveInfo;
57import android.content.pm.ServiceInfo;
58import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.net.Uri;
60import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070061import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.Bundle;
63import android.os.HandlerThread;
64import android.os.Parcel;
65import android.os.RemoteException;
66import android.os.Environment;
67import android.os.FileObserver;
68import android.os.FileUtils;
69import android.os.Handler;
70import android.os.ParcelFileDescriptor;
71import android.os.Process;
72import android.os.ServiceManager;
73import android.os.SystemClock;
74import android.os.SystemProperties;
75import android.util.*;
76import android.view.Display;
77import android.view.WindowManager;
78
79import java.io.File;
80import java.io.FileDescriptor;
81import java.io.FileInputStream;
82import java.io.FileNotFoundException;
83import java.io.FileOutputStream;
84import java.io.FileReader;
85import java.io.FilenameFilter;
86import java.io.IOException;
87import java.io.InputStream;
88import java.io.PrintWriter;
89import java.util.ArrayList;
90import java.util.Arrays;
91import java.util.Collections;
92import java.util.Comparator;
93import java.util.Enumeration;
94import java.util.HashMap;
95import java.util.HashSet;
96import java.util.Iterator;
97import java.util.List;
98import java.util.Map;
99import java.util.Set;
100import java.util.zip.ZipEntry;
101import java.util.zip.ZipFile;
102import java.util.zip.ZipOutputStream;
103
104class PackageManagerService extends IPackageManager.Stub {
105 private static final String TAG = "PackageManager";
106 private static final boolean DEBUG_SETTINGS = false;
107 private static final boolean DEBUG_PREFERRED = false;
108
109 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
110 private static final int RADIO_UID = Process.PHONE_UID;
111 private static final int FIRST_APPLICATION_UID =
112 Process.FIRST_APPLICATION_UID;
113 private static final int MAX_APPLICATION_UIDS = 1000;
114
115 private static final boolean SHOW_INFO = false;
116
117 private static final boolean GET_CERTIFICATES = true;
118
119 private static final int REMOVE_EVENTS =
120 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
121 private static final int ADD_EVENTS =
122 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
123
124 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
125
126 static final int SCAN_MONITOR = 1<<0;
127 static final int SCAN_NO_DEX = 1<<1;
128 static final int SCAN_FORCE_DEX = 1<<2;
129 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
130 static final int SCAN_FORWARD_LOCKED = 1<<4;
The Android Open Source Project10592532009-03-18 17:39:46 -0700131 static final int SCAN_NEW_INSTALL = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132
133 static final int LOG_BOOT_PROGRESS_PMS_START = 3060;
134 static final int LOG_BOOT_PROGRESS_PMS_SYSTEM_SCAN_START = 3070;
135 static final int LOG_BOOT_PROGRESS_PMS_DATA_SCAN_START = 3080;
136 static final int LOG_BOOT_PROGRESS_PMS_SCAN_END = 3090;
137 static final int LOG_BOOT_PROGRESS_PMS_READY = 3100;
138
139 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
140 Process.THREAD_PRIORITY_BACKGROUND);
141 final Handler mHandler;
142
Dianne Hackborn851a5412009-05-08 12:06:44 -0700143 final int mSdkVersion = Build.VERSION.SDK_INT;
144 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
145 ? null : Build.VERSION.CODENAME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146
147 final Context mContext;
148 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700149 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 final DisplayMetrics mMetrics;
151 final int mDefParseFlags;
152 final String[] mSeparateProcesses;
153
154 // This is where all application persistent data goes.
155 final File mAppDataDir;
156
157 // This is the object monitoring the framework dir.
158 final FileObserver mFrameworkInstallObserver;
159
160 // This is the object monitoring the system app dir.
161 final FileObserver mSystemInstallObserver;
162
163 // This is the object monitoring mAppInstallDir.
164 final FileObserver mAppInstallObserver;
165
166 // This is the object monitoring mDrmAppPrivateInstallDir.
167 final FileObserver mDrmAppInstallObserver;
168
169 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
170 // LOCK HELD. Can be called with mInstallLock held.
171 final Installer mInstaller;
172
173 final File mFrameworkDir;
174 final File mSystemAppDir;
175 final File mAppInstallDir;
176
177 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
178 // apps.
179 final File mDrmAppPrivateInstallDir;
180
181 // ----------------------------------------------------------------
182
183 // Lock for state used when installing and doing other long running
184 // operations. Methods that must be called with this lock held have
185 // the prefix "LI".
186 final Object mInstallLock = new Object();
187
188 // These are the directories in the 3rd party applications installed dir
189 // that we have currently loaded packages from. Keys are the application's
190 // installed zip file (absolute codePath), and values are Package.
191 final HashMap<String, PackageParser.Package> mAppDirs =
192 new HashMap<String, PackageParser.Package>();
193
194 // Information for the parser to write more useful error messages.
195 File mScanningPath;
196 int mLastScanError;
197
198 final int[] mOutPermissions = new int[3];
199
200 // ----------------------------------------------------------------
201
202 // Keys are String (package name), values are Package. This also serves
203 // as the lock for the global state. Methods that must be called with
204 // this lock held have the prefix "LP".
205 final HashMap<String, PackageParser.Package> mPackages =
206 new HashMap<String, PackageParser.Package>();
207
208 final Settings mSettings;
209 boolean mRestoredSettings;
210 boolean mReportedUidError;
211
212 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
213 int[] mGlobalGids;
214
215 // These are the built-in uid -> permission mappings that were read from the
216 // etc/permissions.xml file.
217 final SparseArray<HashSet<String>> mSystemPermissions =
218 new SparseArray<HashSet<String>>();
219
220 // These are the built-in shared libraries that were read from the
221 // etc/permissions.xml file.
222 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
223
224 // All available activities, for your resolving pleasure.
225 final ActivityIntentResolver mActivities =
226 new ActivityIntentResolver();
227
228 // All available receivers, for your resolving pleasure.
229 final ActivityIntentResolver mReceivers =
230 new ActivityIntentResolver();
231
232 // All available services, for your resolving pleasure.
233 final ServiceIntentResolver mServices = new ServiceIntentResolver();
234
235 // Keys are String (provider class name), values are Provider.
236 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
237 new HashMap<ComponentName, PackageParser.Provider>();
238
239 // Mapping from provider base names (first directory in content URI codePath)
240 // to the provider information.
241 final HashMap<String, PackageParser.Provider> mProviders =
242 new HashMap<String, PackageParser.Provider>();
243
244 // Mapping from instrumentation class names to info about them.
245 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
246 new HashMap<ComponentName, PackageParser.Instrumentation>();
247
248 // Mapping from permission names to info about them.
249 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
250 new HashMap<String, PackageParser.PermissionGroup>();
251
Dianne Hackborn854060af2009-07-09 18:14:31 -0700252 // Broadcast actions that are only available to the system.
253 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 boolean mSystemReady;
256 boolean mSafeMode;
257 boolean mHasSystemUidErrors;
258
259 ApplicationInfo mAndroidApplication;
260 final ActivityInfo mResolveActivity = new ActivityInfo();
261 final ResolveInfo mResolveInfo = new ResolveInfo();
262 ComponentName mResolveComponentName;
263 PackageParser.Package mPlatformPackage;
264
265 public static final IPackageManager main(Context context, boolean factoryTest) {
266 PackageManagerService m = new PackageManagerService(context, factoryTest);
267 ServiceManager.addService("package", m);
268 return m;
269 }
270
271 static String[] splitString(String str, char sep) {
272 int count = 1;
273 int i = 0;
274 while ((i=str.indexOf(sep, i)) >= 0) {
275 count++;
276 i++;
277 }
278
279 String[] res = new String[count];
280 i=0;
281 count = 0;
282 int lastI=0;
283 while ((i=str.indexOf(sep, i)) >= 0) {
284 res[count] = str.substring(lastI, i);
285 count++;
286 i++;
287 lastI = i;
288 }
289 res[count] = str.substring(lastI, str.length());
290 return res;
291 }
292
293 public PackageManagerService(Context context, boolean factoryTest) {
294 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_START,
295 SystemClock.uptimeMillis());
296
297 if (mSdkVersion <= 0) {
298 Log.w(TAG, "**** ro.build.version.sdk not set!");
299 }
300
301 mContext = context;
302 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700303 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 mMetrics = new DisplayMetrics();
305 mSettings = new Settings();
306 mSettings.addSharedUserLP("android.uid.system",
307 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
308 mSettings.addSharedUserLP("android.uid.phone",
309 MULTIPLE_APPLICATION_UIDS
310 ? RADIO_UID : FIRST_APPLICATION_UID,
311 ApplicationInfo.FLAG_SYSTEM);
312
313 String separateProcesses = SystemProperties.get("debug.separate_processes");
314 if (separateProcesses != null && separateProcesses.length() > 0) {
315 if ("*".equals(separateProcesses)) {
316 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
317 mSeparateProcesses = null;
318 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
319 } else {
320 mDefParseFlags = 0;
321 mSeparateProcesses = separateProcesses.split(",");
322 Log.w(TAG, "Running with debug.separate_processes: "
323 + separateProcesses);
324 }
325 } else {
326 mDefParseFlags = 0;
327 mSeparateProcesses = null;
328 }
329
330 Installer installer = new Installer();
331 // Little hacky thing to check if installd is here, to determine
332 // whether we are running on the simulator and thus need to take
333 // care of building the /data file structure ourself.
334 // (apparently the sim now has a working installer)
335 if (installer.ping() && Process.supportsProcesses()) {
336 mInstaller = installer;
337 } else {
338 mInstaller = null;
339 }
340
341 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
342 Display d = wm.getDefaultDisplay();
343 d.getMetrics(mMetrics);
344
345 synchronized (mInstallLock) {
346 synchronized (mPackages) {
347 mHandlerThread.start();
348 mHandler = new Handler(mHandlerThread.getLooper());
349
350 File dataDir = Environment.getDataDirectory();
351 mAppDataDir = new File(dataDir, "data");
352 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
353
354 if (mInstaller == null) {
355 // Make sure these dirs exist, when we are running in
356 // the simulator.
357 // Make a wide-open directory for random misc stuff.
358 File miscDir = new File(dataDir, "misc");
359 miscDir.mkdirs();
360 mAppDataDir.mkdirs();
361 mDrmAppPrivateInstallDir.mkdirs();
362 }
363
364 readPermissions();
365
366 mRestoredSettings = mSettings.readLP();
367 long startTime = SystemClock.uptimeMillis();
368
369 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
370 startTime);
371
372 int scanMode = SCAN_MONITOR;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700373 if (mNoDexOpt) {
374 Log.w(TAG, "Running ENG build: no pre-dexopt!");
375 scanMode |= SCAN_NO_DEX;
376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377
378 final HashSet<String> libFiles = new HashSet<String>();
379
380 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
381
382 if (mInstaller != null) {
383 /**
384 * Out of paranoia, ensure that everything in the boot class
385 * path has been dexed.
386 */
387 String bootClassPath = System.getProperty("java.boot.class.path");
388 if (bootClassPath != null) {
389 String[] paths = splitString(bootClassPath, ':');
390 for (int i=0; i<paths.length; i++) {
391 try {
392 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
393 libFiles.add(paths[i]);
394 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
395 }
396 } catch (FileNotFoundException e) {
397 Log.w(TAG, "Boot class path not found: " + paths[i]);
398 } catch (IOException e) {
399 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
400 }
401 }
402 } else {
403 Log.w(TAG, "No BOOTCLASSPATH found!");
404 }
405
406 /**
407 * Also ensure all external libraries have had dexopt run on them.
408 */
409 if (mSharedLibraries.size() > 0) {
410 Iterator<String> libs = mSharedLibraries.values().iterator();
411 while (libs.hasNext()) {
412 String lib = libs.next();
413 try {
414 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
415 libFiles.add(lib);
416 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
417 }
418 } catch (FileNotFoundException e) {
419 Log.w(TAG, "Library not found: " + lib);
420 } catch (IOException e) {
421 Log.w(TAG, "Exception reading library: " + lib, e);
422 }
423 }
424 }
425
426 // Gross hack for now: we know this file doesn't contain any
427 // code, so don't dexopt it to avoid the resulting log spew.
428 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
429
430 /**
431 * And there are a number of commands implemented in Java, which
432 * we currently need to do the dexopt on so that they can be
433 * run from a non-root shell.
434 */
435 String[] frameworkFiles = mFrameworkDir.list();
436 if (frameworkFiles != null && mInstaller != null) {
437 for (int i=0; i<frameworkFiles.length; i++) {
438 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
439 String path = libPath.getPath();
440 // Skip the file if we alrady did it.
441 if (libFiles.contains(path)) {
442 continue;
443 }
444 // Skip the file if it is not a type we want to dexopt.
445 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
446 continue;
447 }
448 try {
449 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
450 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
451 }
452 } catch (FileNotFoundException e) {
453 Log.w(TAG, "Jar not found: " + path);
454 } catch (IOException e) {
455 Log.w(TAG, "Exception reading jar: " + path, e);
456 }
457 }
458 }
459 }
460
461 mFrameworkInstallObserver = new AppDirObserver(
462 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
463 mFrameworkInstallObserver.startWatching();
464 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
465 scanMode | SCAN_NO_DEX);
466 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
467 mSystemInstallObserver = new AppDirObserver(
468 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
469 mSystemInstallObserver.startWatching();
470 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
471 mAppInstallDir = new File(dataDir, "app");
472 if (mInstaller == null) {
473 // Make sure these dirs exist, when we are running in
474 // the simulator.
475 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
476 }
477 //look for any incomplete package installations
478 ArrayList<String> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
479 //clean up list
480 for(int i = 0; i < deletePkgsList.size(); i++) {
481 //clean up here
482 cleanupInstallFailedPackage(deletePkgsList.get(i));
483 }
484 //delete tmp files
485 deleteTempPackageFiles();
486
487 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_DATA_SCAN_START,
488 SystemClock.uptimeMillis());
489 mAppInstallObserver = new AppDirObserver(
490 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
491 mAppInstallObserver.startWatching();
492 scanDirLI(mAppInstallDir, 0, scanMode);
493
494 mDrmAppInstallObserver = new AppDirObserver(
495 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
496 mDrmAppInstallObserver.startWatching();
497 scanDirLI(mDrmAppPrivateInstallDir, 0, scanMode);
498
499 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_SCAN_END,
500 SystemClock.uptimeMillis());
501 Log.i(TAG, "Time to scan packages: "
502 + ((SystemClock.uptimeMillis()-startTime)/1000f)
503 + " seconds");
504
505 updatePermissionsLP();
506
507 mSettings.writeLP();
508
509 EventLog.writeEvent(LOG_BOOT_PROGRESS_PMS_READY,
510 SystemClock.uptimeMillis());
511
512 // Now after opening every single application zip, make sure they
513 // are all flushed. Not really needed, but keeps things nice and
514 // tidy.
515 Runtime.getRuntime().gc();
516 } // synchronized (mPackages)
517 } // synchronized (mInstallLock)
518 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 @Override
521 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
522 throws RemoteException {
523 try {
524 return super.onTransact(code, data, reply, flags);
525 } catch (RuntimeException e) {
526 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
527 Log.e(TAG, "Package Manager Crash", e);
528 }
529 throw e;
530 }
531 }
532
533 void cleanupInstallFailedPackage(String packageName) {
534 if (mInstaller != null) {
535 int retCode = mInstaller.remove(packageName);
536 if (retCode < 0) {
537 Log.w(TAG, "Couldn't remove app data directory for package: "
538 + packageName + ", retcode=" + retCode);
539 }
540 } else {
541 //for emulator
542 PackageParser.Package pkg = mPackages.get(packageName);
543 File dataDir = new File(pkg.applicationInfo.dataDir);
544 dataDir.delete();
545 }
546 mSettings.removePackageLP(packageName);
547 }
548
549 void readPermissions() {
550 // Read permissions from .../etc/permission directory.
551 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
552 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
553 Log.w(TAG, "No directory " + libraryDir + ", skipping");
554 return;
555 }
556 if (!libraryDir.canRead()) {
557 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
558 return;
559 }
560
561 // Iterate over the files in the directory and scan .xml files
562 for (File f : libraryDir.listFiles()) {
563 // We'll read platform.xml last
564 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
565 continue;
566 }
567
568 if (!f.getPath().endsWith(".xml")) {
569 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
570 continue;
571 }
572 if (!f.canRead()) {
573 Log.w(TAG, "Permissions library file " + f + " cannot be read");
574 continue;
575 }
576
577 readPermissionsFromXml(f);
578 }
579
580 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
581 final File permFile = new File(Environment.getRootDirectory(),
582 "etc/permissions/platform.xml");
583 readPermissionsFromXml(permFile);
584 }
585
586 private void readPermissionsFromXml(File permFile) {
587 FileReader permReader = null;
588 try {
589 permReader = new FileReader(permFile);
590 } catch (FileNotFoundException e) {
591 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
592 return;
593 }
594
595 try {
596 XmlPullParser parser = Xml.newPullParser();
597 parser.setInput(permReader);
598
599 XmlUtils.beginDocument(parser, "permissions");
600
601 while (true) {
602 XmlUtils.nextElement(parser);
603 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
604 break;
605 }
606
607 String name = parser.getName();
608 if ("group".equals(name)) {
609 String gidStr = parser.getAttributeValue(null, "gid");
610 if (gidStr != null) {
611 int gid = Integer.parseInt(gidStr);
612 mGlobalGids = appendInt(mGlobalGids, gid);
613 } else {
614 Log.w(TAG, "<group> without gid at "
615 + parser.getPositionDescription());
616 }
617
618 XmlUtils.skipCurrentTag(parser);
619 continue;
620 } else if ("permission".equals(name)) {
621 String perm = parser.getAttributeValue(null, "name");
622 if (perm == null) {
623 Log.w(TAG, "<permission> without name at "
624 + parser.getPositionDescription());
625 XmlUtils.skipCurrentTag(parser);
626 continue;
627 }
628 perm = perm.intern();
629 readPermission(parser, perm);
630
631 } else if ("assign-permission".equals(name)) {
632 String perm = parser.getAttributeValue(null, "name");
633 if (perm == null) {
634 Log.w(TAG, "<assign-permission> without name at "
635 + parser.getPositionDescription());
636 XmlUtils.skipCurrentTag(parser);
637 continue;
638 }
639 String uidStr = parser.getAttributeValue(null, "uid");
640 if (uidStr == null) {
641 Log.w(TAG, "<assign-permission> without uid at "
642 + parser.getPositionDescription());
643 XmlUtils.skipCurrentTag(parser);
644 continue;
645 }
646 int uid = Process.getUidForName(uidStr);
647 if (uid < 0) {
648 Log.w(TAG, "<assign-permission> with unknown uid \""
649 + uidStr + "\" at "
650 + parser.getPositionDescription());
651 XmlUtils.skipCurrentTag(parser);
652 continue;
653 }
654 perm = perm.intern();
655 HashSet<String> perms = mSystemPermissions.get(uid);
656 if (perms == null) {
657 perms = new HashSet<String>();
658 mSystemPermissions.put(uid, perms);
659 }
660 perms.add(perm);
661 XmlUtils.skipCurrentTag(parser);
662
663 } else if ("library".equals(name)) {
664 String lname = parser.getAttributeValue(null, "name");
665 String lfile = parser.getAttributeValue(null, "file");
666 if (lname == null) {
667 Log.w(TAG, "<library> without name at "
668 + parser.getPositionDescription());
669 } else if (lfile == null) {
670 Log.w(TAG, "<library> without file at "
671 + parser.getPositionDescription());
672 } else {
673 Log.i(TAG, "Got library " + lname + " in " + lfile);
674 this.mSharedLibraries.put(lname, lfile);
675 }
676 XmlUtils.skipCurrentTag(parser);
677 continue;
678
679 } else {
680 XmlUtils.skipCurrentTag(parser);
681 continue;
682 }
683
684 }
685 } catch (XmlPullParserException e) {
686 Log.w(TAG, "Got execption parsing permissions.", e);
687 } catch (IOException e) {
688 Log.w(TAG, "Got execption parsing permissions.", e);
689 }
690 }
691
692 void readPermission(XmlPullParser parser, String name)
693 throws IOException, XmlPullParserException {
694
695 name = name.intern();
696
697 BasePermission bp = mSettings.mPermissions.get(name);
698 if (bp == null) {
699 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
700 mSettings.mPermissions.put(name, bp);
701 }
702 int outerDepth = parser.getDepth();
703 int type;
704 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
705 && (type != XmlPullParser.END_TAG
706 || parser.getDepth() > outerDepth)) {
707 if (type == XmlPullParser.END_TAG
708 || type == XmlPullParser.TEXT) {
709 continue;
710 }
711
712 String tagName = parser.getName();
713 if ("group".equals(tagName)) {
714 String gidStr = parser.getAttributeValue(null, "gid");
715 if (gidStr != null) {
716 int gid = Process.getGidForName(gidStr);
717 bp.gids = appendInt(bp.gids, gid);
718 } else {
719 Log.w(TAG, "<group> without gid at "
720 + parser.getPositionDescription());
721 }
722 }
723 XmlUtils.skipCurrentTag(parser);
724 }
725 }
726
727 static int[] appendInt(int[] cur, int val) {
728 if (cur == null) {
729 return new int[] { val };
730 }
731 final int N = cur.length;
732 for (int i=0; i<N; i++) {
733 if (cur[i] == val) {
734 return cur;
735 }
736 }
737 int[] ret = new int[N+1];
738 System.arraycopy(cur, 0, ret, 0, N);
739 ret[N] = val;
740 return ret;
741 }
742
743 static int[] appendInts(int[] cur, int[] add) {
744 if (add == null) return cur;
745 if (cur == null) return add;
746 final int N = add.length;
747 for (int i=0; i<N; i++) {
748 cur = appendInt(cur, add[i]);
749 }
750 return cur;
751 }
752
753 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
754 final PackageSetting ps = (PackageSetting)p.mExtras;
755 if (ps == null) {
756 return null;
757 }
758 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
759 return PackageParser.generatePackageInfo(p, gp.gids, flags);
760 }
761
762 public PackageInfo getPackageInfo(String packageName, int flags) {
763 synchronized (mPackages) {
764 PackageParser.Package p = mPackages.get(packageName);
765 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700766 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 + ": " + p);
768 if (p != null) {
769 return generatePackageInfo(p, flags);
770 }
771 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
772 return generatePackageInfoFromSettingsLP(packageName, flags);
773 }
774 }
775 return null;
776 }
777
778 public int getPackageUid(String packageName) {
779 synchronized (mPackages) {
780 PackageParser.Package p = mPackages.get(packageName);
781 if(p != null) {
782 return p.applicationInfo.uid;
783 }
784 PackageSetting ps = mSettings.mPackages.get(packageName);
785 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
786 return -1;
787 }
788 p = ps.pkg;
789 return p != null ? p.applicationInfo.uid : -1;
790 }
791 }
792
793 public int[] getPackageGids(String packageName) {
794 synchronized (mPackages) {
795 PackageParser.Package p = mPackages.get(packageName);
796 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700797 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 + ": " + p);
799 if (p != null) {
800 final PackageSetting ps = (PackageSetting)p.mExtras;
801 final SharedUserSetting suid = ps.sharedUser;
802 return suid != null ? suid.gids : ps.gids;
803 }
804 }
805 // stupid thing to indicate an error.
806 return new int[0];
807 }
808
809 public PermissionInfo getPermissionInfo(String name, int flags) {
810 synchronized (mPackages) {
811 final BasePermission p = mSettings.mPermissions.get(name);
812 if (p != null && p.perm != null) {
813 return PackageParser.generatePermissionInfo(p.perm, flags);
814 }
815 return null;
816 }
817 }
818
819 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
820 synchronized (mPackages) {
821 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
822 for (BasePermission p : mSettings.mPermissions.values()) {
823 if (group == null) {
824 if (p.perm.info.group == null) {
825 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
826 }
827 } else {
828 if (group.equals(p.perm.info.group)) {
829 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
830 }
831 }
832 }
833
834 if (out.size() > 0) {
835 return out;
836 }
837 return mPermissionGroups.containsKey(group) ? out : null;
838 }
839 }
840
841 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
842 synchronized (mPackages) {
843 return PackageParser.generatePermissionGroupInfo(
844 mPermissionGroups.get(name), flags);
845 }
846 }
847
848 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
849 synchronized (mPackages) {
850 final int N = mPermissionGroups.size();
851 ArrayList<PermissionGroupInfo> out
852 = new ArrayList<PermissionGroupInfo>(N);
853 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
854 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
855 }
856 return out;
857 }
858 }
859
860 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
861 PackageSetting ps = mSettings.mPackages.get(packageName);
862 if(ps != null) {
863 if(ps.pkg == null) {
864 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
865 if(pInfo != null) {
866 return pInfo.applicationInfo;
867 }
868 return null;
869 }
870 return PackageParser.generateApplicationInfo(ps.pkg, flags);
871 }
872 return null;
873 }
874
875 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
876 PackageSetting ps = mSettings.mPackages.get(packageName);
877 if(ps != null) {
878 if(ps.pkg == null) {
879 ps.pkg = new PackageParser.Package(packageName);
880 ps.pkg.applicationInfo.packageName = packageName;
881 }
882 return generatePackageInfo(ps.pkg, flags);
883 }
884 return null;
885 }
886
887 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
888 synchronized (mPackages) {
889 PackageParser.Package p = mPackages.get(packageName);
890 if (Config.LOGV) Log.v(
891 TAG, "getApplicationInfo " + packageName
892 + ": " + p);
893 if (p != null) {
894 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -0700895 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 }
897 if ("android".equals(packageName)||"system".equals(packageName)) {
898 return mAndroidApplication;
899 }
900 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
901 return generateApplicationInfoFromSettingsLP(packageName, flags);
902 }
903 }
904 return null;
905 }
906
907
908 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
909 mContext.enforceCallingOrSelfPermission(
910 android.Manifest.permission.CLEAR_APP_CACHE, null);
911 // Queue up an async operation since clearing cache may take a little while.
912 mHandler.post(new Runnable() {
913 public void run() {
914 mHandler.removeCallbacks(this);
915 int retCode = -1;
916 if (mInstaller != null) {
917 retCode = mInstaller.freeCache(freeStorageSize);
918 if (retCode < 0) {
919 Log.w(TAG, "Couldn't clear application caches");
920 }
921 } //end if mInstaller
922 if (observer != null) {
923 try {
924 observer.onRemoveCompleted(null, (retCode >= 0));
925 } catch (RemoteException e) {
926 Log.w(TAG, "RemoveException when invoking call back");
927 }
928 }
929 }
930 });
931 }
932
Suchi Amalapurapubc806f62009-06-17 15:18:19 -0700933 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -0700934 mContext.enforceCallingOrSelfPermission(
935 android.Manifest.permission.CLEAR_APP_CACHE, null);
936 // Queue up an async operation since clearing cache may take a little while.
937 mHandler.post(new Runnable() {
938 public void run() {
939 mHandler.removeCallbacks(this);
940 int retCode = -1;
941 if (mInstaller != null) {
942 retCode = mInstaller.freeCache(freeStorageSize);
943 if (retCode < 0) {
944 Log.w(TAG, "Couldn't clear application caches");
945 }
946 }
947 if(pi != null) {
948 try {
949 // Callback via pending intent
950 int code = (retCode >= 0) ? 1 : 0;
951 pi.sendIntent(null, code, null,
952 null, null);
953 } catch (SendIntentException e1) {
954 Log.i(TAG, "Failed to send pending intent");
955 }
956 }
957 }
958 });
959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960
961 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
962 synchronized (mPackages) {
963 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700964
965 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -0700967 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
969 if (mResolveComponentName.equals(component)) {
970 return mResolveActivity;
971 }
972 }
973 return null;
974 }
975
976 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
977 synchronized (mPackages) {
978 PackageParser.Activity a = mReceivers.mActivities.get(component);
979 if (Config.LOGV) Log.v(
980 TAG, "getReceiverInfo " + component + ": " + a);
981 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
982 return PackageParser.generateActivityInfo(a, flags);
983 }
984 }
985 return null;
986 }
987
988 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
989 synchronized (mPackages) {
990 PackageParser.Service s = mServices.mServices.get(component);
991 if (Config.LOGV) Log.v(
992 TAG, "getServiceInfo " + component + ": " + s);
993 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
994 return PackageParser.generateServiceInfo(s, flags);
995 }
996 }
997 return null;
998 }
999
1000 public String[] getSystemSharedLibraryNames() {
1001 Set<String> libSet;
1002 synchronized (mPackages) {
1003 libSet = mSharedLibraries.keySet();
1004 }
1005 int size = libSet.size();
1006 if (size > 0) {
1007 String[] libs = new String[size];
1008 libSet.toArray(libs);
1009 return libs;
1010 }
1011 return null;
1012 }
1013
1014 public int checkPermission(String permName, String pkgName) {
1015 synchronized (mPackages) {
1016 PackageParser.Package p = mPackages.get(pkgName);
1017 if (p != null && p.mExtras != null) {
1018 PackageSetting ps = (PackageSetting)p.mExtras;
1019 if (ps.sharedUser != null) {
1020 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1021 return PackageManager.PERMISSION_GRANTED;
1022 }
1023 } else if (ps.grantedPermissions.contains(permName)) {
1024 return PackageManager.PERMISSION_GRANTED;
1025 }
1026 }
1027 }
1028 return PackageManager.PERMISSION_DENIED;
1029 }
1030
1031 public int checkUidPermission(String permName, int uid) {
1032 synchronized (mPackages) {
1033 Object obj = mSettings.getUserIdLP(uid);
1034 if (obj != null) {
1035 if (obj instanceof SharedUserSetting) {
1036 SharedUserSetting sus = (SharedUserSetting)obj;
1037 if (sus.grantedPermissions.contains(permName)) {
1038 return PackageManager.PERMISSION_GRANTED;
1039 }
1040 } else if (obj instanceof PackageSetting) {
1041 PackageSetting ps = (PackageSetting)obj;
1042 if (ps.grantedPermissions.contains(permName)) {
1043 return PackageManager.PERMISSION_GRANTED;
1044 }
1045 }
1046 } else {
1047 HashSet<String> perms = mSystemPermissions.get(uid);
1048 if (perms != null && perms.contains(permName)) {
1049 return PackageManager.PERMISSION_GRANTED;
1050 }
1051 }
1052 }
1053 return PackageManager.PERMISSION_DENIED;
1054 }
1055
1056 private BasePermission findPermissionTreeLP(String permName) {
1057 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1058 if (permName.startsWith(bp.name) &&
1059 permName.length() > bp.name.length() &&
1060 permName.charAt(bp.name.length()) == '.') {
1061 return bp;
1062 }
1063 }
1064 return null;
1065 }
1066
1067 private BasePermission checkPermissionTreeLP(String permName) {
1068 if (permName != null) {
1069 BasePermission bp = findPermissionTreeLP(permName);
1070 if (bp != null) {
1071 if (bp.uid == Binder.getCallingUid()) {
1072 return bp;
1073 }
1074 throw new SecurityException("Calling uid "
1075 + Binder.getCallingUid()
1076 + " is not allowed to add to permission tree "
1077 + bp.name + " owned by uid " + bp.uid);
1078 }
1079 }
1080 throw new SecurityException("No permission tree found for " + permName);
1081 }
1082
1083 public boolean addPermission(PermissionInfo info) {
1084 synchronized (mPackages) {
1085 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1086 throw new SecurityException("Label must be specified in permission");
1087 }
1088 BasePermission tree = checkPermissionTreeLP(info.name);
1089 BasePermission bp = mSettings.mPermissions.get(info.name);
1090 boolean added = bp == null;
1091 if (added) {
1092 bp = new BasePermission(info.name, tree.sourcePackage,
1093 BasePermission.TYPE_DYNAMIC);
1094 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1095 throw new SecurityException(
1096 "Not allowed to modify non-dynamic permission "
1097 + info.name);
1098 }
1099 bp.perm = new PackageParser.Permission(tree.perm.owner,
1100 new PermissionInfo(info));
1101 bp.perm.info.packageName = tree.perm.info.packageName;
1102 bp.uid = tree.uid;
1103 if (added) {
1104 mSettings.mPermissions.put(info.name, bp);
1105 }
1106 mSettings.writeLP();
1107 return added;
1108 }
1109 }
1110
1111 public void removePermission(String name) {
1112 synchronized (mPackages) {
1113 checkPermissionTreeLP(name);
1114 BasePermission bp = mSettings.mPermissions.get(name);
1115 if (bp != null) {
1116 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1117 throw new SecurityException(
1118 "Not allowed to modify non-dynamic permission "
1119 + name);
1120 }
1121 mSettings.mPermissions.remove(name);
1122 mSettings.writeLP();
1123 }
1124 }
1125 }
1126
Dianne Hackborn854060af2009-07-09 18:14:31 -07001127 public boolean isProtectedBroadcast(String actionName) {
1128 synchronized (mPackages) {
1129 return mProtectedBroadcasts.contains(actionName);
1130 }
1131 }
1132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 public int checkSignatures(String pkg1, String pkg2) {
1134 synchronized (mPackages) {
1135 PackageParser.Package p1 = mPackages.get(pkg1);
1136 PackageParser.Package p2 = mPackages.get(pkg2);
1137 if (p1 == null || p1.mExtras == null
1138 || p2 == null || p2.mExtras == null) {
1139 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1140 }
1141 return checkSignaturesLP(p1, p2);
1142 }
1143 }
1144
1145 int checkSignaturesLP(PackageParser.Package p1, PackageParser.Package p2) {
1146 if (p1.mSignatures == null) {
1147 return p2.mSignatures == null
1148 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1149 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1150 }
1151 if (p2.mSignatures == null) {
1152 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1153 }
1154 final int N1 = p1.mSignatures.length;
1155 final int N2 = p2.mSignatures.length;
1156 for (int i=0; i<N1; i++) {
1157 boolean match = false;
1158 for (int j=0; j<N2; j++) {
1159 if (p1.mSignatures[i].equals(p2.mSignatures[j])) {
1160 match = true;
1161 break;
1162 }
1163 }
1164 if (!match) {
1165 return PackageManager.SIGNATURE_NO_MATCH;
1166 }
1167 }
1168 return PackageManager.SIGNATURE_MATCH;
1169 }
1170
1171 public String[] getPackagesForUid(int uid) {
1172 synchronized (mPackages) {
1173 Object obj = mSettings.getUserIdLP(uid);
1174 if (obj instanceof SharedUserSetting) {
1175 SharedUserSetting sus = (SharedUserSetting)obj;
1176 final int N = sus.packages.size();
1177 String[] res = new String[N];
1178 Iterator<PackageSetting> it = sus.packages.iterator();
1179 int i=0;
1180 while (it.hasNext()) {
1181 res[i++] = it.next().name;
1182 }
1183 return res;
1184 } else if (obj instanceof PackageSetting) {
1185 PackageSetting ps = (PackageSetting)obj;
1186 return new String[] { ps.name };
1187 }
1188 }
1189 return null;
1190 }
1191
1192 public String getNameForUid(int uid) {
1193 synchronized (mPackages) {
1194 Object obj = mSettings.getUserIdLP(uid);
1195 if (obj instanceof SharedUserSetting) {
1196 SharedUserSetting sus = (SharedUserSetting)obj;
1197 return sus.name + ":" + sus.userId;
1198 } else if (obj instanceof PackageSetting) {
1199 PackageSetting ps = (PackageSetting)obj;
1200 return ps.name;
1201 }
1202 }
1203 return null;
1204 }
1205
1206 public int getUidForSharedUser(String sharedUserName) {
1207 if(sharedUserName == null) {
1208 return -1;
1209 }
1210 synchronized (mPackages) {
1211 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1212 if(suid == null) {
1213 return -1;
1214 }
1215 return suid.userId;
1216 }
1217 }
1218
1219 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1220 int flags) {
1221 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001222 return chooseBestActivity(intent, resolvedType, flags, query);
1223 }
1224
Mihai Predaeae850c2009-05-13 10:13:48 +02001225 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1226 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 if (query != null) {
1228 final int N = query.size();
1229 if (N == 1) {
1230 return query.get(0);
1231 } else if (N > 1) {
1232 // If there is more than one activity with the same priority,
1233 // then let the user decide between them.
1234 ResolveInfo r0 = query.get(0);
1235 ResolveInfo r1 = query.get(1);
1236 if (false) {
1237 System.out.println(r0.activityInfo.name +
1238 "=" + r0.priority + " vs " +
1239 r1.activityInfo.name +
1240 "=" + r1.priority);
1241 }
1242 // If the first activity has a higher priority, or a different
1243 // default, then it is always desireable to pick it.
1244 if (r0.priority != r1.priority
1245 || r0.preferredOrder != r1.preferredOrder
1246 || r0.isDefault != r1.isDefault) {
1247 return query.get(0);
1248 }
1249 // If we have saved a preference for a preferred activity for
1250 // this Intent, use that.
1251 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1252 flags, query, r0.priority);
1253 if (ri != null) {
1254 return ri;
1255 }
1256 return mResolveInfo;
1257 }
1258 }
1259 return null;
1260 }
1261
1262 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1263 int flags, List<ResolveInfo> query, int priority) {
1264 synchronized (mPackages) {
1265 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1266 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001267 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1269 if (prefs != null && prefs.size() > 0) {
1270 // First figure out how good the original match set is.
1271 // We will only allow preferred activities that came
1272 // from the same match quality.
1273 int match = 0;
1274 final int N = query.size();
1275 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1276 for (int j=0; j<N; j++) {
1277 ResolveInfo ri = query.get(j);
1278 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1279 + ": 0x" + Integer.toHexString(match));
1280 if (ri.match > match) match = ri.match;
1281 }
1282 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1283 + Integer.toHexString(match));
1284 match &= IntentFilter.MATCH_CATEGORY_MASK;
1285 final int M = prefs.size();
1286 for (int i=0; i<M; i++) {
1287 PreferredActivity pa = prefs.get(i);
1288 if (pa.mMatch != match) {
1289 continue;
1290 }
1291 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1292 if (DEBUG_PREFERRED) {
1293 Log.v(TAG, "Got preferred activity:");
1294 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1295 }
1296 if (ai != null) {
1297 for (int j=0; j<N; j++) {
1298 ResolveInfo ri = query.get(j);
1299 if (!ri.activityInfo.applicationInfo.packageName
1300 .equals(ai.applicationInfo.packageName)) {
1301 continue;
1302 }
1303 if (!ri.activityInfo.name.equals(ai.name)) {
1304 continue;
1305 }
1306
1307 // Okay we found a previously set preferred app.
1308 // If the result set is different from when this
1309 // was created, we need to clear it and re-ask the
1310 // user their preference.
1311 if (!pa.sameSet(query, priority)) {
1312 Log.i(TAG, "Result set changed, dropping preferred activity for "
1313 + intent + " type " + resolvedType);
1314 mSettings.mPreferredActivities.removeFilter(pa);
1315 return null;
1316 }
1317
1318 // Yay!
1319 return ri;
1320 }
1321 }
1322 }
1323 }
1324 }
1325 return null;
1326 }
1327
1328 public List<ResolveInfo> queryIntentActivities(Intent intent,
1329 String resolvedType, int flags) {
1330 ComponentName comp = intent.getComponent();
1331 if (comp != null) {
1332 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1333 ActivityInfo ai = getActivityInfo(comp, flags);
1334 if (ai != null) {
1335 ResolveInfo ri = new ResolveInfo();
1336 ri.activityInfo = ai;
1337 list.add(ri);
1338 }
1339 return list;
1340 }
1341
1342 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001343 String pkgName = intent.getPackage();
1344 if (pkgName == null) {
1345 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1346 resolvedType, flags);
1347 }
1348 PackageParser.Package pkg = mPackages.get(pkgName);
1349 if (pkg != null) {
1350 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1351 resolvedType, flags, pkg.activities);
1352 }
1353 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 }
1355 }
1356
1357 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1358 Intent[] specifics, String[] specificTypes, Intent intent,
1359 String resolvedType, int flags) {
1360 final String resultsAction = intent.getAction();
1361
1362 List<ResolveInfo> results = queryIntentActivities(
1363 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1364 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1365
1366 int specificsPos = 0;
1367 int N;
1368
1369 // todo: note that the algorithm used here is O(N^2). This
1370 // isn't a problem in our current environment, but if we start running
1371 // into situations where we have more than 5 or 10 matches then this
1372 // should probably be changed to something smarter...
1373
1374 // First we go through and resolve each of the specific items
1375 // that were supplied, taking care of removing any corresponding
1376 // duplicate items in the generic resolve list.
1377 if (specifics != null) {
1378 for (int i=0; i<specifics.length; i++) {
1379 final Intent sintent = specifics[i];
1380 if (sintent == null) {
1381 continue;
1382 }
1383
1384 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1385 String action = sintent.getAction();
1386 if (resultsAction != null && resultsAction.equals(action)) {
1387 // If this action was explicitly requested, then don't
1388 // remove things that have it.
1389 action = null;
1390 }
1391 ComponentName comp = sintent.getComponent();
1392 ResolveInfo ri = null;
1393 ActivityInfo ai = null;
1394 if (comp == null) {
1395 ri = resolveIntent(
1396 sintent,
1397 specificTypes != null ? specificTypes[i] : null,
1398 flags);
1399 if (ri == null) {
1400 continue;
1401 }
1402 if (ri == mResolveInfo) {
1403 // ACK! Must do something better with this.
1404 }
1405 ai = ri.activityInfo;
1406 comp = new ComponentName(ai.applicationInfo.packageName,
1407 ai.name);
1408 } else {
1409 ai = getActivityInfo(comp, flags);
1410 if (ai == null) {
1411 continue;
1412 }
1413 }
1414
1415 // Look for any generic query activities that are duplicates
1416 // of this specific one, and remove them from the results.
1417 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1418 N = results.size();
1419 int j;
1420 for (j=specificsPos; j<N; j++) {
1421 ResolveInfo sri = results.get(j);
1422 if ((sri.activityInfo.name.equals(comp.getClassName())
1423 && sri.activityInfo.applicationInfo.packageName.equals(
1424 comp.getPackageName()))
1425 || (action != null && sri.filter.matchAction(action))) {
1426 results.remove(j);
1427 if (Config.LOGV) Log.v(
1428 TAG, "Removing duplicate item from " + j
1429 + " due to specific " + specificsPos);
1430 if (ri == null) {
1431 ri = sri;
1432 }
1433 j--;
1434 N--;
1435 }
1436 }
1437
1438 // Add this specific item to its proper place.
1439 if (ri == null) {
1440 ri = new ResolveInfo();
1441 ri.activityInfo = ai;
1442 }
1443 results.add(specificsPos, ri);
1444 ri.specificIndex = i;
1445 specificsPos++;
1446 }
1447 }
1448
1449 // Now we go through the remaining generic results and remove any
1450 // duplicate actions that are found here.
1451 N = results.size();
1452 for (int i=specificsPos; i<N-1; i++) {
1453 final ResolveInfo rii = results.get(i);
1454 if (rii.filter == null) {
1455 continue;
1456 }
1457
1458 // Iterate over all of the actions of this result's intent
1459 // filter... typically this should be just one.
1460 final Iterator<String> it = rii.filter.actionsIterator();
1461 if (it == null) {
1462 continue;
1463 }
1464 while (it.hasNext()) {
1465 final String action = it.next();
1466 if (resultsAction != null && resultsAction.equals(action)) {
1467 // If this action was explicitly requested, then don't
1468 // remove things that have it.
1469 continue;
1470 }
1471 for (int j=i+1; j<N; j++) {
1472 final ResolveInfo rij = results.get(j);
1473 if (rij.filter != null && rij.filter.hasAction(action)) {
1474 results.remove(j);
1475 if (Config.LOGV) Log.v(
1476 TAG, "Removing duplicate item from " + j
1477 + " due to action " + action + " at " + i);
1478 j--;
1479 N--;
1480 }
1481 }
1482 }
1483
1484 // If the caller didn't request filter information, drop it now
1485 // so we don't have to marshall/unmarshall it.
1486 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1487 rii.filter = null;
1488 }
1489 }
1490
1491 // Filter out the caller activity if so requested.
1492 if (caller != null) {
1493 N = results.size();
1494 for (int i=0; i<N; i++) {
1495 ActivityInfo ainfo = results.get(i).activityInfo;
1496 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1497 && caller.getClassName().equals(ainfo.name)) {
1498 results.remove(i);
1499 break;
1500 }
1501 }
1502 }
1503
1504 // If the caller didn't request filter information,
1505 // drop them now so we don't have to
1506 // marshall/unmarshall it.
1507 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1508 N = results.size();
1509 for (int i=0; i<N; i++) {
1510 results.get(i).filter = null;
1511 }
1512 }
1513
1514 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1515 return results;
1516 }
1517
1518 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1519 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001520 ComponentName comp = intent.getComponent();
1521 if (comp != null) {
1522 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1523 ActivityInfo ai = getReceiverInfo(comp, flags);
1524 if (ai != null) {
1525 ResolveInfo ri = new ResolveInfo();
1526 ri.activityInfo = ai;
1527 list.add(ri);
1528 }
1529 return list;
1530 }
1531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001533 String pkgName = intent.getPackage();
1534 if (pkgName == null) {
1535 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1536 resolvedType, flags);
1537 }
1538 PackageParser.Package pkg = mPackages.get(pkgName);
1539 if (pkg != null) {
1540 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1541 resolvedType, flags, pkg.receivers);
1542 }
1543 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545 }
1546
1547 public ResolveInfo resolveService(Intent intent, String resolvedType,
1548 int flags) {
1549 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1550 flags);
1551 if (query != null) {
1552 if (query.size() >= 1) {
1553 // If there is more than one service with the same priority,
1554 // just arbitrarily pick the first one.
1555 return query.get(0);
1556 }
1557 }
1558 return null;
1559 }
1560
1561 public List<ResolveInfo> queryIntentServices(Intent intent,
1562 String resolvedType, int flags) {
1563 ComponentName comp = intent.getComponent();
1564 if (comp != null) {
1565 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1566 ServiceInfo si = getServiceInfo(comp, flags);
1567 if (si != null) {
1568 ResolveInfo ri = new ResolveInfo();
1569 ri.serviceInfo = si;
1570 list.add(ri);
1571 }
1572 return list;
1573 }
1574
1575 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001576 String pkgName = intent.getPackage();
1577 if (pkgName == null) {
1578 return (List<ResolveInfo>)mServices.queryIntent(intent,
1579 resolvedType, flags);
1580 }
1581 PackageParser.Package pkg = mPackages.get(pkgName);
1582 if (pkg != null) {
1583 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1584 resolvedType, flags, pkg.services);
1585 }
1586 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 }
1588 }
1589
1590 public List<PackageInfo> getInstalledPackages(int flags) {
1591 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1592
1593 synchronized (mPackages) {
1594 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1595 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1596 while (i.hasNext()) {
1597 final PackageSetting ps = i.next();
1598 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1599 if(psPkg != null) {
1600 finalList.add(psPkg);
1601 }
1602 }
1603 }
1604 else {
1605 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1606 while (i.hasNext()) {
1607 final PackageParser.Package p = i.next();
1608 if (p.applicationInfo != null) {
1609 PackageInfo pi = generatePackageInfo(p, flags);
1610 if(pi != null) {
1611 finalList.add(pi);
1612 }
1613 }
1614 }
1615 }
1616 }
1617 return finalList;
1618 }
1619
1620 public List<ApplicationInfo> getInstalledApplications(int flags) {
1621 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1622 synchronized(mPackages) {
1623 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1624 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1625 while (i.hasNext()) {
1626 final PackageSetting ps = i.next();
1627 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1628 if(ai != null) {
1629 finalList.add(ai);
1630 }
1631 }
1632 }
1633 else {
1634 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1635 while (i.hasNext()) {
1636 final PackageParser.Package p = i.next();
1637 if (p.applicationInfo != null) {
1638 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1639 if(ai != null) {
1640 finalList.add(ai);
1641 }
1642 }
1643 }
1644 }
1645 }
1646 return finalList;
1647 }
1648
1649 public List<ApplicationInfo> getPersistentApplications(int flags) {
1650 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1651
1652 synchronized (mPackages) {
1653 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1654 while (i.hasNext()) {
1655 PackageParser.Package p = i.next();
1656 if (p.applicationInfo != null
1657 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
1658 && (!mSafeMode || (p.applicationInfo.flags
1659 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1660 finalList.add(p.applicationInfo);
1661 }
1662 }
1663 }
1664
1665 return finalList;
1666 }
1667
1668 public ProviderInfo resolveContentProvider(String name, int flags) {
1669 synchronized (mPackages) {
1670 final PackageParser.Provider provider = mProviders.get(name);
1671 return provider != null
1672 && mSettings.isEnabledLP(provider.info, flags)
1673 && (!mSafeMode || (provider.info.applicationInfo.flags
1674 &ApplicationInfo.FLAG_SYSTEM) != 0)
1675 ? PackageParser.generateProviderInfo(provider, flags)
1676 : null;
1677 }
1678 }
1679
Fred Quintana718d8a22009-04-29 17:53:20 -07001680 /**
1681 * @deprecated
1682 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 public void querySyncProviders(List outNames, List outInfo) {
1684 synchronized (mPackages) {
1685 Iterator<Map.Entry<String, PackageParser.Provider>> i
1686 = mProviders.entrySet().iterator();
1687
1688 while (i.hasNext()) {
1689 Map.Entry<String, PackageParser.Provider> entry = i.next();
1690 PackageParser.Provider p = entry.getValue();
1691
1692 if (p.syncable
1693 && (!mSafeMode || (p.info.applicationInfo.flags
1694 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1695 outNames.add(entry.getKey());
1696 outInfo.add(PackageParser.generateProviderInfo(p, 0));
1697 }
1698 }
1699 }
1700 }
1701
1702 public List<ProviderInfo> queryContentProviders(String processName,
1703 int uid, int flags) {
1704 ArrayList<ProviderInfo> finalList = null;
1705
1706 synchronized (mPackages) {
1707 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
1708 while (i.hasNext()) {
1709 PackageParser.Provider p = i.next();
1710 if (p.info.authority != null
1711 && (processName == null ||
1712 (p.info.processName.equals(processName)
1713 && p.info.applicationInfo.uid == uid))
1714 && mSettings.isEnabledLP(p.info, flags)
1715 && (!mSafeMode || (p.info.applicationInfo.flags
1716 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1717 if (finalList == null) {
1718 finalList = new ArrayList<ProviderInfo>(3);
1719 }
1720 finalList.add(PackageParser.generateProviderInfo(p,
1721 flags));
1722 }
1723 }
1724 }
1725
1726 if (finalList != null) {
1727 Collections.sort(finalList, mProviderInitOrderSorter);
1728 }
1729
1730 return finalList;
1731 }
1732
1733 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
1734 int flags) {
1735 synchronized (mPackages) {
1736 final PackageParser.Instrumentation i = mInstrumentation.get(name);
1737 return PackageParser.generateInstrumentationInfo(i, flags);
1738 }
1739 }
1740
1741 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
1742 int flags) {
1743 ArrayList<InstrumentationInfo> finalList =
1744 new ArrayList<InstrumentationInfo>();
1745
1746 synchronized (mPackages) {
1747 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
1748 while (i.hasNext()) {
1749 PackageParser.Instrumentation p = i.next();
1750 if (targetPackage == null
1751 || targetPackage.equals(p.info.targetPackage)) {
1752 finalList.add(PackageParser.generateInstrumentationInfo(p,
1753 flags));
1754 }
1755 }
1756 }
1757
1758 return finalList;
1759 }
1760
1761 private void scanDirLI(File dir, int flags, int scanMode) {
1762 Log.d(TAG, "Scanning app dir " + dir);
1763
1764 String[] files = dir.list();
1765
1766 int i;
1767 for (i=0; i<files.length; i++) {
1768 File file = new File(dir, files[i]);
1769 PackageParser.Package pkg = scanPackageLI(file, file, file,
1770 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
1771 }
1772 }
1773
1774 private static void reportSettingsProblem(int priority, String msg) {
1775 try {
1776 File dataDir = Environment.getDataDirectory();
1777 File systemDir = new File(dataDir, "system");
1778 File fname = new File(systemDir, "uiderrors.txt");
1779 FileOutputStream out = new FileOutputStream(fname, true);
1780 PrintWriter pw = new PrintWriter(out);
1781 pw.println(msg);
1782 pw.close();
1783 FileUtils.setPermissions(
1784 fname.toString(),
1785 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
1786 -1, -1);
1787 } catch (java.io.IOException e) {
1788 }
1789 Log.println(priority, TAG, msg);
1790 }
1791
1792 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
1793 PackageParser.Package pkg, File srcFile, int parseFlags) {
1794 if (GET_CERTIFICATES) {
1795 if (ps == null || !ps.codePath.equals(srcFile)
1796 || ps.getTimeStamp() != srcFile.lastModified()) {
1797 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
1798 if (!pp.collectCertificates(pkg, parseFlags)) {
1799 mLastScanError = pp.getParseError();
1800 return false;
1801 }
1802 }
1803 }
1804 return true;
1805 }
1806
1807 /*
1808 * Scan a package and return the newly parsed package.
1809 * Returns null in case of errors and the error code is stored in mLastScanError
1810 */
1811 private PackageParser.Package scanPackageLI(File scanFile,
1812 File destCodeFile, File destResourceFile, int parseFlags,
1813 int scanMode) {
1814 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
1815 parseFlags |= mDefParseFlags;
1816 PackageParser pp = new PackageParser(scanFile.getPath());
1817 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackborn851a5412009-05-08 12:06:44 -07001818 pp.setSdkVersion(mSdkVersion, mSdkCodename);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 final PackageParser.Package pkg = pp.parsePackage(scanFile,
1820 destCodeFile.getAbsolutePath(), mMetrics, parseFlags);
1821 if (pkg == null) {
1822 mLastScanError = pp.getParseError();
1823 return null;
1824 }
1825 PackageSetting ps;
1826 PackageSetting updatedPkg;
1827 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07001828 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
1830 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07001831 // Verify certificates first
1832 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
1833 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
1834 return null;
1835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 if (updatedPkg != null) {
1837 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
1838 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
1839 }
1840 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
1841 // Check for updated system applications here
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07001842 if (updatedPkg != null) {
1843 if ((ps != null) && (!ps.codePath.getPath().equals(scanFile.getPath()))) {
1844 if (pkg.mVersionCode <= ps.versionCode) {
1845 // The system package has been updated and the code path does not match
1846 // Ignore entry. Just return
1847 Log.w(TAG, "Package:" + pkg.packageName +
1848 " has been updated. Ignoring the one from path:"+scanFile);
1849 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
1850 return null;
1851 } else {
1852 // Delete the older apk pointed to by ps
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07001853 // At this point, its safely assumed that package installation for
1854 // apps in system partition will go through. If not there won't be a working
1855 // version of the app
1856 synchronized (mPackages) {
1857 // Just remove the loaded entries from package lists.
1858 mPackages.remove(ps.name);
1859 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07001860 deletePackageResourcesLI(ps.name, ps.codePathString, ps.resourcePathString);
1861 mSettings.enableSystemPackageLP(ps.name);
1862 }
1863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 }
1865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 // The apk is forward locked (not public) if its code and resources
1867 // are kept in different files.
1868 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
1869 scanMode |= SCAN_FORWARD_LOCKED;
1870 }
1871 // Note that we invoke the following method only if we are about to unpack an application
1872 return scanPackageLI(scanFile, destCodeFile, destResourceFile,
1873 pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
1874 }
1875
1876 private static String fixProcessName(String defProcessName,
1877 String processName, int uid) {
1878 if (processName == null) {
1879 return defProcessName;
1880 }
1881 return processName;
1882 }
1883
1884 private boolean verifySignaturesLP(PackageSetting pkgSetting,
1885 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
1886 if (pkg.mSignatures != null) {
1887 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
1888 updateSignature)) {
1889 Log.e(TAG, "Package " + pkg.packageName
1890 + " signatures do not match the previously installed version; ignoring!");
1891 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
1892 return false;
1893 }
1894
1895 if (pkgSetting.sharedUser != null) {
1896 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
1897 pkg.mSignatures, updateSignature)) {
1898 Log.e(TAG, "Package " + pkg.packageName
1899 + " has no signatures that match those in shared user "
1900 + pkgSetting.sharedUser.name + "; ignoring!");
1901 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
1902 return false;
1903 }
1904 }
1905 } else {
1906 pkg.mSignatures = pkgSetting.signatures.mSignatures;
1907 }
1908 return true;
1909 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001910
1911 public boolean performDexOpt(String packageName) {
1912 if (!mNoDexOpt) {
1913 return false;
1914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001916 PackageParser.Package p;
1917 synchronized (mPackages) {
1918 p = mPackages.get(packageName);
1919 if (p == null || p.mDidDexOpt) {
1920 return false;
1921 }
1922 }
1923 synchronized (mInstallLock) {
1924 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
1925 }
1926 }
1927
1928 static final int DEX_OPT_SKIPPED = 0;
1929 static final int DEX_OPT_PERFORMED = 1;
1930 static final int DEX_OPT_FAILED = -1;
1931
1932 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
1933 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07001934 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001935 String path = pkg.mScanPath;
1936 int ret = 0;
1937 try {
1938 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
1939 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
1940 !pkg.mForwardLocked);
1941 pkg.mDidDexOpt = true;
1942 performed = true;
1943 }
1944 } catch (FileNotFoundException e) {
1945 Log.w(TAG, "Apk not found for dexopt: " + path);
1946 ret = -1;
1947 } catch (IOException e) {
1948 Log.w(TAG, "Exception reading apk: " + path, e);
1949 ret = -1;
1950 }
1951 if (ret < 0) {
1952 //error from installer
1953 return DEX_OPT_FAILED;
1954 }
1955 }
1956
1957 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
1958 }
1959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 private PackageParser.Package scanPackageLI(
1961 File scanFile, File destCodeFile, File destResourceFile,
1962 PackageParser.Package pkg, int parseFlags, int scanMode) {
1963
1964 mScanningPath = scanFile;
1965 if (pkg == null) {
1966 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
1967 return null;
1968 }
1969
1970 final String pkgName = pkg.applicationInfo.packageName;
1971 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
1972 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
1973 }
1974
1975 if (pkgName.equals("android")) {
1976 synchronized (mPackages) {
1977 if (mAndroidApplication != null) {
1978 Log.w(TAG, "*************************************************");
1979 Log.w(TAG, "Core android package being redefined. Skipping.");
1980 Log.w(TAG, " file=" + mScanningPath);
1981 Log.w(TAG, "*************************************************");
1982 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
1983 return null;
1984 }
1985
1986 // Set up information for our fall-back user intent resolution
1987 // activity.
1988 mPlatformPackage = pkg;
1989 pkg.mVersionCode = mSdkVersion;
1990 mAndroidApplication = pkg.applicationInfo;
1991 mResolveActivity.applicationInfo = mAndroidApplication;
1992 mResolveActivity.name = ResolverActivity.class.getName();
1993 mResolveActivity.packageName = mAndroidApplication.packageName;
1994 mResolveActivity.processName = mAndroidApplication.processName;
1995 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
1996 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1997 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
1998 mResolveActivity.exported = true;
1999 mResolveActivity.enabled = true;
2000 mResolveInfo.activityInfo = mResolveActivity;
2001 mResolveInfo.priority = 0;
2002 mResolveInfo.preferredOrder = 0;
2003 mResolveInfo.match = 0;
2004 mResolveComponentName = new ComponentName(
2005 mAndroidApplication.packageName, mResolveActivity.name);
2006 }
2007 }
2008
2009 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
2010 TAG, "Scanning package " + pkgName);
2011 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
2012 Log.w(TAG, "*************************************************");
2013 Log.w(TAG, "Application package " + pkgName
2014 + " already installed. Skipping duplicate.");
2015 Log.w(TAG, "*************************************************");
2016 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2017 return null;
2018 }
2019
2020 SharedUserSetting suid = null;
2021 PackageSetting pkgSetting = null;
2022
2023 boolean removeExisting = false;
2024
2025 synchronized (mPackages) {
2026 // Check all shared libraries and map to their actual file path.
2027 if (pkg.usesLibraryFiles != null) {
2028 for (int i=0; i<pkg.usesLibraryFiles.length; i++) {
2029 String file = mSharedLibraries.get(pkg.usesLibraryFiles[i]);
2030 if (file == null) {
2031 Log.e(TAG, "Package " + pkg.packageName
2032 + " requires unavailable shared library "
2033 + pkg.usesLibraryFiles[i] + "; ignoring!");
2034 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2035 return null;
2036 }
2037 pkg.usesLibraryFiles[i] = file;
2038 }
2039 }
2040
2041 if (pkg.mSharedUserId != null) {
2042 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2043 pkg.applicationInfo.flags, true);
2044 if (suid == null) {
2045 Log.w(TAG, "Creating application package " + pkgName
2046 + " for shared user failed");
2047 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2048 return null;
2049 }
2050 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2051 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2052 + suid.userId + "): packages=" + suid.packages);
2053 }
2054 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002055
2056 // Just create the setting, don't add it yet. For already existing packages
2057 // the PkgSetting exists already and doesn't have to be created.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile,
2059 destResourceFile, pkg.applicationInfo.flags, true, false);
2060 if (pkgSetting == null) {
2061 Log.w(TAG, "Creating application package " + pkgName + " failed");
2062 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2063 return null;
2064 }
2065 if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
2066 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2067 }
2068
2069 pkg.applicationInfo.uid = pkgSetting.userId;
2070 pkg.mExtras = pkgSetting;
2071
2072 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
2073 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2074 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2075 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2076 return null;
2077 }
2078 // The signature has changed, but this package is in the system
2079 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002080 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 // However... if this package is part of a shared user, but it
2082 // doesn't match the signature of the shared user, let's fail.
2083 // What this means is that you can't change the signatures
2084 // associated with an overall shared user, which doesn't seem all
2085 // that unreasonable.
2086 if (pkgSetting.sharedUser != null) {
2087 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2088 pkg.mSignatures, false)) {
2089 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2090 return null;
2091 }
2092 }
2093 removeExisting = true;
2094 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002095
2096 // Verify that this new package doesn't have any content providers
2097 // that conflict with existing packages. Only do this if the
2098 // package isn't already installed, since we don't want to break
2099 // things that are installed.
2100 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2101 int N = pkg.providers.size();
2102 int i;
2103 for (i=0; i<N; i++) {
2104 PackageParser.Provider p = pkg.providers.get(i);
2105 String names[] = p.info.authority.split(";");
2106 for (int j = 0; j < names.length; j++) {
2107 if (mProviders.containsKey(names[j])) {
2108 PackageParser.Provider other = mProviders.get(names[j]);
2109 Log.w(TAG, "Can't install because provider name " + names[j] +
2110 " (in package " + pkg.applicationInfo.packageName +
2111 ") is already used by "
2112 + ((other != null && other.component != null)
2113 ? other.component.getPackageName() : "?"));
2114 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2115 return null;
2116 }
2117 }
2118 }
2119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 }
2121
2122 if (removeExisting) {
2123 if (mInstaller != null) {
2124 int ret = mInstaller.remove(pkgName);
2125 if (ret != 0) {
2126 String msg = "System package " + pkg.packageName
2127 + " could not have data directory erased after signature change.";
2128 reportSettingsProblem(Log.WARN, msg);
2129 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2130 return null;
2131 }
2132 }
2133 Log.w(TAG, "System package " + pkg.packageName
2134 + " signature changed: existing data removed.");
2135 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2136 }
2137
2138 long scanFileTime = scanFile.lastModified();
2139 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2140 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2141 pkg.applicationInfo.processName = fixProcessName(
2142 pkg.applicationInfo.packageName,
2143 pkg.applicationInfo.processName,
2144 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002145 pkg.applicationInfo.publicSourceDir = destResourceFile.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146
2147 File dataPath;
2148 if (mPlatformPackage == pkg) {
2149 // The system package is special.
2150 dataPath = new File (Environment.getDataDirectory(), "system");
2151 pkg.applicationInfo.dataDir = dataPath.getPath();
2152 } else {
2153 // This is a normal package, need to make its data directory.
2154 dataPath = new File(mAppDataDir, pkgName);
2155 if (dataPath.exists()) {
2156 mOutPermissions[1] = 0;
2157 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2158 if (mOutPermissions[1] == pkg.applicationInfo.uid
2159 || !Process.supportsProcesses()) {
2160 pkg.applicationInfo.dataDir = dataPath.getPath();
2161 } else {
2162 boolean recovered = false;
2163 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2164 // If this is a system app, we can at least delete its
2165 // current data so the application will still work.
2166 if (mInstaller != null) {
2167 int ret = mInstaller.remove(pkgName);
2168 if(ret >= 0) {
2169 // Old data gone!
2170 String msg = "System package " + pkg.packageName
2171 + " has changed from uid: "
2172 + mOutPermissions[1] + " to "
2173 + pkg.applicationInfo.uid + "; old data erased";
2174 reportSettingsProblem(Log.WARN, msg);
2175 recovered = true;
2176
2177 // And now re-install the app.
2178 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2179 pkg.applicationInfo.uid);
2180 if (ret == -1) {
2181 // Ack should not happen!
2182 msg = "System package " + pkg.packageName
2183 + " could not have data directory re-created after delete.";
2184 reportSettingsProblem(Log.WARN, msg);
2185 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2186 return null;
2187 }
2188 }
2189 }
2190 if (!recovered) {
2191 mHasSystemUidErrors = true;
2192 }
2193 }
2194 if (!recovered) {
2195 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2196 + pkg.applicationInfo.uid + "/fs_"
2197 + mOutPermissions[1];
2198 String msg = "Package " + pkg.packageName
2199 + " has mismatched uid: "
2200 + mOutPermissions[1] + " on disk, "
2201 + pkg.applicationInfo.uid + " in settings";
2202 synchronized (mPackages) {
2203 if (!mReportedUidError) {
2204 mReportedUidError = true;
2205 msg = msg + "; read messages:\n"
2206 + mSettings.getReadMessagesLP();
2207 }
2208 reportSettingsProblem(Log.ERROR, msg);
2209 }
2210 }
2211 }
2212 pkg.applicationInfo.dataDir = dataPath.getPath();
2213 } else {
2214 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2215 Log.v(TAG, "Want this data dir: " + dataPath);
2216 //invoke installer to do the actual installation
2217 if (mInstaller != null) {
2218 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2219 pkg.applicationInfo.uid);
2220 if(ret < 0) {
2221 // Error from installer
2222 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2223 return null;
2224 }
2225 } else {
2226 dataPath.mkdirs();
2227 if (dataPath.exists()) {
2228 FileUtils.setPermissions(
2229 dataPath.toString(),
2230 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2231 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2232 }
2233 }
2234 if (dataPath.exists()) {
2235 pkg.applicationInfo.dataDir = dataPath.getPath();
2236 } else {
2237 Log.w(TAG, "Unable to create data directory: " + dataPath);
2238 pkg.applicationInfo.dataDir = null;
2239 }
2240 }
2241 }
2242
2243 // Perform shared library installation and dex validation and
2244 // optimization, if this is not a system app.
2245 if (mInstaller != null) {
2246 String path = scanFile.getPath();
2247 if (scanFileNewer) {
2248 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002249 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2250 if (err != PackageManager.INSTALL_SUCCEEDED) {
2251 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 return null;
2253 }
2254 }
2255
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002256 pkg.mForwardLocked = (scanMode&SCAN_FORWARD_LOCKED) != 0;
2257 pkg.mScanPath = path;
2258
2259 if ((scanMode&SCAN_NO_DEX) == 0) {
2260 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2262 return null;
2263 }
2264 }
2265 }
2266
2267 if (mFactoryTest && pkg.requestedPermissions.contains(
2268 android.Manifest.permission.FACTORY_TEST)) {
2269 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2270 }
2271
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002272 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 if ((scanMode&SCAN_MONITOR) != 0) {
2274 pkg.mPath = destCodeFile.getAbsolutePath();
2275 mAppDirs.put(pkg.mPath, pkg);
2276 }
2277
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002278 // Request the ActivityManager to kill the process(only for existing packages)
2279 // so that we do not end up in a confused state while the user is still using the older
2280 // version of the application while the new one gets installed.
2281 IActivityManager am = ActivityManagerNative.getDefault();
2282 if ((am != null) && ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING ) != 0)) {
2283 try {
2284 am.killApplicationWithUid(pkg.applicationInfo.packageName,
2285 pkg.applicationInfo.uid);
2286 } catch (RemoteException e) {
2287 }
2288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 // Add the new setting to mSettings
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002291 mSettings.insertPackageSettingLP(pkgSetting, pkg, destCodeFile, destResourceFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002293 mPackages.put(pkg.applicationInfo.packageName, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 int N = pkg.providers.size();
2295 StringBuilder r = null;
2296 int i;
2297 for (i=0; i<N; i++) {
2298 PackageParser.Provider p = pkg.providers.get(i);
2299 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2300 p.info.processName, pkg.applicationInfo.uid);
2301 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2302 p.info.name), p);
2303 p.syncable = p.info.isSyncable;
2304 String names[] = p.info.authority.split(";");
2305 p.info.authority = null;
2306 for (int j = 0; j < names.length; j++) {
2307 if (j == 1 && p.syncable) {
2308 // We only want the first authority for a provider to possibly be
2309 // syncable, so if we already added this provider using a different
2310 // authority clear the syncable flag. We copy the provider before
2311 // changing it because the mProviders object contains a reference
2312 // to a provider that we don't want to change.
2313 // Only do this for the second authority since the resulting provider
2314 // object can be the same for all future authorities for this provider.
2315 p = new PackageParser.Provider(p);
2316 p.syncable = false;
2317 }
2318 if (!mProviders.containsKey(names[j])) {
2319 mProviders.put(names[j], p);
2320 if (p.info.authority == null) {
2321 p.info.authority = names[j];
2322 } else {
2323 p.info.authority = p.info.authority + ";" + names[j];
2324 }
2325 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2326 Log.d(TAG, "Registered content provider: " + names[j] +
2327 ", className = " + p.info.name +
2328 ", isSyncable = " + p.info.isSyncable);
2329 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002330 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002331 Log.w(TAG, "Skipping provider name " + names[j] +
2332 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002333 "): name already used by "
2334 + ((other != null && other.component != null)
2335 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 }
2337 }
2338 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2339 if (r == null) {
2340 r = new StringBuilder(256);
2341 } else {
2342 r.append(' ');
2343 }
2344 r.append(p.info.name);
2345 }
2346 }
2347 if (r != null) {
2348 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2349 }
2350
2351 N = pkg.services.size();
2352 r = null;
2353 for (i=0; i<N; i++) {
2354 PackageParser.Service s = pkg.services.get(i);
2355 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2356 s.info.processName, pkg.applicationInfo.uid);
2357 mServices.addService(s);
2358 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2359 if (r == null) {
2360 r = new StringBuilder(256);
2361 } else {
2362 r.append(' ');
2363 }
2364 r.append(s.info.name);
2365 }
2366 }
2367 if (r != null) {
2368 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2369 }
2370
2371 N = pkg.receivers.size();
2372 r = null;
2373 for (i=0; i<N; i++) {
2374 PackageParser.Activity a = pkg.receivers.get(i);
2375 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2376 a.info.processName, pkg.applicationInfo.uid);
2377 mReceivers.addActivity(a, "receiver");
2378 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2379 if (r == null) {
2380 r = new StringBuilder(256);
2381 } else {
2382 r.append(' ');
2383 }
2384 r.append(a.info.name);
2385 }
2386 }
2387 if (r != null) {
2388 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2389 }
2390
2391 N = pkg.activities.size();
2392 r = null;
2393 for (i=0; i<N; i++) {
2394 PackageParser.Activity a = pkg.activities.get(i);
2395 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2396 a.info.processName, pkg.applicationInfo.uid);
2397 mActivities.addActivity(a, "activity");
2398 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2399 if (r == null) {
2400 r = new StringBuilder(256);
2401 } else {
2402 r.append(' ');
2403 }
2404 r.append(a.info.name);
2405 }
2406 }
2407 if (r != null) {
2408 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2409 }
2410
2411 N = pkg.permissionGroups.size();
2412 r = null;
2413 for (i=0; i<N; i++) {
2414 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2415 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2416 if (cur == null) {
2417 mPermissionGroups.put(pg.info.name, pg);
2418 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2419 if (r == null) {
2420 r = new StringBuilder(256);
2421 } else {
2422 r.append(' ');
2423 }
2424 r.append(pg.info.name);
2425 }
2426 } else {
2427 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2428 + pg.info.packageName + " ignored: original from "
2429 + cur.info.packageName);
2430 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2431 if (r == null) {
2432 r = new StringBuilder(256);
2433 } else {
2434 r.append(' ');
2435 }
2436 r.append("DUP:");
2437 r.append(pg.info.name);
2438 }
2439 }
2440 }
2441 if (r != null) {
2442 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2443 }
2444
2445 N = pkg.permissions.size();
2446 r = null;
2447 for (i=0; i<N; i++) {
2448 PackageParser.Permission p = pkg.permissions.get(i);
2449 HashMap<String, BasePermission> permissionMap =
2450 p.tree ? mSettings.mPermissionTrees
2451 : mSettings.mPermissions;
2452 p.group = mPermissionGroups.get(p.info.group);
2453 if (p.info.group == null || p.group != null) {
2454 BasePermission bp = permissionMap.get(p.info.name);
2455 if (bp == null) {
2456 bp = new BasePermission(p.info.name, p.info.packageName,
2457 BasePermission.TYPE_NORMAL);
2458 permissionMap.put(p.info.name, bp);
2459 }
2460 if (bp.perm == null) {
2461 if (bp.sourcePackage == null
2462 || bp.sourcePackage.equals(p.info.packageName)) {
2463 BasePermission tree = findPermissionTreeLP(p.info.name);
2464 if (tree == null
2465 || tree.sourcePackage.equals(p.info.packageName)) {
2466 bp.perm = p;
2467 bp.uid = pkg.applicationInfo.uid;
2468 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2469 if (r == null) {
2470 r = new StringBuilder(256);
2471 } else {
2472 r.append(' ');
2473 }
2474 r.append(p.info.name);
2475 }
2476 } else {
2477 Log.w(TAG, "Permission " + p.info.name + " from package "
2478 + p.info.packageName + " ignored: base tree "
2479 + tree.name + " is from package "
2480 + tree.sourcePackage);
2481 }
2482 } else {
2483 Log.w(TAG, "Permission " + p.info.name + " from package "
2484 + p.info.packageName + " ignored: original from "
2485 + bp.sourcePackage);
2486 }
2487 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2488 if (r == null) {
2489 r = new StringBuilder(256);
2490 } else {
2491 r.append(' ');
2492 }
2493 r.append("DUP:");
2494 r.append(p.info.name);
2495 }
2496 } else {
2497 Log.w(TAG, "Permission " + p.info.name + " from package "
2498 + p.info.packageName + " ignored: no group "
2499 + p.group);
2500 }
2501 }
2502 if (r != null) {
2503 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2504 }
2505
2506 N = pkg.instrumentation.size();
2507 r = null;
2508 for (i=0; i<N; i++) {
2509 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2510 a.info.packageName = pkg.applicationInfo.packageName;
2511 a.info.sourceDir = pkg.applicationInfo.sourceDir;
2512 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
2513 a.info.dataDir = pkg.applicationInfo.dataDir;
2514 mInstrumentation.put(a.component, a);
2515 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2516 if (r == null) {
2517 r = new StringBuilder(256);
2518 } else {
2519 r.append(' ');
2520 }
2521 r.append(a.info.name);
2522 }
2523 }
2524 if (r != null) {
2525 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2526 }
2527
Dianne Hackborn854060af2009-07-09 18:14:31 -07002528 if (pkg.protectedBroadcasts != null) {
2529 N = pkg.protectedBroadcasts.size();
2530 for (i=0; i<N; i++) {
2531 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
2532 }
2533 }
2534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 pkgSetting.setTimeStamp(scanFileTime);
2536 }
2537
2538 return pkg;
2539 }
2540
Dianne Hackbornb1811182009-05-21 15:45:42 -07002541 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
2542 File dataPath, File scanFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002544 final String sharedLibraryABI = Build.CPU_ABI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 final String apkLibraryDirectory = "lib/" + sharedLibraryABI + "/";
2546 final String apkSharedLibraryPrefix = apkLibraryDirectory + "lib";
2547 final String sharedLibrarySuffix = ".so";
Dianne Hackbornb1811182009-05-21 15:45:42 -07002548 boolean hasNativeCode = false;
2549 boolean installedNativeCode = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 try {
2551 ZipFile zipFile = new ZipFile(scanFile);
2552 Enumeration<ZipEntry> entries =
2553 (Enumeration<ZipEntry>) zipFile.entries();
2554
2555 while (entries.hasMoreElements()) {
2556 ZipEntry entry = entries.nextElement();
2557 if (entry.isDirectory()) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07002558 if (!hasNativeCode && entry.getName().startsWith("lib")) {
2559 hasNativeCode = true;
2560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 continue;
2562 }
2563 String entryName = entry.getName();
Dianne Hackbornb1811182009-05-21 15:45:42 -07002564 if (entryName.startsWith("lib/")) {
2565 hasNativeCode = true;
2566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 if (! (entryName.startsWith(apkSharedLibraryPrefix)
2568 && entryName.endsWith(sharedLibrarySuffix))) {
2569 continue;
2570 }
2571 String libFileName = entryName.substring(
2572 apkLibraryDirectory.length());
2573 if (libFileName.contains("/")
2574 || (!FileUtils.isFilenameSafe(new File(libFileName)))) {
2575 continue;
2576 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07002577
2578 installedNativeCode = true;
2579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
2581 File.separator + libFileName;
2582 File sharedLibraryFile = new File(sharedLibraryFilePath);
2583 if (! sharedLibraryFile.exists() ||
2584 sharedLibraryFile.length() != entry.getSize() ||
2585 sharedLibraryFile.lastModified() != entry.getTime()) {
2586 if (Config.LOGD) {
2587 Log.d(TAG, "Caching shared lib " + entry.getName());
2588 }
2589 if (mInstaller == null) {
2590 sharedLibraryDir.mkdir();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
2592 cacheSharedLibLI(pkg, zipFile, entry, sharedLibraryDir,
2593 sharedLibraryFile);
2594 }
2595 }
2596 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07002597 Log.w(TAG, "Failed to cache package shared libs", e);
2598 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07002600
2601 if (hasNativeCode && !installedNativeCode) {
2602 Log.w(TAG, "Install failed: .apk has native code but none for arch "
2603 + Build.CPU_ABI);
2604 return PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
2605 }
2606
2607 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 }
2609
2610 private void cacheSharedLibLI(PackageParser.Package pkg,
2611 ZipFile zipFile, ZipEntry entry,
2612 File sharedLibraryDir,
2613 File sharedLibraryFile) throws IOException {
2614 InputStream inputStream = zipFile.getInputStream(entry);
2615 try {
2616 File tempFile = File.createTempFile("tmp", "tmp", sharedLibraryDir);
2617 String tempFilePath = tempFile.getPath();
2618 // XXX package manager can't change owner, so the lib files for
2619 // now need to be left as world readable and owned by the system.
2620 if (! FileUtils.copyToFile(inputStream, tempFile) ||
2621 ! tempFile.setLastModified(entry.getTime()) ||
2622 FileUtils.setPermissions(tempFilePath,
2623 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
2624 |FileUtils.S_IROTH, -1, -1) != 0 ||
2625 ! tempFile.renameTo(sharedLibraryFile)) {
2626 // Failed to properly write file.
2627 tempFile.delete();
2628 throw new IOException("Couldn't create cached shared lib "
2629 + sharedLibraryFile + " in " + sharedLibraryDir);
2630 }
2631 } finally {
2632 inputStream.close();
2633 }
2634 }
2635
2636 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
2637 if (chatty && Config.LOGD) Log.d(
2638 TAG, "Removing package " + pkg.applicationInfo.packageName );
2639
2640 synchronized (mPackages) {
2641 if (pkg.mPreferredOrder > 0) {
2642 mSettings.mPreferredPackages.remove(pkg);
2643 pkg.mPreferredOrder = 0;
2644 updatePreferredIndicesLP();
2645 }
2646
2647 clearPackagePreferredActivitiesLP(pkg.packageName);
2648
2649 mPackages.remove(pkg.applicationInfo.packageName);
2650 if (pkg.mPath != null) {
2651 mAppDirs.remove(pkg.mPath);
2652 }
2653
2654 PackageSetting ps = (PackageSetting)pkg.mExtras;
2655 if (ps != null && ps.sharedUser != null) {
2656 // XXX don't do this until the data is removed.
2657 if (false) {
2658 ps.sharedUser.packages.remove(ps);
2659 if (ps.sharedUser.packages.size() == 0) {
2660 // Remove.
2661 }
2662 }
2663 }
2664
2665 int N = pkg.providers.size();
2666 StringBuilder r = null;
2667 int i;
2668 for (i=0; i<N; i++) {
2669 PackageParser.Provider p = pkg.providers.get(i);
2670 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
2671 p.info.name));
2672 if (p.info.authority == null) {
2673
2674 /* The is another ContentProvider with this authority when
2675 * this app was installed so this authority is null,
2676 * Ignore it as we don't have to unregister the provider.
2677 */
2678 continue;
2679 }
2680 String names[] = p.info.authority.split(";");
2681 for (int j = 0; j < names.length; j++) {
2682 if (mProviders.get(names[j]) == p) {
2683 mProviders.remove(names[j]);
2684 if (chatty && Config.LOGD) Log.d(
2685 TAG, "Unregistered content provider: " + names[j] +
2686 ", className = " + p.info.name +
2687 ", isSyncable = " + p.info.isSyncable);
2688 }
2689 }
2690 if (chatty) {
2691 if (r == null) {
2692 r = new StringBuilder(256);
2693 } else {
2694 r.append(' ');
2695 }
2696 r.append(p.info.name);
2697 }
2698 }
2699 if (r != null) {
2700 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2701 }
2702
2703 N = pkg.services.size();
2704 r = null;
2705 for (i=0; i<N; i++) {
2706 PackageParser.Service s = pkg.services.get(i);
2707 mServices.removeService(s);
2708 if (chatty) {
2709 if (r == null) {
2710 r = new StringBuilder(256);
2711 } else {
2712 r.append(' ');
2713 }
2714 r.append(s.info.name);
2715 }
2716 }
2717 if (r != null) {
2718 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2719 }
2720
2721 N = pkg.receivers.size();
2722 r = null;
2723 for (i=0; i<N; i++) {
2724 PackageParser.Activity a = pkg.receivers.get(i);
2725 mReceivers.removeActivity(a, "receiver");
2726 if (chatty) {
2727 if (r == null) {
2728 r = new StringBuilder(256);
2729 } else {
2730 r.append(' ');
2731 }
2732 r.append(a.info.name);
2733 }
2734 }
2735 if (r != null) {
2736 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2737 }
2738
2739 N = pkg.activities.size();
2740 r = null;
2741 for (i=0; i<N; i++) {
2742 PackageParser.Activity a = pkg.activities.get(i);
2743 mActivities.removeActivity(a, "activity");
2744 if (chatty) {
2745 if (r == null) {
2746 r = new StringBuilder(256);
2747 } else {
2748 r.append(' ');
2749 }
2750 r.append(a.info.name);
2751 }
2752 }
2753 if (r != null) {
2754 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2755 }
2756
2757 N = pkg.permissions.size();
2758 r = null;
2759 for (i=0; i<N; i++) {
2760 PackageParser.Permission p = pkg.permissions.get(i);
2761 boolean tree = false;
2762 BasePermission bp = mSettings.mPermissions.get(p.info.name);
2763 if (bp == null) {
2764 tree = true;
2765 bp = mSettings.mPermissionTrees.get(p.info.name);
2766 }
2767 if (bp != null && bp.perm == p) {
2768 if (bp.type != BasePermission.TYPE_BUILTIN) {
2769 if (tree) {
2770 mSettings.mPermissionTrees.remove(p.info.name);
2771 } else {
2772 mSettings.mPermissions.remove(p.info.name);
2773 }
2774 } else {
2775 bp.perm = null;
2776 }
2777 if (chatty) {
2778 if (r == null) {
2779 r = new StringBuilder(256);
2780 } else {
2781 r.append(' ');
2782 }
2783 r.append(p.info.name);
2784 }
2785 }
2786 }
2787 if (r != null) {
2788 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2789 }
2790
2791 N = pkg.instrumentation.size();
2792 r = null;
2793 for (i=0; i<N; i++) {
2794 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2795 mInstrumentation.remove(a.component);
2796 if (chatty) {
2797 if (r == null) {
2798 r = new StringBuilder(256);
2799 } else {
2800 r.append(' ');
2801 }
2802 r.append(a.info.name);
2803 }
2804 }
2805 if (r != null) {
2806 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2807 }
2808 }
2809 }
2810
2811 private static final boolean isPackageFilename(String name) {
2812 return name != null && name.endsWith(".apk");
2813 }
2814
2815 private void updatePermissionsLP() {
2816 // Make sure there are no dangling permission trees.
2817 Iterator<BasePermission> it = mSettings.mPermissionTrees
2818 .values().iterator();
2819 while (it.hasNext()) {
2820 BasePermission bp = it.next();
2821 if (bp.perm == null) {
2822 Log.w(TAG, "Removing dangling permission tree: " + bp.name
2823 + " from package " + bp.sourcePackage);
2824 it.remove();
2825 }
2826 }
2827
2828 // Make sure all dynamic permissions have been assigned to a package,
2829 // and make sure there are no dangling permissions.
2830 it = mSettings.mPermissions.values().iterator();
2831 while (it.hasNext()) {
2832 BasePermission bp = it.next();
2833 if (bp.type == BasePermission.TYPE_DYNAMIC) {
2834 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
2835 + bp.name + " pkg=" + bp.sourcePackage
2836 + " info=" + bp.pendingInfo);
2837 if (bp.perm == null && bp.pendingInfo != null) {
2838 BasePermission tree = findPermissionTreeLP(bp.name);
2839 if (tree != null) {
2840 bp.perm = new PackageParser.Permission(tree.perm.owner,
2841 new PermissionInfo(bp.pendingInfo));
2842 bp.perm.info.packageName = tree.perm.info.packageName;
2843 bp.perm.info.name = bp.name;
2844 bp.uid = tree.uid;
2845 }
2846 }
2847 }
2848 if (bp.perm == null) {
2849 Log.w(TAG, "Removing dangling permission: " + bp.name
2850 + " from package " + bp.sourcePackage);
2851 it.remove();
2852 }
2853 }
2854
2855 // Now update the permissions for all packages, in particular
2856 // replace the granted permissions of the system packages.
2857 for (PackageParser.Package pkg : mPackages.values()) {
2858 grantPermissionsLP(pkg, false);
2859 }
2860 }
2861
2862 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
2863 final PackageSetting ps = (PackageSetting)pkg.mExtras;
2864 if (ps == null) {
2865 return;
2866 }
2867 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2868 boolean addedPermission = false;
2869
2870 if (replace) {
2871 ps.permissionsFixed = false;
2872 if (gp == ps) {
2873 gp.grantedPermissions.clear();
2874 gp.gids = mGlobalGids;
2875 }
2876 }
2877
2878 if (gp.gids == null) {
2879 gp.gids = mGlobalGids;
2880 }
2881
2882 final int N = pkg.requestedPermissions.size();
2883 for (int i=0; i<N; i++) {
2884 String name = pkg.requestedPermissions.get(i);
2885 BasePermission bp = mSettings.mPermissions.get(name);
2886 PackageParser.Permission p = bp != null ? bp.perm : null;
2887 if (false) {
2888 if (gp != ps) {
2889 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
2890 + ": " + p);
2891 }
2892 }
2893 if (p != null) {
2894 final String perm = p.info.name;
2895 boolean allowed;
2896 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
2897 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
2898 allowed = true;
2899 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
2900 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
2901 allowed = (checkSignaturesLP(p.owner, pkg)
2902 == PackageManager.SIGNATURE_MATCH)
2903 || (checkSignaturesLP(mPlatformPackage, pkg)
2904 == PackageManager.SIGNATURE_MATCH);
2905 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
2906 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
2907 // For updated system applications, the signatureOrSystem permission
2908 // is granted only if it had been defined by the original application.
2909 if ((pkg.applicationInfo.flags
2910 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
2911 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
2912 if(sysPs.grantedPermissions.contains(perm)) {
2913 allowed = true;
2914 } else {
2915 allowed = false;
2916 }
2917 } else {
2918 allowed = true;
2919 }
2920 }
2921 }
2922 } else {
2923 allowed = false;
2924 }
2925 if (false) {
2926 if (gp != ps) {
2927 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
2928 }
2929 }
2930 if (allowed) {
2931 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
2932 && ps.permissionsFixed) {
2933 // If this is an existing, non-system package, then
2934 // we can't add any new permissions to it.
2935 if (!gp.loadedPermissions.contains(perm)) {
2936 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07002937 // Except... if this is a permission that was added
2938 // to the platform (note: need to only do this when
2939 // updating the platform).
2940 final int NP = PackageParser.NEW_PERMISSIONS.length;
2941 for (int ip=0; ip<NP; ip++) {
2942 final PackageParser.NewPermissionInfo npi
2943 = PackageParser.NEW_PERMISSIONS[ip];
2944 if (npi.name.equals(perm)
2945 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
2946 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07002947 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07002948 + pkg.packageName);
2949 break;
2950 }
2951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 }
2953 }
2954 if (allowed) {
2955 if (!gp.grantedPermissions.contains(perm)) {
2956 addedPermission = true;
2957 gp.grantedPermissions.add(perm);
2958 gp.gids = appendInts(gp.gids, bp.gids);
2959 }
2960 } else {
2961 Log.w(TAG, "Not granting permission " + perm
2962 + " to package " + pkg.packageName
2963 + " because it was previously installed without");
2964 }
2965 } else {
2966 Log.w(TAG, "Not granting permission " + perm
2967 + " to package " + pkg.packageName
2968 + " (protectionLevel=" + p.info.protectionLevel
2969 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
2970 + ")");
2971 }
2972 } else {
2973 Log.w(TAG, "Unknown permission " + name
2974 + " in package " + pkg.packageName);
2975 }
2976 }
2977
2978 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002979 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
2980 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 // This is the first that we have heard about this package, so the
2982 // permissions we have now selected are fixed until explicitly
2983 // changed.
2984 ps.permissionsFixed = true;
2985 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
2986 }
2987 }
2988
2989 private final class ActivityIntentResolver
2990 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02002991 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02002993 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 }
2995
Mihai Preda074edef2009-05-18 17:13:31 +02002996 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02002998 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3000 }
3001
Mihai Predaeae850c2009-05-13 10:13:48 +02003002 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3003 ArrayList<PackageParser.Activity> packageActivities) {
3004 if (packageActivities == null) {
3005 return null;
3006 }
3007 mFlags = flags;
3008 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3009 int N = packageActivities.size();
3010 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3011 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003012
3013 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003014 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003015 intentFilters = packageActivities.get(i).intents;
3016 if (intentFilters != null && intentFilters.size() > 0) {
3017 listCut.add(intentFilters);
3018 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003019 }
3020 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3021 }
3022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 public final void addActivity(PackageParser.Activity a, String type) {
3024 mActivities.put(a.component, a);
3025 if (SHOW_INFO || Config.LOGV) Log.v(
3026 TAG, " " + type + " " +
3027 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3028 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3029 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003030 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3032 if (SHOW_INFO || Config.LOGV) {
3033 Log.v(TAG, " IntentFilter:");
3034 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3035 }
3036 if (!intent.debugCheck()) {
3037 Log.w(TAG, "==> For Activity " + a.info.name);
3038 }
3039 addFilter(intent);
3040 }
3041 }
3042
3043 public final void removeActivity(PackageParser.Activity a, String type) {
3044 mActivities.remove(a.component);
3045 if (SHOW_INFO || Config.LOGV) Log.v(
3046 TAG, " " + type + " " +
3047 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3048 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3049 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003050 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3052 if (SHOW_INFO || Config.LOGV) {
3053 Log.v(TAG, " IntentFilter:");
3054 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3055 }
3056 removeFilter(intent);
3057 }
3058 }
3059
3060 @Override
3061 protected boolean allowFilterResult(
3062 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3063 ActivityInfo filterAi = filter.activity.info;
3064 for (int i=dest.size()-1; i>=0; i--) {
3065 ActivityInfo destAi = dest.get(i).activityInfo;
3066 if (destAi.name == filterAi.name
3067 && destAi.packageName == filterAi.packageName) {
3068 return false;
3069 }
3070 }
3071 return true;
3072 }
3073
3074 @Override
3075 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3076 int match) {
3077 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3078 return null;
3079 }
3080 final PackageParser.Activity activity = info.activity;
3081 if (mSafeMode && (activity.info.applicationInfo.flags
3082 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3083 return null;
3084 }
3085 final ResolveInfo res = new ResolveInfo();
3086 res.activityInfo = PackageParser.generateActivityInfo(activity,
3087 mFlags);
3088 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3089 res.filter = info;
3090 }
3091 res.priority = info.getPriority();
3092 res.preferredOrder = activity.owner.mPreferredOrder;
3093 //System.out.println("Result: " + res.activityInfo.className +
3094 // " = " + res.priority);
3095 res.match = match;
3096 res.isDefault = info.hasDefault;
3097 res.labelRes = info.labelRes;
3098 res.nonLocalizedLabel = info.nonLocalizedLabel;
3099 res.icon = info.icon;
3100 return res;
3101 }
3102
3103 @Override
3104 protected void sortResults(List<ResolveInfo> results) {
3105 Collections.sort(results, mResolvePrioritySorter);
3106 }
3107
3108 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003109 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003111 out.print(prefix); out.print(
3112 Integer.toHexString(System.identityHashCode(filter.activity)));
3113 out.print(' ');
3114 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 }
3116
3117// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3118// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3119// final List<ResolveInfo> retList = Lists.newArrayList();
3120// while (i.hasNext()) {
3121// final ResolveInfo resolveInfo = i.next();
3122// if (isEnabledLP(resolveInfo.activityInfo)) {
3123// retList.add(resolveInfo);
3124// }
3125// }
3126// return retList;
3127// }
3128
3129 // Keys are String (activity class name), values are Activity.
3130 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3131 = new HashMap<ComponentName, PackageParser.Activity>();
3132 private int mFlags;
3133 }
3134
3135 private final class ServiceIntentResolver
3136 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003137 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003139 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 }
3141
Mihai Preda074edef2009-05-18 17:13:31 +02003142 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003144 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3146 }
3147
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003148 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3149 ArrayList<PackageParser.Service> packageServices) {
3150 if (packageServices == null) {
3151 return null;
3152 }
3153 mFlags = flags;
3154 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3155 int N = packageServices.size();
3156 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3157 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3158
3159 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3160 for (int i = 0; i < N; ++i) {
3161 intentFilters = packageServices.get(i).intents;
3162 if (intentFilters != null && intentFilters.size() > 0) {
3163 listCut.add(intentFilters);
3164 }
3165 }
3166 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3167 }
3168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 public final void addService(PackageParser.Service s) {
3170 mServices.put(s.component, s);
3171 if (SHOW_INFO || Config.LOGV) Log.v(
3172 TAG, " " + (s.info.nonLocalizedLabel != null
3173 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3174 if (SHOW_INFO || Config.LOGV) Log.v(
3175 TAG, " Class=" + s.info.name);
3176 int NI = s.intents.size();
3177 int j;
3178 for (j=0; j<NI; j++) {
3179 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3180 if (SHOW_INFO || Config.LOGV) {
3181 Log.v(TAG, " IntentFilter:");
3182 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3183 }
3184 if (!intent.debugCheck()) {
3185 Log.w(TAG, "==> For Service " + s.info.name);
3186 }
3187 addFilter(intent);
3188 }
3189 }
3190
3191 public final void removeService(PackageParser.Service s) {
3192 mServices.remove(s.component);
3193 if (SHOW_INFO || Config.LOGV) Log.v(
3194 TAG, " " + (s.info.nonLocalizedLabel != null
3195 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3196 if (SHOW_INFO || Config.LOGV) Log.v(
3197 TAG, " Class=" + s.info.name);
3198 int NI = s.intents.size();
3199 int j;
3200 for (j=0; j<NI; j++) {
3201 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3202 if (SHOW_INFO || Config.LOGV) {
3203 Log.v(TAG, " IntentFilter:");
3204 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3205 }
3206 removeFilter(intent);
3207 }
3208 }
3209
3210 @Override
3211 protected boolean allowFilterResult(
3212 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3213 ServiceInfo filterSi = filter.service.info;
3214 for (int i=dest.size()-1; i>=0; i--) {
3215 ServiceInfo destAi = dest.get(i).serviceInfo;
3216 if (destAi.name == filterSi.name
3217 && destAi.packageName == filterSi.packageName) {
3218 return false;
3219 }
3220 }
3221 return true;
3222 }
3223
3224 @Override
3225 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3226 int match) {
3227 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3228 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3229 return null;
3230 }
3231 final PackageParser.Service service = info.service;
3232 if (mSafeMode && (service.info.applicationInfo.flags
3233 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3234 return null;
3235 }
3236 final ResolveInfo res = new ResolveInfo();
3237 res.serviceInfo = PackageParser.generateServiceInfo(service,
3238 mFlags);
3239 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3240 res.filter = filter;
3241 }
3242 res.priority = info.getPriority();
3243 res.preferredOrder = service.owner.mPreferredOrder;
3244 //System.out.println("Result: " + res.activityInfo.className +
3245 // " = " + res.priority);
3246 res.match = match;
3247 res.isDefault = info.hasDefault;
3248 res.labelRes = info.labelRes;
3249 res.nonLocalizedLabel = info.nonLocalizedLabel;
3250 res.icon = info.icon;
3251 return res;
3252 }
3253
3254 @Override
3255 protected void sortResults(List<ResolveInfo> results) {
3256 Collections.sort(results, mResolvePrioritySorter);
3257 }
3258
3259 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003260 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003262 out.print(prefix); out.print(
3263 Integer.toHexString(System.identityHashCode(filter.service)));
3264 out.print(' ');
3265 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 }
3267
3268// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3269// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3270// final List<ResolveInfo> retList = Lists.newArrayList();
3271// while (i.hasNext()) {
3272// final ResolveInfo resolveInfo = (ResolveInfo) i;
3273// if (isEnabledLP(resolveInfo.serviceInfo)) {
3274// retList.add(resolveInfo);
3275// }
3276// }
3277// return retList;
3278// }
3279
3280 // Keys are String (activity class name), values are Activity.
3281 private final HashMap<ComponentName, PackageParser.Service> mServices
3282 = new HashMap<ComponentName, PackageParser.Service>();
3283 private int mFlags;
3284 };
3285
3286 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3287 new Comparator<ResolveInfo>() {
3288 public int compare(ResolveInfo r1, ResolveInfo r2) {
3289 int v1 = r1.priority;
3290 int v2 = r2.priority;
3291 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3292 if (v1 != v2) {
3293 return (v1 > v2) ? -1 : 1;
3294 }
3295 v1 = r1.preferredOrder;
3296 v2 = r2.preferredOrder;
3297 if (v1 != v2) {
3298 return (v1 > v2) ? -1 : 1;
3299 }
3300 if (r1.isDefault != r2.isDefault) {
3301 return r1.isDefault ? -1 : 1;
3302 }
3303 v1 = r1.match;
3304 v2 = r2.match;
3305 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3306 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3307 }
3308 };
3309
3310 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3311 new Comparator<ProviderInfo>() {
3312 public int compare(ProviderInfo p1, ProviderInfo p2) {
3313 final int v1 = p1.initOrder;
3314 final int v2 = p2.initOrder;
3315 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3316 }
3317 };
3318
3319 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3320 IActivityManager am = ActivityManagerNative.getDefault();
3321 if (am != null) {
3322 try {
3323 final Intent intent = new Intent(action,
3324 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3325 if (extras != null) {
3326 intent.putExtras(extras);
3327 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07003328 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 am.broadcastIntent(
3330 null, intent,
3331 null, null, 0, null, null, null, false, false);
3332 } catch (RemoteException ex) {
3333 }
3334 }
3335 }
3336
3337 private final class AppDirObserver extends FileObserver {
3338 public AppDirObserver(String path, int mask, boolean isrom) {
3339 super(path, mask);
3340 mRootDir = path;
3341 mIsRom = isrom;
3342 }
3343
3344 public void onEvent(int event, String path) {
3345 String removedPackage = null;
3346 int removedUid = -1;
3347 String addedPackage = null;
3348 int addedUid = -1;
3349
3350 synchronized (mInstallLock) {
3351 String fullPathStr = null;
3352 File fullPath = null;
3353 if (path != null) {
3354 fullPath = new File(mRootDir, path);
3355 fullPathStr = fullPath.getPath();
3356 }
3357
3358 if (Config.LOGV) Log.v(
3359 TAG, "File " + fullPathStr + " changed: "
3360 + Integer.toHexString(event));
3361
3362 if (!isPackageFilename(path)) {
3363 if (Config.LOGV) Log.v(
3364 TAG, "Ignoring change of non-package file: " + fullPathStr);
3365 return;
3366 }
3367
3368 if ((event&REMOVE_EVENTS) != 0) {
3369 synchronized (mInstallLock) {
3370 PackageParser.Package p = mAppDirs.get(fullPathStr);
3371 if (p != null) {
3372 removePackageLI(p, true);
3373 removedPackage = p.applicationInfo.packageName;
3374 removedUid = p.applicationInfo.uid;
3375 }
3376 }
3377 }
3378
3379 if ((event&ADD_EVENTS) != 0) {
3380 PackageParser.Package p = mAppDirs.get(fullPathStr);
3381 if (p == null) {
3382 p = scanPackageLI(fullPath, fullPath, fullPath,
3383 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3384 PackageParser.PARSE_CHATTY |
3385 PackageParser.PARSE_MUST_BE_APK,
3386 SCAN_MONITOR);
3387 if (p != null) {
3388 synchronized (mPackages) {
3389 grantPermissionsLP(p, false);
3390 }
3391 addedPackage = p.applicationInfo.packageName;
3392 addedUid = p.applicationInfo.uid;
3393 }
3394 }
3395 }
3396
3397 synchronized (mPackages) {
3398 mSettings.writeLP();
3399 }
3400 }
3401
3402 if (removedPackage != null) {
3403 Bundle extras = new Bundle(1);
3404 extras.putInt(Intent.EXTRA_UID, removedUid);
3405 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3406 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3407 }
3408 if (addedPackage != null) {
3409 Bundle extras = new Bundle(1);
3410 extras.putInt(Intent.EXTRA_UID, addedUid);
3411 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3412 }
3413 }
3414
3415 private final String mRootDir;
3416 private final boolean mIsRom;
3417 }
Jacek Surazski65e13172009-04-28 15:26:38 +02003418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 /* Called when a downloaded package installation has been confirmed by the user */
3420 public void installPackage(
3421 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02003422 installPackage(packageURI, observer, flags, null);
3423 }
3424
3425 /* Called when a downloaded package installation has been confirmed by the user */
3426 public void installPackage(
3427 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3428 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 mContext.enforceCallingOrSelfPermission(
3430 android.Manifest.permission.INSTALL_PACKAGES, null);
Jacek Surazski65e13172009-04-28 15:26:38 +02003431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 // Queue up an async operation since the package installation may take a little while.
3433 mHandler.post(new Runnable() {
3434 public void run() {
3435 mHandler.removeCallbacks(this);
3436 PackageInstalledInfo res;
3437 synchronized (mInstallLock) {
Jacek Surazski65e13172009-04-28 15:26:38 +02003438 res = installPackageLI(packageURI, flags, true, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 }
3440 if (observer != null) {
3441 try {
3442 observer.packageInstalled(res.name, res.returnCode);
3443 } catch (RemoteException e) {
3444 Log.i(TAG, "Observer no longer exists.");
3445 }
3446 }
3447 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
3448 // call appears in the synchronized block above.
3449 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3450 res.removedInfo.sendBroadcast(false, true);
3451 Bundle extras = new Bundle(1);
3452 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003453 final boolean update = res.removedInfo.removedPackage != null;
3454 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 extras.putBoolean(Intent.EXTRA_REPLACING, true);
3456 }
3457 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
3458 res.pkg.applicationInfo.packageName,
3459 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003460 if (update) {
3461 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
3462 res.pkg.applicationInfo.packageName,
3463 extras);
3464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 }
3466 Runtime.getRuntime().gc();
3467 }
3468 });
3469 }
3470
3471 class PackageInstalledInfo {
3472 String name;
3473 int uid;
3474 PackageParser.Package pkg;
3475 int returnCode;
3476 PackageRemovedInfo removedInfo;
3477 }
3478
3479 /*
3480 * Install a non-existing package.
3481 */
3482 private void installNewPackageLI(String pkgName,
3483 File tmpPackageFile,
3484 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003485 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003486 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 // Remember this for later, in case we need to rollback this install
3488 boolean dataDirExists = (new File(mAppDataDir, pkgName)).exists();
3489 res.name = pkgName;
3490 synchronized(mPackages) {
3491 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(destFilePath)) {
3492 // Don't allow installation over an existing package with the same name.
3493 Log.w(TAG, "Attempt to re-install " + pkgName
3494 + " without first uninstalling.");
3495 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
3496 return;
3497 }
3498 }
3499 if (destPackageFile.exists()) {
3500 // It's safe to do this because we know (from the above check) that the file
3501 // isn't currently used for an installed package.
3502 destPackageFile.delete();
3503 }
3504 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3505 PackageParser.Package newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3506 destResourceFile, pkg, 0,
3507 SCAN_MONITOR | SCAN_FORCE_DEX
3508 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003509 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3510 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 if (newPackage == null) {
3512 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3513 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3514 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3515 }
3516 } else {
3517 updateSettingsLI(pkgName, tmpPackageFile,
3518 destFilePath, destPackageFile,
3519 destResourceFile, pkg,
3520 newPackage,
3521 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02003522 forwardLocked,
3523 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 res);
3525 // delete the partially installed application. the data directory will have to be
3526 // restored if it was already existing
3527 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3528 // remove package from internal structures. Note that we want deletePackageX to
3529 // delete the package data and cache directories that it created in
3530 // scanPackageLocked, unless those directories existed before we even tried to
3531 // install.
3532 deletePackageLI(
3533 pkgName, true,
3534 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
3535 res.removedInfo);
3536 }
3537 }
3538 }
3539
3540 private void replacePackageLI(String pkgName,
3541 File tmpPackageFile,
3542 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003543 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003544 String installerPackageName, PackageInstalledInfo res) {
3545
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003546 PackageParser.Package oldPackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 // First find the old package info and check signatures
3548 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003549 oldPackage = mPackages.get(pkgName);
3550 if(checkSignaturesLP(pkg, oldPackage) != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3552 return;
3553 }
3554 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003555 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 if(sysPkg) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003557 replaceSystemPackageLI(oldPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003559 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003560 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 } else {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003562 replaceNonSystemPackageLI(oldPackage, tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003563 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003564 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003565 }
3566 }
3567
3568 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
3569 File tmpPackageFile,
3570 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003571 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003572 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 PackageParser.Package newPackage = null;
3574 String pkgName = deletedPackage.packageName;
3575 boolean deletedPkg = true;
3576 boolean updatedSettings = false;
Jacek Surazski65e13172009-04-28 15:26:38 +02003577
3578 String oldInstallerPackageName = null;
3579 synchronized (mPackages) {
3580 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
3581 }
3582
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003583 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 // First delete the existing package while retaining the data directory
3585 if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
3586 res.removedInfo)) {
3587 // If the existing package was'nt successfully deleted
3588 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3589 deletedPkg = false;
3590 } else {
3591 // Successfully deleted the old package. Now proceed with re-installation
3592 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3593 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3594 destResourceFile, pkg, parseFlags,
3595 SCAN_MONITOR | SCAN_FORCE_DEX
3596 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003597 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3598 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 if (newPackage == null) {
3600 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3601 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3602 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3603 }
3604 } else {
3605 updateSettingsLI(pkgName, tmpPackageFile,
3606 destFilePath, destPackageFile,
3607 destResourceFile, pkg,
3608 newPackage,
3609 true,
3610 forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003611 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 res);
3613 updatedSettings = true;
3614 }
3615 }
3616
3617 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3618 // If we deleted an exisiting package, the old source and resource files that we
3619 // were keeping around in case we needed them (see below) can now be deleted
3620 final ApplicationInfo deletedPackageAppInfo = deletedPackage.applicationInfo;
3621 final ApplicationInfo installedPackageAppInfo =
3622 newPackage.applicationInfo;
3623 if (!deletedPackageAppInfo.sourceDir
3624 .equals(installedPackageAppInfo.sourceDir)) {
3625 new File(deletedPackageAppInfo.sourceDir).delete();
3626 }
3627 if (!deletedPackageAppInfo.publicSourceDir
3628 .equals(installedPackageAppInfo.publicSourceDir)) {
3629 new File(deletedPackageAppInfo.publicSourceDir).delete();
3630 }
3631 //update signature on the new package setting
3632 //this should always succeed, since we checked the
3633 //signature earlier.
3634 synchronized(mPackages) {
3635 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
3636 parseFlags, true);
3637 }
3638 } else {
3639 // remove package from internal structures. Note that we want deletePackageX to
3640 // delete the package data and cache directories that it created in
3641 // scanPackageLocked, unless those directories existed before we even tried to
3642 // install.
3643 if(updatedSettings) {
3644 deletePackageLI(
3645 pkgName, true,
3646 PackageManager.DONT_DELETE_DATA,
3647 res.removedInfo);
3648 }
3649 // Since we failed to install the new package we need to restore the old
3650 // package that we deleted.
3651 if(deletedPkg) {
3652 installPackageLI(
3653 Uri.fromFile(new File(deletedPackage.mPath)),
3654 isForwardLocked(deletedPackage)
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003655 ? PackageManager.INSTALL_FORWARD_LOCK
Jacek Surazski65e13172009-04-28 15:26:38 +02003656 : 0, false, oldInstallerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 }
3658 }
3659 }
3660
3661 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
3662 File tmpPackageFile,
3663 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003664 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazski65e13172009-04-28 15:26:38 +02003665 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 PackageParser.Package newPackage = null;
3667 boolean updatedSettings = false;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003668 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 PackageParser.PARSE_IS_SYSTEM;
3670 String packageName = deletedPackage.packageName;
3671 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3672 if (packageName == null) {
3673 Log.w(TAG, "Attempt to delete null packageName.");
3674 return;
3675 }
3676 PackageParser.Package oldPkg;
3677 PackageSetting oldPkgSetting;
3678 synchronized (mPackages) {
3679 oldPkg = mPackages.get(packageName);
3680 oldPkgSetting = mSettings.mPackages.get(packageName);
3681 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
3682 (oldPkgSetting == null)) {
3683 Log.w(TAG, "Could'nt find package:"+packageName+" information");
3684 return;
3685 }
3686 }
3687 res.removedInfo.uid = oldPkg.applicationInfo.uid;
3688 res.removedInfo.removedPackage = packageName;
3689 // Remove existing system package
3690 removePackageLI(oldPkg, true);
3691 synchronized (mPackages) {
3692 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
3693 }
3694
3695 // Successfully disabled the old package. Now proceed with re-installation
3696 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3697 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3698 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3699 destResourceFile, pkg, parseFlags,
3700 SCAN_MONITOR | SCAN_FORCE_DEX
3701 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003702 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3703 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 if (newPackage == null) {
3705 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3706 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3707 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3708 }
3709 } else {
3710 updateSettingsLI(packageName, tmpPackageFile,
3711 destFilePath, destPackageFile,
3712 destResourceFile, pkg,
3713 newPackage,
3714 true,
Jacek Surazski65e13172009-04-28 15:26:38 +02003715 forwardLocked,
3716 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 res);
3718 updatedSettings = true;
3719 }
3720
3721 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3722 //update signature on the new package setting
3723 //this should always succeed, since we checked the
3724 //signature earlier.
3725 synchronized(mPackages) {
3726 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
3727 parseFlags, true);
3728 }
3729 } else {
3730 // Re installation failed. Restore old information
3731 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07003732 if (newPackage != null) {
3733 removePackageLI(newPackage, true);
3734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 // Add back the old system package
3736 scanPackageLI(oldPkgSetting.codePath, oldPkgSetting.codePath,
3737 oldPkgSetting.resourcePath,
3738 oldPkg, parseFlags,
3739 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07003740 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 // Restore the old system information in Settings
3742 synchronized(mPackages) {
3743 if(updatedSettings) {
3744 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02003745 mSettings.setInstallerPackageName(packageName,
3746 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747 }
3748 mSettings.writeLP();
3749 }
3750 }
3751 }
3752
3753 private void updateSettingsLI(String pkgName, File tmpPackageFile,
3754 String destFilePath, File destPackageFile,
3755 File destResourceFile,
3756 PackageParser.Package pkg,
3757 PackageParser.Package newPackage,
3758 boolean replacingExistingPackage,
3759 boolean forwardLocked,
Jacek Surazski65e13172009-04-28 15:26:38 +02003760 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 synchronized (mPackages) {
3762 //write settings. the installStatus will be incomplete at this stage.
3763 //note that the new package setting would have already been
3764 //added to mPackages. It hasn't been persisted yet.
3765 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
3766 mSettings.writeLP();
3767 }
3768
3769 int retCode = 0;
3770 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
3771 retCode = mInstaller.movedex(tmpPackageFile.toString(),
3772 destPackageFile.toString());
3773 if (retCode != 0) {
3774 Log.e(TAG, "Couldn't rename dex file: " + destPackageFile);
3775 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3776 return;
3777 }
3778 }
3779 // XXX There are probably some big issues here: upon doing
3780 // the rename, we have reached the point of no return (the
3781 // original .apk is gone!), so we can't fail. Yet... we can.
3782 if (!tmpPackageFile.renameTo(destPackageFile)) {
3783 Log.e(TAG, "Couldn't move package file to: " + destPackageFile);
3784 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3785 } else {
3786 res.returnCode = setPermissionsLI(pkgName, newPackage, destFilePath,
3787 destResourceFile,
3788 forwardLocked);
3789 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3790 return;
3791 } else {
3792 Log.d(TAG, "New package installed in " + destPackageFile);
3793 }
3794 }
3795 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3796 if (mInstaller != null) {
3797 mInstaller.rmdex(tmpPackageFile.getPath());
3798 }
3799 }
3800
3801 synchronized (mPackages) {
3802 grantPermissionsLP(newPackage, true);
3803 res.name = pkgName;
3804 res.uid = newPackage.applicationInfo.uid;
3805 res.pkg = newPackage;
3806 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02003807 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3809 //to update install status
3810 mSettings.writeLP();
3811 }
3812 }
3813
The Android Open Source Project10592532009-03-18 17:39:46 -07003814 private PackageInstalledInfo installPackageLI(Uri pPackageURI,
Jacek Surazski65e13172009-04-28 15:26:38 +02003815 int pFlags, boolean newInstall, String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 File tmpPackageFile = null;
3817 String pkgName = null;
3818 boolean forwardLocked = false;
3819 boolean replacingExistingPackage = false;
3820 // Result object to be returned
3821 PackageInstalledInfo res = new PackageInstalledInfo();
3822 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3823 res.uid = -1;
3824 res.pkg = null;
3825 res.removedInfo = new PackageRemovedInfo();
3826
3827 main_flow: try {
3828 tmpPackageFile = createTempPackageFile();
3829 if (tmpPackageFile == null) {
3830 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3831 break main_flow;
3832 }
3833 tmpPackageFile.deleteOnExit(); // paranoia
3834 if (pPackageURI.getScheme().equals("file")) {
3835 final File srcPackageFile = new File(pPackageURI.getPath());
3836 // We copy the source package file to a temp file and then rename it to the
3837 // destination file in order to eliminate a window where the package directory
3838 // scanner notices the new package file but it's not completely copied yet.
3839 if (!FileUtils.copyFile(srcPackageFile, tmpPackageFile)) {
3840 Log.e(TAG, "Couldn't copy package file to temp file.");
3841 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3842 break main_flow;
3843 }
3844 } else if (pPackageURI.getScheme().equals("content")) {
3845 ParcelFileDescriptor fd;
3846 try {
3847 fd = mContext.getContentResolver().openFileDescriptor(pPackageURI, "r");
3848 } catch (FileNotFoundException e) {
3849 Log.e(TAG, "Couldn't open file descriptor from download service.");
3850 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3851 break main_flow;
3852 }
3853 if (fd == null) {
3854 Log.e(TAG, "Couldn't open file descriptor from download service (null).");
3855 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3856 break main_flow;
3857 }
3858 if (Config.LOGV) {
3859 Log.v(TAG, "Opened file descriptor from download service.");
3860 }
3861 ParcelFileDescriptor.AutoCloseInputStream
3862 dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
3863 // We copy the source package file to a temp file and then rename it to the
3864 // destination file in order to eliminate a window where the package directory
3865 // scanner notices the new package file but it's not completely copied yet.
3866 if (!FileUtils.copyToFile(dlStream, tmpPackageFile)) {
3867 Log.e(TAG, "Couldn't copy package stream to temp file.");
3868 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3869 break main_flow;
3870 }
3871 } else {
3872 Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
3873 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_URI;
3874 break main_flow;
3875 }
3876 pkgName = PackageParser.parsePackageName(
3877 tmpPackageFile.getAbsolutePath(), 0);
3878 if (pkgName == null) {
3879 Log.e(TAG, "Couldn't find a package name in : " + tmpPackageFile);
3880 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3881 break main_flow;
3882 }
3883 res.name = pkgName;
3884 //initialize some variables before installing pkg
3885 final String pkgFileName = pkgName + ".apk";
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003886 final File destDir = ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 ? mDrmAppPrivateInstallDir
3888 : mAppInstallDir;
3889 final File destPackageFile = new File(destDir, pkgFileName);
3890 final String destFilePath = destPackageFile.getAbsolutePath();
3891 File destResourceFile;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003892 if ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 final String publicZipFileName = pkgName + ".zip";
3894 destResourceFile = new File(mAppInstallDir, publicZipFileName);
3895 forwardLocked = true;
3896 } else {
3897 destResourceFile = destPackageFile;
3898 }
3899 // Retrieve PackageSettings and parse package
3900 int parseFlags = PackageParser.PARSE_CHATTY;
3901 parseFlags |= mDefParseFlags;
3902 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
3903 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackborn851a5412009-05-08 12:06:44 -07003904 pp.setSdkVersion(mSdkVersion, mSdkCodename);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
3906 destPackageFile.getAbsolutePath(), mMetrics, parseFlags);
3907 if (pkg == null) {
3908 res.returnCode = pp.getParseError();
3909 break main_flow;
3910 }
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003911 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
3912 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
3913 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
3914 break main_flow;
3915 }
3916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
3918 res.returnCode = pp.getParseError();
3919 break main_flow;
3920 }
3921
3922 synchronized (mPackages) {
3923 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003924 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 && mPackages.containsKey(pkgName)) {
3926 replacingExistingPackage = true;
3927 }
3928 }
3929
3930 if(replacingExistingPackage) {
3931 replacePackageLI(pkgName,
3932 tmpPackageFile,
3933 destFilePath, destPackageFile, destResourceFile,
Jacek Surazski65e13172009-04-28 15:26:38 +02003934 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 res);
3936 } else {
3937 installNewPackageLI(pkgName,
3938 tmpPackageFile,
3939 destFilePath, destPackageFile, destResourceFile,
Jacek Surazski65e13172009-04-28 15:26:38 +02003940 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 res);
3942 }
3943 } finally {
3944 if (tmpPackageFile != null && tmpPackageFile.exists()) {
3945 tmpPackageFile.delete();
3946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003948 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 }
3950
3951 private int setPermissionsLI(String pkgName,
3952 PackageParser.Package newPackage,
3953 String destFilePath,
3954 File destResourceFile,
3955 boolean forwardLocked) {
3956 int retCode;
3957 if (forwardLocked) {
3958 try {
3959 extractPublicFiles(newPackage, destResourceFile);
3960 } catch (IOException e) {
3961 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
3962 " forward-locked app.");
3963 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3964 } finally {
3965 //TODO clean up the extracted public files
3966 }
3967 if (mInstaller != null) {
3968 retCode = mInstaller.setForwardLockPerm(pkgName,
3969 newPackage.applicationInfo.uid);
3970 } else {
3971 final int filePermissions =
3972 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
3973 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1,
3974 newPackage.applicationInfo.uid);
3975 }
3976 } else {
3977 final int filePermissions =
3978 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
3979 |FileUtils.S_IROTH;
3980 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1, -1);
3981 }
3982 if (retCode != 0) {
3983 Log.e(TAG, "Couldn't set new package file permissions for " + destFilePath
3984 + ". The return code was: " + retCode);
3985 }
3986 return PackageManager.INSTALL_SUCCEEDED;
3987 }
3988
3989 private boolean isForwardLocked(PackageParser.Package deletedPackage) {
3990 final ApplicationInfo applicationInfo = deletedPackage.applicationInfo;
3991 return applicationInfo.sourceDir.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath());
3992 }
3993
3994 private void extractPublicFiles(PackageParser.Package newPackage,
3995 File publicZipFile) throws IOException {
3996 final ZipOutputStream publicZipOutStream =
3997 new ZipOutputStream(new FileOutputStream(publicZipFile));
3998 final ZipFile privateZip = new ZipFile(newPackage.mPath);
3999
4000 // Copy manifest, resources.arsc and res directory to public zip
4001
4002 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
4003 while (privateZipEntries.hasMoreElements()) {
4004 final ZipEntry zipEntry = privateZipEntries.nextElement();
4005 final String zipEntryName = zipEntry.getName();
4006 if ("AndroidManifest.xml".equals(zipEntryName)
4007 || "resources.arsc".equals(zipEntryName)
4008 || zipEntryName.startsWith("res/")) {
4009 try {
4010 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
4011 } catch (IOException e) {
4012 try {
4013 publicZipOutStream.close();
4014 throw e;
4015 } finally {
4016 publicZipFile.delete();
4017 }
4018 }
4019 }
4020 }
4021
4022 publicZipOutStream.close();
4023 FileUtils.setPermissions(
4024 publicZipFile.getAbsolutePath(),
4025 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
4026 -1, -1);
4027 }
4028
4029 private static void copyZipEntry(ZipEntry zipEntry,
4030 ZipFile inZipFile,
4031 ZipOutputStream outZipStream) throws IOException {
4032 byte[] buffer = new byte[4096];
4033 int num;
4034
4035 ZipEntry newEntry;
4036 if (zipEntry.getMethod() == ZipEntry.STORED) {
4037 // Preserve the STORED method of the input entry.
4038 newEntry = new ZipEntry(zipEntry);
4039 } else {
4040 // Create a new entry so that the compressed len is recomputed.
4041 newEntry = new ZipEntry(zipEntry.getName());
4042 }
4043 outZipStream.putNextEntry(newEntry);
4044
4045 InputStream data = inZipFile.getInputStream(zipEntry);
4046 while ((num = data.read(buffer)) > 0) {
4047 outZipStream.write(buffer, 0, num);
4048 }
4049 outZipStream.flush();
4050 }
4051
4052 private void deleteTempPackageFiles() {
4053 FilenameFilter filter = new FilenameFilter() {
4054 public boolean accept(File dir, String name) {
4055 return name.startsWith("vmdl") && name.endsWith(".tmp");
4056 }
4057 };
4058 String tmpFilesList[] = mAppInstallDir.list(filter);
4059 if(tmpFilesList == null) {
4060 return;
4061 }
4062 for(int i = 0; i < tmpFilesList.length; i++) {
4063 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
4064 tmpFile.delete();
4065 }
4066 }
4067
4068 private File createTempPackageFile() {
4069 File tmpPackageFile;
4070 try {
4071 tmpPackageFile = File.createTempFile("vmdl", ".tmp", mAppInstallDir);
4072 } catch (IOException e) {
4073 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
4074 return null;
4075 }
4076 try {
4077 FileUtils.setPermissions(
4078 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
4079 -1, -1);
4080 } catch (IOException e) {
4081 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
4082 return null;
4083 }
4084 return tmpPackageFile;
4085 }
4086
4087 public void deletePackage(final String packageName,
4088 final IPackageDeleteObserver observer,
4089 final int flags) {
4090 mContext.enforceCallingOrSelfPermission(
4091 android.Manifest.permission.DELETE_PACKAGES, null);
4092 // Queue up an async operation since the package deletion may take a little while.
4093 mHandler.post(new Runnable() {
4094 public void run() {
4095 mHandler.removeCallbacks(this);
4096 final boolean succeded = deletePackageX(packageName, true, true, flags);
4097 if (observer != null) {
4098 try {
4099 observer.packageDeleted(succeded);
4100 } catch (RemoteException e) {
4101 Log.i(TAG, "Observer no longer exists.");
4102 } //end catch
4103 } //end if
4104 } //end run
4105 });
4106 }
4107
4108 /**
4109 * This method is an internal method that could be get invoked either
4110 * to delete an installed package or to clean up a failed installation.
4111 * After deleting an installed package, a broadcast is sent to notify any
4112 * listeners that the package has been installed. For cleaning up a failed
4113 * installation, the broadcast is not necessary since the package's
4114 * installation wouldn't have sent the initial broadcast either
4115 * The key steps in deleting a package are
4116 * deleting the package information in internal structures like mPackages,
4117 * deleting the packages base directories through installd
4118 * updating mSettings to reflect current status
4119 * persisting settings for later use
4120 * sending a broadcast if necessary
4121 */
4122
4123 private boolean deletePackageX(String packageName, boolean sendBroadCast,
4124 boolean deleteCodeAndResources, int flags) {
4125 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07004126 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127
4128 synchronized (mInstallLock) {
4129 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
4130 }
4131
4132 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004133 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4134 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4135
4136 // If the removed package was a system update, the old system packaged
4137 // was re-enabled; we need to broadcast this information
4138 if (systemUpdate) {
4139 Bundle extras = new Bundle(1);
4140 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4141 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4142
4143 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4144 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 }
4147 return res;
4148 }
4149
4150 static class PackageRemovedInfo {
4151 String removedPackage;
4152 int uid = -1;
4153 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004154 boolean isRemovedPackageSystemUpdate = false;
4155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 void sendBroadcast(boolean fullRemove, boolean replacing) {
4157 Bundle extras = new Bundle(1);
4158 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4159 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4160 if (replacing) {
4161 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4162 }
4163 if (removedPackage != null) {
4164 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4165 }
4166 if (removedUid >= 0) {
4167 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
4168 }
4169 }
4170 }
4171
4172 /*
4173 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
4174 * flag is not set, the data directory is removed as well.
4175 * make sure this flag is set for partially installed apps. If not its meaningless to
4176 * delete a partially installed application.
4177 */
4178 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
4179 int flags) {
4180 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004181 if (outInfo != null) {
4182 outInfo.removedPackage = packageName;
4183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 removePackageLI(p, true);
4185 // Retrieve object to delete permissions for shared user later on
4186 PackageSetting deletedPs;
4187 synchronized (mPackages) {
4188 deletedPs = mSettings.mPackages.get(packageName);
4189 }
4190 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
4191 if (mInstaller != null) {
4192 int retCode = mInstaller.remove(packageName);
4193 if (retCode < 0) {
4194 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
4195 + packageName + ", retcode=" + retCode);
4196 // we don't consider this to be a failure of the core package deletion
4197 }
4198 } else {
4199 //for emulator
4200 PackageParser.Package pkg = mPackages.get(packageName);
4201 File dataDir = new File(pkg.applicationInfo.dataDir);
4202 dataDir.delete();
4203 }
4204 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004205 if (outInfo != null) {
4206 outInfo.removedUid = mSettings.removePackageLP(packageName);
4207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 }
4209 }
4210 synchronized (mPackages) {
4211 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
4212 // remove permissions associated with package
4213 mSettings.updateSharedUserPerms (deletedPs);
4214 }
4215 // Save settings now
4216 mSettings.writeLP ();
4217 }
4218 }
4219
4220 /*
4221 * Tries to delete system package.
4222 */
4223 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004224 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 ApplicationInfo applicationInfo = p.applicationInfo;
4226 //applicable for non-partially installed applications only
4227 if (applicationInfo == null) {
4228 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4229 return false;
4230 }
4231 PackageSetting ps = null;
4232 // Confirm if the system package has been updated
4233 // An updated system app can be deleted. This will also have to restore
4234 // the system pkg from system partition
4235 synchronized (mPackages) {
4236 ps = mSettings.getDisabledSystemPkg(p.packageName);
4237 }
4238 if (ps == null) {
4239 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
4240 return false;
4241 } else {
4242 Log.i(TAG, "Deleting system pkg from data partition");
4243 }
4244 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07004245 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004246 boolean deleteCodeAndResources = false;
4247 if (ps.versionCode < p.mVersionCode) {
4248 // Delete code and resources for downgrades
4249 deleteCodeAndResources = true;
4250 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4251 flags &= ~PackageManager.DONT_DELETE_DATA;
4252 }
4253 } else {
4254 // Preserve data by setting flag
4255 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4256 flags |= PackageManager.DONT_DELETE_DATA;
4257 }
4258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
4260 if (!ret) {
4261 return false;
4262 }
4263 synchronized (mPackages) {
4264 // Reinstate the old system package
4265 mSettings.enableSystemPackageLP(p.packageName);
4266 }
4267 // Install the system package
4268 PackageParser.Package newPkg = scanPackageLI(ps.codePath, ps.codePath, ps.resourcePath,
4269 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
4270 SCAN_MONITOR);
4271
4272 if (newPkg == null) {
4273 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
4274 return false;
4275 }
4276 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07004277 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 mSettings.writeLP();
4279 }
4280 return true;
4281 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004282
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004283 private void deletePackageResourcesLI(String packageName,
4284 String sourceDir, String publicSourceDir) {
4285 File sourceFile = new File(sourceDir);
4286 if (!sourceFile.exists()) {
4287 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4288 }
4289 // Delete application's code and resources
4290 sourceFile.delete();
4291 final File publicSourceFile = new File(publicSourceDir);
4292 if (publicSourceFile.exists()) {
4293 publicSourceFile.delete();
4294 }
4295 if (mInstaller != null) {
4296 int retCode = mInstaller.rmdex(sourceFile.toString());
4297 if (retCode < 0) {
4298 Log.w(TAG, "Couldn't remove dex file for package: "
4299 + packageName + " at location " + sourceFile.toString() + ", retcode=" + retCode);
4300 // we don't consider this to be a failure of the core package deletion
4301 }
4302 }
4303 }
4304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 private boolean deleteInstalledPackageLI(PackageParser.Package p,
4306 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4307 ApplicationInfo applicationInfo = p.applicationInfo;
4308 if (applicationInfo == null) {
4309 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4310 return false;
4311 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004312 if (outInfo != null) {
4313 outInfo.uid = applicationInfo.uid;
4314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315
4316 // Delete package data from internal structures and also remove data if flag is set
4317 removePackageDataLI(p, outInfo, flags);
4318
4319 // Delete application code and resources
4320 if (deleteCodeAndResources) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004321 deletePackageResourcesLI(applicationInfo.packageName,
4322 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004323 }
4324 return true;
4325 }
4326
4327 /*
4328 * This method handles package deletion in general
4329 */
4330 private boolean deletePackageLI(String packageName,
4331 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4332 if (packageName == null) {
4333 Log.w(TAG, "Attempt to delete null packageName.");
4334 return false;
4335 }
4336 PackageParser.Package p;
4337 boolean dataOnly = false;
4338 synchronized (mPackages) {
4339 p = mPackages.get(packageName);
4340 if (p == null) {
4341 //this retrieves partially installed apps
4342 dataOnly = true;
4343 PackageSetting ps = mSettings.mPackages.get(packageName);
4344 if (ps == null) {
4345 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4346 return false;
4347 }
4348 p = ps.pkg;
4349 }
4350 }
4351 if (p == null) {
4352 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4353 return false;
4354 }
4355
4356 if (dataOnly) {
4357 // Delete application data first
4358 removePackageDataLI(p, outInfo, flags);
4359 return true;
4360 }
4361 // At this point the package should have ApplicationInfo associated with it
4362 if (p.applicationInfo == null) {
4363 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4364 return false;
4365 }
4366 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4367 Log.i(TAG, "Removing system package:"+p.packageName);
4368 // When an updated system application is deleted we delete the existing resources as well and
4369 // fall back to existing code in system partition
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004370 return deleteSystemPackageLI(p, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 }
4372 Log.i(TAG, "Removing non-system package:"+p.packageName);
4373 return deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
4374 }
4375
4376 public void clearApplicationUserData(final String packageName,
4377 final IPackageDataObserver observer) {
4378 mContext.enforceCallingOrSelfPermission(
4379 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4380 // Queue up an async operation since the package deletion may take a little while.
4381 mHandler.post(new Runnable() {
4382 public void run() {
4383 mHandler.removeCallbacks(this);
4384 final boolean succeeded;
4385 synchronized (mInstallLock) {
4386 succeeded = clearApplicationUserDataLI(packageName);
4387 }
4388 if (succeeded) {
4389 // invoke DeviceStorageMonitor's update method to clear any notifications
4390 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4391 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4392 if (dsm != null) {
4393 dsm.updateMemory();
4394 }
4395 }
4396 if(observer != null) {
4397 try {
4398 observer.onRemoveCompleted(packageName, succeeded);
4399 } catch (RemoteException e) {
4400 Log.i(TAG, "Observer no longer exists.");
4401 }
4402 } //end if observer
4403 } //end run
4404 });
4405 }
4406
4407 private boolean clearApplicationUserDataLI(String packageName) {
4408 if (packageName == null) {
4409 Log.w(TAG, "Attempt to delete null packageName.");
4410 return false;
4411 }
4412 PackageParser.Package p;
4413 boolean dataOnly = false;
4414 synchronized (mPackages) {
4415 p = mPackages.get(packageName);
4416 if(p == null) {
4417 dataOnly = true;
4418 PackageSetting ps = mSettings.mPackages.get(packageName);
4419 if((ps == null) || (ps.pkg == null)) {
4420 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4421 return false;
4422 }
4423 p = ps.pkg;
4424 }
4425 }
4426 if(!dataOnly) {
4427 //need to check this only for fully installed applications
4428 if (p == null) {
4429 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4430 return false;
4431 }
4432 final ApplicationInfo applicationInfo = p.applicationInfo;
4433 if (applicationInfo == null) {
4434 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4435 return false;
4436 }
4437 }
4438 if (mInstaller != null) {
4439 int retCode = mInstaller.clearUserData(packageName);
4440 if (retCode < 0) {
4441 Log.w(TAG, "Couldn't remove cache files for package: "
4442 + packageName);
4443 return false;
4444 }
4445 }
4446 return true;
4447 }
4448
4449 public void deleteApplicationCacheFiles(final String packageName,
4450 final IPackageDataObserver observer) {
4451 mContext.enforceCallingOrSelfPermission(
4452 android.Manifest.permission.DELETE_CACHE_FILES, null);
4453 // Queue up an async operation since the package deletion may take a little while.
4454 mHandler.post(new Runnable() {
4455 public void run() {
4456 mHandler.removeCallbacks(this);
4457 final boolean succeded;
4458 synchronized (mInstallLock) {
4459 succeded = deleteApplicationCacheFilesLI(packageName);
4460 }
4461 if(observer != null) {
4462 try {
4463 observer.onRemoveCompleted(packageName, succeded);
4464 } catch (RemoteException e) {
4465 Log.i(TAG, "Observer no longer exists.");
4466 }
4467 } //end if observer
4468 } //end run
4469 });
4470 }
4471
4472 private boolean deleteApplicationCacheFilesLI(String packageName) {
4473 if (packageName == null) {
4474 Log.w(TAG, "Attempt to delete null packageName.");
4475 return false;
4476 }
4477 PackageParser.Package p;
4478 synchronized (mPackages) {
4479 p = mPackages.get(packageName);
4480 }
4481 if (p == null) {
4482 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4483 return false;
4484 }
4485 final ApplicationInfo applicationInfo = p.applicationInfo;
4486 if (applicationInfo == null) {
4487 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4488 return false;
4489 }
4490 if (mInstaller != null) {
4491 int retCode = mInstaller.deleteCacheFiles(packageName);
4492 if (retCode < 0) {
4493 Log.w(TAG, "Couldn't remove cache files for package: "
4494 + packageName);
4495 return false;
4496 }
4497 }
4498 return true;
4499 }
4500
4501 public void getPackageSizeInfo(final String packageName,
4502 final IPackageStatsObserver observer) {
4503 mContext.enforceCallingOrSelfPermission(
4504 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4505 // Queue up an async operation since the package deletion may take a little while.
4506 mHandler.post(new Runnable() {
4507 public void run() {
4508 mHandler.removeCallbacks(this);
4509 PackageStats lStats = new PackageStats(packageName);
4510 final boolean succeded;
4511 synchronized (mInstallLock) {
4512 succeded = getPackageSizeInfoLI(packageName, lStats);
4513 }
4514 if(observer != null) {
4515 try {
4516 observer.onGetStatsCompleted(lStats, succeded);
4517 } catch (RemoteException e) {
4518 Log.i(TAG, "Observer no longer exists.");
4519 }
4520 } //end if observer
4521 } //end run
4522 });
4523 }
4524
4525 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4526 if (packageName == null) {
4527 Log.w(TAG, "Attempt to get size of null packageName.");
4528 return false;
4529 }
4530 PackageParser.Package p;
4531 boolean dataOnly = false;
4532 synchronized (mPackages) {
4533 p = mPackages.get(packageName);
4534 if(p == null) {
4535 dataOnly = true;
4536 PackageSetting ps = mSettings.mPackages.get(packageName);
4537 if((ps == null) || (ps.pkg == null)) {
4538 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4539 return false;
4540 }
4541 p = ps.pkg;
4542 }
4543 }
4544 String publicSrcDir = null;
4545 if(!dataOnly) {
4546 final ApplicationInfo applicationInfo = p.applicationInfo;
4547 if (applicationInfo == null) {
4548 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4549 return false;
4550 }
4551 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4552 }
4553 if (mInstaller != null) {
4554 int res = mInstaller.getSizeInfo(packageName, p.mPath,
4555 publicSrcDir, pStats);
4556 if (res < 0) {
4557 return false;
4558 } else {
4559 return true;
4560 }
4561 }
4562 return true;
4563 }
4564
4565
4566 public void addPackageToPreferred(String packageName) {
4567 mContext.enforceCallingOrSelfPermission(
4568 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4569
4570 synchronized (mPackages) {
4571 PackageParser.Package p = mPackages.get(packageName);
4572 if (p == null) {
4573 return;
4574 }
4575 PackageSetting ps = (PackageSetting)p.mExtras;
4576 if (ps != null) {
4577 mSettings.mPreferredPackages.remove(ps);
4578 mSettings.mPreferredPackages.add(0, ps);
4579 updatePreferredIndicesLP();
4580 mSettings.writeLP();
4581 }
4582 }
4583 }
4584
4585 public void removePackageFromPreferred(String packageName) {
4586 mContext.enforceCallingOrSelfPermission(
4587 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4588
4589 synchronized (mPackages) {
4590 PackageParser.Package p = mPackages.get(packageName);
4591 if (p == null) {
4592 return;
4593 }
4594 if (p.mPreferredOrder > 0) {
4595 PackageSetting ps = (PackageSetting)p.mExtras;
4596 if (ps != null) {
4597 mSettings.mPreferredPackages.remove(ps);
4598 p.mPreferredOrder = 0;
4599 updatePreferredIndicesLP();
4600 mSettings.writeLP();
4601 }
4602 }
4603 }
4604 }
4605
4606 private void updatePreferredIndicesLP() {
4607 final ArrayList<PackageSetting> pkgs
4608 = mSettings.mPreferredPackages;
4609 final int N = pkgs.size();
4610 for (int i=0; i<N; i++) {
4611 pkgs.get(i).pkg.mPreferredOrder = N - i;
4612 }
4613 }
4614
4615 public List<PackageInfo> getPreferredPackages(int flags) {
4616 synchronized (mPackages) {
4617 final ArrayList<PackageInfo> res = new ArrayList<PackageInfo>();
4618 final ArrayList<PackageSetting> pref = mSettings.mPreferredPackages;
4619 final int N = pref.size();
4620 for (int i=0; i<N; i++) {
4621 res.add(generatePackageInfo(pref.get(i).pkg, flags));
4622 }
4623 return res;
4624 }
4625 }
4626
4627 public void addPreferredActivity(IntentFilter filter, int match,
4628 ComponentName[] set, ComponentName activity) {
4629 mContext.enforceCallingOrSelfPermission(
4630 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4631
4632 synchronized (mPackages) {
4633 Log.i(TAG, "Adding preferred activity " + activity + ":");
4634 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4635 mSettings.mPreferredActivities.addFilter(
4636 new PreferredActivity(filter, match, set, activity));
4637 mSettings.writeLP();
4638 }
4639 }
4640
Satish Sampath8dbe6122009-06-02 23:35:54 +01004641 public void replacePreferredActivity(IntentFilter filter, int match,
4642 ComponentName[] set, ComponentName activity) {
4643 mContext.enforceCallingOrSelfPermission(
4644 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4645 if (filter.countActions() != 1) {
4646 throw new IllegalArgumentException(
4647 "replacePreferredActivity expects filter to have only 1 action.");
4648 }
4649 if (filter.countCategories() != 1) {
4650 throw new IllegalArgumentException(
4651 "replacePreferredActivity expects filter to have only 1 category.");
4652 }
4653 if (filter.countDataAuthorities() != 0
4654 || filter.countDataPaths() != 0
4655 || filter.countDataSchemes() != 0
4656 || filter.countDataTypes() != 0) {
4657 throw new IllegalArgumentException(
4658 "replacePreferredActivity expects filter to have no data authorities, " +
4659 "paths, schemes or types.");
4660 }
4661 synchronized (mPackages) {
4662 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4663 String action = filter.getAction(0);
4664 String category = filter.getCategory(0);
4665 while (it.hasNext()) {
4666 PreferredActivity pa = it.next();
4667 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
4668 it.remove();
4669 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
4670 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4671 }
4672 }
4673 addPreferredActivity(filter, match, set, activity);
4674 }
4675 }
4676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 public void clearPackagePreferredActivities(String packageName) {
4678 mContext.enforceCallingOrSelfPermission(
4679 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4680
4681 synchronized (mPackages) {
4682 if (clearPackagePreferredActivitiesLP(packageName)) {
4683 mSettings.writeLP();
4684 }
4685 }
4686 }
4687
4688 boolean clearPackagePreferredActivitiesLP(String packageName) {
4689 boolean changed = false;
4690 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4691 while (it.hasNext()) {
4692 PreferredActivity pa = it.next();
4693 if (pa.mActivity.getPackageName().equals(packageName)) {
4694 it.remove();
4695 changed = true;
4696 }
4697 }
4698 return changed;
4699 }
4700
4701 public int getPreferredActivities(List<IntentFilter> outFilters,
4702 List<ComponentName> outActivities, String packageName) {
4703
4704 int num = 0;
4705 synchronized (mPackages) {
4706 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4707 while (it.hasNext()) {
4708 PreferredActivity pa = it.next();
4709 if (packageName == null
4710 || pa.mActivity.getPackageName().equals(packageName)) {
4711 if (outFilters != null) {
4712 outFilters.add(new IntentFilter(pa));
4713 }
4714 if (outActivities != null) {
4715 outActivities.add(pa.mActivity);
4716 }
4717 }
4718 }
4719 }
4720
4721 return num;
4722 }
4723
4724 public void setApplicationEnabledSetting(String appPackageName,
4725 int newState, int flags) {
4726 setEnabledSetting(appPackageName, null, newState, flags);
4727 }
4728
4729 public void setComponentEnabledSetting(ComponentName componentName,
4730 int newState, int flags) {
4731 setEnabledSetting(componentName.getPackageName(),
4732 componentName.getClassName(), newState, flags);
4733 }
4734
4735 private void setEnabledSetting(
4736 final String packageNameStr, String classNameStr, int newState, final int flags) {
4737 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
4738 || newState == COMPONENT_ENABLED_STATE_ENABLED
4739 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
4740 throw new IllegalArgumentException("Invalid new component state: "
4741 + newState);
4742 }
4743 PackageSetting pkgSetting;
4744 final int uid = Binder.getCallingUid();
4745 final int permission = mContext.checkCallingPermission(
4746 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
4747 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4748 int packageUid = -1;
4749 synchronized (mPackages) {
4750 pkgSetting = mSettings.mPackages.get(packageNameStr);
4751 if (pkgSetting == null) {
4752 if (classNameStr == null) {
4753 throw new IllegalArgumentException(
4754 "Unknown package: " + packageNameStr);
4755 }
4756 throw new IllegalArgumentException(
4757 "Unknown component: " + packageNameStr
4758 + "/" + classNameStr);
4759 }
4760 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4761 throw new SecurityException(
4762 "Permission Denial: attempt to change component state from pid="
4763 + Binder.getCallingPid()
4764 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
4765 }
4766 packageUid = pkgSetting.userId;
4767 if (classNameStr == null) {
4768 // We're dealing with an application/package level state change
4769 pkgSetting.enabled = newState;
4770 } else {
4771 // We're dealing with a component level state change
4772 switch (newState) {
4773 case COMPONENT_ENABLED_STATE_ENABLED:
4774 pkgSetting.enableComponentLP(classNameStr);
4775 break;
4776 case COMPONENT_ENABLED_STATE_DISABLED:
4777 pkgSetting.disableComponentLP(classNameStr);
4778 break;
4779 case COMPONENT_ENABLED_STATE_DEFAULT:
4780 pkgSetting.restoreComponentLP(classNameStr);
4781 break;
4782 default:
4783 Log.e(TAG, "Invalid new component state: " + newState);
4784 }
4785 }
4786 mSettings.writeLP();
4787 }
4788
4789 long callingId = Binder.clearCallingIdentity();
4790 try {
4791 Bundle extras = new Bundle(2);
4792 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP,
4793 (flags&PackageManager.DONT_KILL_APP) != 0);
4794 extras.putInt(Intent.EXTRA_UID, packageUid);
4795 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageNameStr, extras);
4796 } finally {
4797 Binder.restoreCallingIdentity(callingId);
4798 }
4799 }
4800
Jacek Surazski65e13172009-04-28 15:26:38 +02004801 public String getInstallerPackageName(String packageName) {
4802 synchronized (mPackages) {
4803 PackageSetting pkg = mSettings.mPackages.get(packageName);
4804 if (pkg == null) {
4805 throw new IllegalArgumentException("Unknown package: " + packageName);
4806 }
4807 return pkg.installerPackageName;
4808 }
4809 }
4810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004811 public int getApplicationEnabledSetting(String appPackageName) {
4812 synchronized (mPackages) {
4813 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
4814 if (pkg == null) {
4815 throw new IllegalArgumentException("Unknown package: " + appPackageName);
4816 }
4817 return pkg.enabled;
4818 }
4819 }
4820
4821 public int getComponentEnabledSetting(ComponentName componentName) {
4822 synchronized (mPackages) {
4823 final String packageNameStr = componentName.getPackageName();
4824 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
4825 if (pkg == null) {
4826 throw new IllegalArgumentException("Unknown component: " + componentName);
4827 }
4828 final String classNameStr = componentName.getClassName();
4829 return pkg.currentEnabledStateLP(classNameStr);
4830 }
4831 }
4832
4833 public void enterSafeMode() {
4834 if (!mSystemReady) {
4835 mSafeMode = true;
4836 }
4837 }
4838
4839 public void systemReady() {
4840 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07004841
4842 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07004843 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07004844 mContext.getContentResolver(),
4845 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07004846 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07004847 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07004848 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07004849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004850 }
4851
4852 public boolean isSafeMode() {
4853 return mSafeMode;
4854 }
4855
4856 public boolean hasSystemUidErrors() {
4857 return mHasSystemUidErrors;
4858 }
4859
4860 static String arrayToString(int[] array) {
4861 StringBuffer buf = new StringBuffer(128);
4862 buf.append('[');
4863 if (array != null) {
4864 for (int i=0; i<array.length; i++) {
4865 if (i > 0) buf.append(", ");
4866 buf.append(array[i]);
4867 }
4868 }
4869 buf.append(']');
4870 return buf.toString();
4871 }
4872
4873 @Override
4874 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4875 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4876 != PackageManager.PERMISSION_GRANTED) {
4877 pw.println("Permission Denial: can't dump ActivityManager from from pid="
4878 + Binder.getCallingPid()
4879 + ", uid=" + Binder.getCallingUid()
4880 + " without permission "
4881 + android.Manifest.permission.DUMP);
4882 return;
4883 }
4884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004885 synchronized (mPackages) {
4886 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004887 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004888 pw.println(" ");
4889 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004890 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 pw.println(" ");
4892 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004893 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004894 pw.println(" ");
4895 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004896 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004897 pw.println(" ");
4898 pw.println("Preferred Packages:");
4899 {
4900 for (PackageSetting ps : mSettings.mPreferredPackages) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004901 pw.print(" "); pw.println(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 }
4903 }
4904 pw.println(" ");
4905 pw.println("Permissions:");
4906 {
4907 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004908 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
4909 pw.print(Integer.toHexString(System.identityHashCode(p)));
4910 pw.println("):");
4911 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
4912 pw.print(" uid="); pw.print(p.uid);
4913 pw.print(" gids="); pw.print(arrayToString(p.gids));
4914 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004915 }
4916 }
4917 pw.println(" ");
4918 pw.println("Packages:");
4919 {
4920 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004921 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
4922 pw.print(Integer.toHexString(System.identityHashCode(ps)));
4923 pw.println("):");
4924 pw.print(" userId="); pw.print(ps.userId);
4925 pw.print(" gids="); pw.println(arrayToString(ps.gids));
4926 pw.print(" sharedUser="); pw.println(ps.sharedUser);
4927 pw.print(" pkg="); pw.println(ps.pkg);
4928 pw.print(" codePath="); pw.println(ps.codePathString);
4929 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004930 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004931 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07004932 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07004933 pw.print(" supportsScreens=[");
4934 boolean first = true;
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07004935 if ((ps.pkg.applicationInfo.flags &
4936 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07004937 if (!first) pw.print(", ");
4938 first = false;
4939 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07004940 }
4941 if ((ps.pkg.applicationInfo.flags &
4942 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07004943 if (!first) pw.print(", ");
4944 first = false;
4945 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07004946 }
4947 if ((ps.pkg.applicationInfo.flags &
4948 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07004949 if (!first) pw.print(", ");
4950 first = false;
4951 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07004952 }
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07004953 if ((ps.pkg.applicationInfo.flags &
4954 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07004955 if (!first) pw.print(", ");
4956 first = false;
4957 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07004958 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07004959 if ((ps.pkg.applicationInfo.flags &
4960 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
4961 if (!first) pw.print(", ");
4962 first = false;
4963 pw.print("anyDensity");
4964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07004966 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004967 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
4968 pw.print(" signatures="); pw.println(ps.signatures);
4969 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
4970 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
4971 pw.print(" installStatus="); pw.print(ps.installStatus);
4972 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004973 if (ps.disabledComponents.size() > 0) {
4974 pw.println(" disabledComponents:");
4975 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004976 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 }
4978 }
4979 if (ps.enabledComponents.size() > 0) {
4980 pw.println(" enabledComponents:");
4981 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004982 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004983 }
4984 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004985 if (ps.grantedPermissions.size() > 0) {
4986 pw.println(" grantedPermissions:");
4987 for (String s : ps.grantedPermissions) {
4988 pw.print(" "); pw.println(s);
4989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004990 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004991 if (ps.loadedPermissions.size() > 0) {
4992 pw.println(" loadedPermissions:");
4993 for (String s : ps.loadedPermissions) {
4994 pw.print(" "); pw.println(s);
4995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004996 }
4997 }
4998 }
4999 pw.println(" ");
5000 pw.println("Shared Users:");
5001 {
5002 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005003 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
5004 pw.print(Integer.toHexString(System.identityHashCode(su)));
5005 pw.println("):");
5006 pw.print(" userId="); pw.print(su.userId);
5007 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005008 pw.println(" grantedPermissions:");
5009 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005010 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011 }
5012 pw.println(" loadedPermissions:");
5013 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005014 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005015 }
5016 }
5017 }
5018 pw.println(" ");
5019 pw.println("Settings parse messages:");
5020 pw.println(mSettings.mReadMessages.toString());
5021 }
5022 }
5023
5024 static final class BasePermission {
5025 final static int TYPE_NORMAL = 0;
5026 final static int TYPE_BUILTIN = 1;
5027 final static int TYPE_DYNAMIC = 2;
5028
5029 final String name;
5030 final String sourcePackage;
5031 final int type;
5032 PackageParser.Permission perm;
5033 PermissionInfo pendingInfo;
5034 int uid;
5035 int[] gids;
5036
5037 BasePermission(String _name, String _sourcePackage, int _type) {
5038 name = _name;
5039 sourcePackage = _sourcePackage;
5040 type = _type;
5041 }
5042 }
5043
5044 static class PackageSignatures {
5045 private Signature[] mSignatures;
5046
5047 PackageSignatures(Signature[] sigs) {
5048 assignSignatures(sigs);
5049 }
5050
5051 PackageSignatures() {
5052 }
5053
5054 void writeXml(XmlSerializer serializer, String tagName,
5055 ArrayList<Signature> pastSignatures) throws IOException {
5056 if (mSignatures == null) {
5057 return;
5058 }
5059 serializer.startTag(null, tagName);
5060 serializer.attribute(null, "count",
5061 Integer.toString(mSignatures.length));
5062 for (int i=0; i<mSignatures.length; i++) {
5063 serializer.startTag(null, "cert");
5064 final Signature sig = mSignatures[i];
5065 final int sigHash = sig.hashCode();
5066 final int numPast = pastSignatures.size();
5067 int j;
5068 for (j=0; j<numPast; j++) {
5069 Signature pastSig = pastSignatures.get(j);
5070 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
5071 serializer.attribute(null, "index", Integer.toString(j));
5072 break;
5073 }
5074 }
5075 if (j >= numPast) {
5076 pastSignatures.add(sig);
5077 serializer.attribute(null, "index", Integer.toString(numPast));
5078 serializer.attribute(null, "key", sig.toCharsString());
5079 }
5080 serializer.endTag(null, "cert");
5081 }
5082 serializer.endTag(null, tagName);
5083 }
5084
5085 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
5086 throws IOException, XmlPullParserException {
5087 String countStr = parser.getAttributeValue(null, "count");
5088 if (countStr == null) {
5089 reportSettingsProblem(Log.WARN,
5090 "Error in package manager settings: <signatures> has"
5091 + " no count at " + parser.getPositionDescription());
5092 XmlUtils.skipCurrentTag(parser);
5093 }
5094 final int count = Integer.parseInt(countStr);
5095 mSignatures = new Signature[count];
5096 int pos = 0;
5097
5098 int outerDepth = parser.getDepth();
5099 int type;
5100 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5101 && (type != XmlPullParser.END_TAG
5102 || parser.getDepth() > outerDepth)) {
5103 if (type == XmlPullParser.END_TAG
5104 || type == XmlPullParser.TEXT) {
5105 continue;
5106 }
5107
5108 String tagName = parser.getName();
5109 if (tagName.equals("cert")) {
5110 if (pos < count) {
5111 String index = parser.getAttributeValue(null, "index");
5112 if (index != null) {
5113 try {
5114 int idx = Integer.parseInt(index);
5115 String key = parser.getAttributeValue(null, "key");
5116 if (key == null) {
5117 if (idx >= 0 && idx < pastSignatures.size()) {
5118 Signature sig = pastSignatures.get(idx);
5119 if (sig != null) {
5120 mSignatures[pos] = pastSignatures.get(idx);
5121 pos++;
5122 } else {
5123 reportSettingsProblem(Log.WARN,
5124 "Error in package manager settings: <cert> "
5125 + "index " + index + " is not defined at "
5126 + parser.getPositionDescription());
5127 }
5128 } else {
5129 reportSettingsProblem(Log.WARN,
5130 "Error in package manager settings: <cert> "
5131 + "index " + index + " is out of bounds at "
5132 + parser.getPositionDescription());
5133 }
5134 } else {
5135 while (pastSignatures.size() <= idx) {
5136 pastSignatures.add(null);
5137 }
5138 Signature sig = new Signature(key);
5139 pastSignatures.set(idx, sig);
5140 mSignatures[pos] = sig;
5141 pos++;
5142 }
5143 } catch (NumberFormatException e) {
5144 reportSettingsProblem(Log.WARN,
5145 "Error in package manager settings: <cert> "
5146 + "index " + index + " is not a number at "
5147 + parser.getPositionDescription());
5148 }
5149 } else {
5150 reportSettingsProblem(Log.WARN,
5151 "Error in package manager settings: <cert> has"
5152 + " no index at " + parser.getPositionDescription());
5153 }
5154 } else {
5155 reportSettingsProblem(Log.WARN,
5156 "Error in package manager settings: too "
5157 + "many <cert> tags, expected " + count
5158 + " at " + parser.getPositionDescription());
5159 }
5160 } else {
5161 reportSettingsProblem(Log.WARN,
5162 "Unknown element under <cert>: "
5163 + parser.getName());
5164 }
5165 XmlUtils.skipCurrentTag(parser);
5166 }
5167
5168 if (pos < count) {
5169 // Should never happen -- there is an error in the written
5170 // settings -- but if it does we don't want to generate
5171 // a bad array.
5172 Signature[] newSigs = new Signature[pos];
5173 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
5174 mSignatures = newSigs;
5175 }
5176 }
5177
5178 /**
5179 * If any of the given 'sigs' is contained in the existing signatures,
5180 * then completely replace the current signatures with the ones in
5181 * 'sigs'. This is used for updating an existing package to a newly
5182 * installed version.
5183 */
5184 boolean updateSignatures(Signature[] sigs, boolean update) {
5185 if (mSignatures == null) {
5186 if (update) {
5187 assignSignatures(sigs);
5188 }
5189 return true;
5190 }
5191 if (sigs == null) {
5192 return false;
5193 }
5194
5195 for (int i=0; i<sigs.length; i++) {
5196 Signature sig = sigs[i];
5197 for (int j=0; j<mSignatures.length; j++) {
5198 if (mSignatures[j].equals(sig)) {
5199 if (update) {
5200 assignSignatures(sigs);
5201 }
5202 return true;
5203 }
5204 }
5205 }
5206 return false;
5207 }
5208
5209 /**
5210 * If any of the given 'sigs' is contained in the existing signatures,
5211 * then add in any new signatures found in 'sigs'. This is used for
5212 * including a new package into an existing shared user id.
5213 */
5214 boolean mergeSignatures(Signature[] sigs, boolean update) {
5215 if (mSignatures == null) {
5216 if (update) {
5217 assignSignatures(sigs);
5218 }
5219 return true;
5220 }
5221 if (sigs == null) {
5222 return false;
5223 }
5224
5225 Signature[] added = null;
5226 int addedCount = 0;
5227 boolean haveMatch = false;
5228 for (int i=0; i<sigs.length; i++) {
5229 Signature sig = sigs[i];
5230 boolean found = false;
5231 for (int j=0; j<mSignatures.length; j++) {
5232 if (mSignatures[j].equals(sig)) {
5233 found = true;
5234 haveMatch = true;
5235 break;
5236 }
5237 }
5238
5239 if (!found) {
5240 if (added == null) {
5241 added = new Signature[sigs.length];
5242 }
5243 added[i] = sig;
5244 addedCount++;
5245 }
5246 }
5247
5248 if (!haveMatch) {
5249 // Nothing matched -- reject the new signatures.
5250 return false;
5251 }
5252 if (added == null) {
5253 // Completely matched -- nothing else to do.
5254 return true;
5255 }
5256
5257 // Add additional signatures in.
5258 if (update) {
5259 Signature[] total = new Signature[addedCount+mSignatures.length];
5260 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5261 int j = mSignatures.length;
5262 for (int i=0; i<added.length; i++) {
5263 if (added[i] != null) {
5264 total[j] = added[i];
5265 j++;
5266 }
5267 }
5268 mSignatures = total;
5269 }
5270 return true;
5271 }
5272
5273 private void assignSignatures(Signature[] sigs) {
5274 if (sigs == null) {
5275 mSignatures = null;
5276 return;
5277 }
5278 mSignatures = new Signature[sigs.length];
5279 for (int i=0; i<sigs.length; i++) {
5280 mSignatures[i] = sigs[i];
5281 }
5282 }
5283
5284 @Override
5285 public String toString() {
5286 StringBuffer buf = new StringBuffer(128);
5287 buf.append("PackageSignatures{");
5288 buf.append(Integer.toHexString(System.identityHashCode(this)));
5289 buf.append(" [");
5290 if (mSignatures != null) {
5291 for (int i=0; i<mSignatures.length; i++) {
5292 if (i > 0) buf.append(", ");
5293 buf.append(Integer.toHexString(
5294 System.identityHashCode(mSignatures[i])));
5295 }
5296 }
5297 buf.append("]}");
5298 return buf.toString();
5299 }
5300 }
5301
5302 static class PreferredActivity extends IntentFilter {
5303 final int mMatch;
5304 final String[] mSetPackages;
5305 final String[] mSetClasses;
5306 final String[] mSetComponents;
5307 final ComponentName mActivity;
5308 final String mShortActivity;
5309 String mParseError;
5310
5311 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5312 ComponentName activity) {
5313 super(filter);
5314 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5315 mActivity = activity;
5316 mShortActivity = activity.flattenToShortString();
5317 mParseError = null;
5318 if (set != null) {
5319 final int N = set.length;
5320 String[] myPackages = new String[N];
5321 String[] myClasses = new String[N];
5322 String[] myComponents = new String[N];
5323 for (int i=0; i<N; i++) {
5324 ComponentName cn = set[i];
5325 if (cn == null) {
5326 mSetPackages = null;
5327 mSetClasses = null;
5328 mSetComponents = null;
5329 return;
5330 }
5331 myPackages[i] = cn.getPackageName().intern();
5332 myClasses[i] = cn.getClassName().intern();
5333 myComponents[i] = cn.flattenToShortString().intern();
5334 }
5335 mSetPackages = myPackages;
5336 mSetClasses = myClasses;
5337 mSetComponents = myComponents;
5338 } else {
5339 mSetPackages = null;
5340 mSetClasses = null;
5341 mSetComponents = null;
5342 }
5343 }
5344
5345 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5346 IOException {
5347 mShortActivity = parser.getAttributeValue(null, "name");
5348 mActivity = ComponentName.unflattenFromString(mShortActivity);
5349 if (mActivity == null) {
5350 mParseError = "Bad activity name " + mShortActivity;
5351 }
5352 String matchStr = parser.getAttributeValue(null, "match");
5353 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5354 String setCountStr = parser.getAttributeValue(null, "set");
5355 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5356
5357 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5358 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5359 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5360
5361 int setPos = 0;
5362
5363 int outerDepth = parser.getDepth();
5364 int type;
5365 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5366 && (type != XmlPullParser.END_TAG
5367 || parser.getDepth() > outerDepth)) {
5368 if (type == XmlPullParser.END_TAG
5369 || type == XmlPullParser.TEXT) {
5370 continue;
5371 }
5372
5373 String tagName = parser.getName();
5374 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5375 // + parser.getDepth() + " tag=" + tagName);
5376 if (tagName.equals("set")) {
5377 String name = parser.getAttributeValue(null, "name");
5378 if (name == null) {
5379 if (mParseError == null) {
5380 mParseError = "No name in set tag in preferred activity "
5381 + mShortActivity;
5382 }
5383 } else if (setPos >= setCount) {
5384 if (mParseError == null) {
5385 mParseError = "Too many set tags in preferred activity "
5386 + mShortActivity;
5387 }
5388 } else {
5389 ComponentName cn = ComponentName.unflattenFromString(name);
5390 if (cn == null) {
5391 if (mParseError == null) {
5392 mParseError = "Bad set name " + name + " in preferred activity "
5393 + mShortActivity;
5394 }
5395 } else {
5396 myPackages[setPos] = cn.getPackageName();
5397 myClasses[setPos] = cn.getClassName();
5398 myComponents[setPos] = name;
5399 setPos++;
5400 }
5401 }
5402 XmlUtils.skipCurrentTag(parser);
5403 } else if (tagName.equals("filter")) {
5404 //Log.i(TAG, "Starting to parse filter...");
5405 readFromXml(parser);
5406 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5407 // + parser.getDepth() + " tag=" + parser.getName());
5408 } else {
5409 reportSettingsProblem(Log.WARN,
5410 "Unknown element under <preferred-activities>: "
5411 + parser.getName());
5412 XmlUtils.skipCurrentTag(parser);
5413 }
5414 }
5415
5416 if (setPos != setCount) {
5417 if (mParseError == null) {
5418 mParseError = "Not enough set tags (expected " + setCount
5419 + " but found " + setPos + ") in " + mShortActivity;
5420 }
5421 }
5422
5423 mSetPackages = myPackages;
5424 mSetClasses = myClasses;
5425 mSetComponents = myComponents;
5426 }
5427
5428 public void writeToXml(XmlSerializer serializer) throws IOException {
5429 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5430 serializer.attribute(null, "name", mShortActivity);
5431 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5432 serializer.attribute(null, "set", Integer.toString(NS));
5433 for (int s=0; s<NS; s++) {
5434 serializer.startTag(null, "set");
5435 serializer.attribute(null, "name", mSetComponents[s]);
5436 serializer.endTag(null, "set");
5437 }
5438 serializer.startTag(null, "filter");
5439 super.writeToXml(serializer);
5440 serializer.endTag(null, "filter");
5441 }
5442
5443 boolean sameSet(List<ResolveInfo> query, int priority) {
5444 if (mSetPackages == null) return false;
5445 final int NQ = query.size();
5446 final int NS = mSetPackages.length;
5447 int numMatch = 0;
5448 for (int i=0; i<NQ; i++) {
5449 ResolveInfo ri = query.get(i);
5450 if (ri.priority != priority) continue;
5451 ActivityInfo ai = ri.activityInfo;
5452 boolean good = false;
5453 for (int j=0; j<NS; j++) {
5454 if (mSetPackages[j].equals(ai.packageName)
5455 && mSetClasses[j].equals(ai.name)) {
5456 numMatch++;
5457 good = true;
5458 break;
5459 }
5460 }
5461 if (!good) return false;
5462 }
5463 return numMatch == NS;
5464 }
5465 }
5466
5467 static class GrantedPermissions {
5468 final int pkgFlags;
5469
5470 HashSet<String> grantedPermissions = new HashSet<String>();
5471 int[] gids;
5472
5473 HashSet<String> loadedPermissions = new HashSet<String>();
5474
5475 GrantedPermissions(int pkgFlags) {
5476 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5477 }
5478 }
5479
5480 /**
5481 * Settings base class for pending and resolved classes.
5482 */
5483 static class PackageSettingBase extends GrantedPermissions {
5484 final String name;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005485 File codePath;
5486 String codePathString;
5487 File resourcePath;
5488 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 private long timeStamp;
5490 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005491 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492
5493 PackageSignatures signatures = new PackageSignatures();
5494
5495 boolean permissionsFixed;
5496
5497 /* Explicitly disabled components */
5498 HashSet<String> disabledComponents = new HashSet<String>(0);
5499 /* Explicitly enabled components */
5500 HashSet<String> enabledComponents = new HashSet<String>(0);
5501 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5502 int installStatus = PKG_INSTALL_COMPLETE;
Jacek Surazski65e13172009-04-28 15:26:38 +02005503
5504 /* package name of the app that installed this package */
5505 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506
5507 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005508 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 super(pkgFlags);
5510 this.name = name;
5511 this.codePath = codePath;
5512 this.codePathString = codePath.toString();
5513 this.resourcePath = resourcePath;
5514 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005515 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 }
5517
Jacek Surazski65e13172009-04-28 15:26:38 +02005518 public void setInstallerPackageName(String packageName) {
5519 installerPackageName = packageName;
5520 }
5521
5522 String getInstallerPackageName() {
5523 return installerPackageName;
5524 }
5525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 public void setInstallStatus(int newStatus) {
5527 installStatus = newStatus;
5528 }
5529
5530 public int getInstallStatus() {
5531 return installStatus;
5532 }
5533
5534 public void setTimeStamp(long newStamp) {
5535 if (newStamp != timeStamp) {
5536 timeStamp = newStamp;
5537 timeStampString = Long.toString(newStamp);
5538 }
5539 }
5540
5541 public void setTimeStamp(long newStamp, String newStampStr) {
5542 timeStamp = newStamp;
5543 timeStampString = newStampStr;
5544 }
5545
5546 public long getTimeStamp() {
5547 return timeStamp;
5548 }
5549
5550 public String getTimeStampStr() {
5551 return timeStampString;
5552 }
5553
5554 public void copyFrom(PackageSettingBase base) {
5555 grantedPermissions = base.grantedPermissions;
5556 gids = base.gids;
5557 loadedPermissions = base.loadedPermissions;
5558
5559 timeStamp = base.timeStamp;
5560 timeStampString = base.timeStampString;
5561 signatures = base.signatures;
5562 permissionsFixed = base.permissionsFixed;
5563 disabledComponents = base.disabledComponents;
5564 enabledComponents = base.enabledComponents;
5565 enabled = base.enabled;
5566 installStatus = base.installStatus;
5567 }
5568
5569 void enableComponentLP(String componentClassName) {
5570 disabledComponents.remove(componentClassName);
5571 enabledComponents.add(componentClassName);
5572 }
5573
5574 void disableComponentLP(String componentClassName) {
5575 enabledComponents.remove(componentClassName);
5576 disabledComponents.add(componentClassName);
5577 }
5578
5579 void restoreComponentLP(String componentClassName) {
5580 enabledComponents.remove(componentClassName);
5581 disabledComponents.remove(componentClassName);
5582 }
5583
5584 int currentEnabledStateLP(String componentName) {
5585 if (enabledComponents.contains(componentName)) {
5586 return COMPONENT_ENABLED_STATE_ENABLED;
5587 } else if (disabledComponents.contains(componentName)) {
5588 return COMPONENT_ENABLED_STATE_DISABLED;
5589 } else {
5590 return COMPONENT_ENABLED_STATE_DEFAULT;
5591 }
5592 }
5593 }
5594
5595 /**
5596 * Settings data for a particular package we know about.
5597 */
5598 static final class PackageSetting extends PackageSettingBase {
5599 int userId;
5600 PackageParser.Package pkg;
5601 SharedUserSetting sharedUser;
5602
5603 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005604 int pVersionCode, int pkgFlags) {
5605 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 }
5607
5608 @Override
5609 public String toString() {
5610 return "PackageSetting{"
5611 + Integer.toHexString(System.identityHashCode(this))
5612 + " " + name + "/" + userId + "}";
5613 }
5614 }
5615
5616 /**
5617 * Settings data for a particular shared user ID we know about.
5618 */
5619 static final class SharedUserSetting extends GrantedPermissions {
5620 final String name;
5621 int userId;
5622 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
5623 final PackageSignatures signatures = new PackageSignatures();
5624
5625 SharedUserSetting(String _name, int _pkgFlags) {
5626 super(_pkgFlags);
5627 name = _name;
5628 }
5629
5630 @Override
5631 public String toString() {
5632 return "SharedUserSetting{"
5633 + Integer.toHexString(System.identityHashCode(this))
5634 + " " + name + "/" + userId + "}";
5635 }
5636 }
5637
5638 /**
5639 * Holds information about dynamic settings.
5640 */
5641 private static final class Settings {
5642 private final File mSettingsFilename;
5643 private final File mBackupSettingsFilename;
5644 private final HashMap<String, PackageSetting> mPackages =
5645 new HashMap<String, PackageSetting>();
5646 // The user's preferred packages/applications, in order of preference.
5647 // First is the most preferred.
5648 private final ArrayList<PackageSetting> mPreferredPackages =
5649 new ArrayList<PackageSetting>();
5650 // List of replaced system applications
5651 final HashMap<String, PackageSetting> mDisabledSysPackages =
5652 new HashMap<String, PackageSetting>();
5653
5654 // The user's preferred activities associated with particular intent
5655 // filters.
5656 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
5657 new IntentResolver<PreferredActivity, PreferredActivity>() {
5658 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005659 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005661 out.print(prefix); out.print(
5662 Integer.toHexString(System.identityHashCode(filter)));
5663 out.print(' ');
5664 out.print(filter.mActivity.flattenToShortString());
5665 out.print(" match=0x");
5666 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005668 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005670 out.print(prefix); out.print(" ");
5671 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 }
5673 }
5674 }
5675 };
5676 private final HashMap<String, SharedUserSetting> mSharedUsers =
5677 new HashMap<String, SharedUserSetting>();
5678 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
5679 private final SparseArray<Object> mOtherUserIds =
5680 new SparseArray<Object>();
5681
5682 // For reading/writing settings file.
5683 private final ArrayList<Signature> mPastSignatures =
5684 new ArrayList<Signature>();
5685
5686 // Mapping from permission names to info about them.
5687 final HashMap<String, BasePermission> mPermissions =
5688 new HashMap<String, BasePermission>();
5689
5690 // Mapping from permission tree names to info about them.
5691 final HashMap<String, BasePermission> mPermissionTrees =
5692 new HashMap<String, BasePermission>();
5693
5694 private final ArrayList<String> mPendingPreferredPackages
5695 = new ArrayList<String>();
5696
5697 private final StringBuilder mReadMessages = new StringBuilder();
5698
5699 private static final class PendingPackage extends PackageSettingBase {
5700 final int sharedId;
5701
5702 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005703 int sharedId, int pVersionCode, int pkgFlags) {
5704 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 this.sharedId = sharedId;
5706 }
5707 }
5708 private final ArrayList<PendingPackage> mPendingPackages
5709 = new ArrayList<PendingPackage>();
5710
5711 Settings() {
5712 File dataDir = Environment.getDataDirectory();
5713 File systemDir = new File(dataDir, "system");
5714 systemDir.mkdirs();
5715 FileUtils.setPermissions(systemDir.toString(),
5716 FileUtils.S_IRWXU|FileUtils.S_IRWXG
5717 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
5718 -1, -1);
5719 mSettingsFilename = new File(systemDir, "packages.xml");
5720 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
5721 }
5722
5723 PackageSetting getPackageLP(PackageParser.Package pkg,
5724 SharedUserSetting sharedUser, File codePath, File resourcePath,
5725 int pkgFlags, boolean create, boolean add) {
5726 final String name = pkg.packageName;
5727 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005728 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 return p;
5730 }
5731
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005732 PackageSetting peekPackageLP(String name) {
5733 return mPackages.get(name);
5734 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005735 PackageSetting p = mPackages.get(name);
5736 if (p != null && p.codePath.getPath().equals(codePath)) {
5737 return p;
5738 }
5739 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005740 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005741 }
5742
5743 void setInstallStatus(String pkgName, int status) {
5744 PackageSetting p = mPackages.get(pkgName);
5745 if(p != null) {
5746 if(p.getInstallStatus() != status) {
5747 p.setInstallStatus(status);
5748 }
5749 }
5750 }
5751
Jacek Surazski65e13172009-04-28 15:26:38 +02005752 void setInstallerPackageName(String pkgName,
5753 String installerPkgName) {
5754 PackageSetting p = mPackages.get(pkgName);
5755 if(p != null) {
5756 p.setInstallerPackageName(installerPkgName);
5757 }
5758 }
5759
5760 String getInstallerPackageName(String pkgName) {
5761 PackageSetting p = mPackages.get(pkgName);
5762 return (p == null) ? null : p.getInstallerPackageName();
5763 }
5764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 int getInstallStatus(String pkgName) {
5766 PackageSetting p = mPackages.get(pkgName);
5767 if(p != null) {
5768 return p.getInstallStatus();
5769 }
5770 return -1;
5771 }
5772
5773 SharedUserSetting getSharedUserLP(String name,
5774 int pkgFlags, boolean create) {
5775 SharedUserSetting s = mSharedUsers.get(name);
5776 if (s == null) {
5777 if (!create) {
5778 return null;
5779 }
5780 s = new SharedUserSetting(name, pkgFlags);
5781 if (MULTIPLE_APPLICATION_UIDS) {
5782 s.userId = newUserIdLP(s);
5783 } else {
5784 s.userId = FIRST_APPLICATION_UID;
5785 }
5786 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
5787 // < 0 means we couldn't assign a userid; fall out and return
5788 // s, which is currently null
5789 if (s.userId >= 0) {
5790 mSharedUsers.put(name, s);
5791 }
5792 }
5793
5794 return s;
5795 }
5796
5797 int disableSystemPackageLP(String name) {
5798 PackageSetting p = mPackages.get(name);
5799 if(p == null) {
5800 Log.w(TAG, "Package:"+name+" is not an installed package");
5801 return -1;
5802 }
5803 PackageSetting dp = mDisabledSysPackages.get(name);
5804 // always make sure the system package code and resource paths dont change
5805 if(dp == null) {
5806 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
5807 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5808 }
5809 mDisabledSysPackages.put(name, p);
5810 }
5811 return removePackageLP(name);
5812 }
5813
5814 PackageSetting enableSystemPackageLP(String name) {
5815 PackageSetting p = mDisabledSysPackages.get(name);
5816 if(p == null) {
5817 Log.w(TAG, "Package:"+name+" is not disabled");
5818 return null;
5819 }
5820 // Reset flag in ApplicationInfo object
5821 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
5822 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5823 }
5824 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005825 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 mDisabledSysPackages.remove(name);
5827 return ret;
5828 }
5829
5830 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005831 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 PackageSetting p = mPackages.get(name);
5833 if (p != null) {
5834 if (p.userId == uid) {
5835 return p;
5836 }
5837 reportSettingsProblem(Log.ERROR,
5838 "Adding duplicate package, keeping first: " + name);
5839 return null;
5840 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005841 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005842 p.userId = uid;
5843 if (addUserIdLP(uid, p, name)) {
5844 mPackages.put(name, p);
5845 return p;
5846 }
5847 return null;
5848 }
5849
5850 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
5851 SharedUserSetting s = mSharedUsers.get(name);
5852 if (s != null) {
5853 if (s.userId == uid) {
5854 return s;
5855 }
5856 reportSettingsProblem(Log.ERROR,
5857 "Adding duplicate shared user, keeping first: " + name);
5858 return null;
5859 }
5860 s = new SharedUserSetting(name, pkgFlags);
5861 s.userId = uid;
5862 if (addUserIdLP(uid, s, name)) {
5863 mSharedUsers.put(name, s);
5864 return s;
5865 }
5866 return null;
5867 }
5868
5869 private PackageSetting getPackageLP(String name,
5870 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005871 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 PackageSetting p = mPackages.get(name);
5873 if (p != null) {
5874 if (!p.codePath.equals(codePath)) {
5875 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005876 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07005877 // This is an updated system app with versions in both system
5878 // and data partition. Just let the most recent version
5879 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005880 Log.w(TAG, "Trying to update system app code path from " +
5881 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005882 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07005883 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07005884 reportSettingsProblem(Log.WARN,
5885 "Package " + name + " codePath changed from " + p.codePath
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07005886 + " to " + codePath + "; Retaining data and using new code from " +
5887 codePath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 }
5889 } else if (p.sharedUser != sharedUser) {
5890 reportSettingsProblem(Log.WARN,
5891 "Package " + name + " shared user changed from "
5892 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
5893 + " to "
5894 + (sharedUser != null ? sharedUser.name : "<nothing>")
5895 + "; replacing with new");
5896 p = null;
5897 }
5898 }
5899 if (p == null) {
5900 // Create a new PackageSettings entry. this can end up here because
5901 // of code path mismatch or user id mismatch of an updated system partition
5902 if (!create) {
5903 return null;
5904 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005905 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07005907 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005908 if (sharedUser != null) {
5909 p.userId = sharedUser.userId;
5910 } else if (MULTIPLE_APPLICATION_UIDS) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005911 // Clone the setting here for disabled system packages
5912 PackageSetting dis = mDisabledSysPackages.get(name);
5913 if (dis != null) {
5914 // For disabled packages a new setting is created
5915 // from the existing user id. This still has to be
5916 // added to list of user id's
5917 // Copy signatures from previous setting
5918 if (dis.signatures.mSignatures != null) {
5919 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
5920 }
5921 p.userId = dis.userId;
5922 // Clone permissions
5923 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
5924 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
5925 // Clone component info
5926 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
5927 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
5928 // Add new setting to list of user ids
5929 addUserIdLP(p.userId, p, name);
5930 } else {
5931 // Assign new user id
5932 p.userId = newUserIdLP(p);
5933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 } else {
5935 p.userId = FIRST_APPLICATION_UID;
5936 }
5937 if (p.userId < 0) {
5938 reportSettingsProblem(Log.WARN,
5939 "Package " + name + " could not be assigned a valid uid");
5940 return null;
5941 }
5942 if (add) {
5943 // Finish adding new package by adding it and updating shared
5944 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005945 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 }
5947 }
5948 return p;
5949 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005950
5951 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg,
5952 File codePath, File resourcePath) {
5953 p.pkg = pkg;
5954 // Update code path if needed
5955 if (!codePath.toString().equalsIgnoreCase(p.codePathString)) {
5956 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
5957 " changing form " + p.codePathString + " to " + codePath);
5958 p.codePath = codePath;
5959 p.codePathString = codePath.toString();
5960 }
5961 //Update resource path if needed
5962 if (!resourcePath.toString().equalsIgnoreCase(p.resourcePathString)) {
5963 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
5964 " changing form " + p.resourcePathString + " to " + resourcePath);
5965 p.resourcePath = resourcePath;
5966 p.resourcePathString = resourcePath.toString();
5967 }
5968 // Update version code if needed
5969 if (pkg.mVersionCode != p.versionCode) {
5970 p.versionCode = pkg.mVersionCode;
5971 }
5972 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
5973 }
5974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 // Utility method that adds a PackageSetting to mPackages and
5976 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005977 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 SharedUserSetting sharedUser) {
5979 mPackages.put(name, p);
5980 if (sharedUser != null) {
5981 if (p.sharedUser != null && p.sharedUser != sharedUser) {
5982 reportSettingsProblem(Log.ERROR,
5983 "Package " + p.name + " was user "
5984 + p.sharedUser + " but is now " + sharedUser
5985 + "; I am not changing its files so it will probably fail!");
5986 p.sharedUser.packages.remove(p);
5987 } else if (p.userId != sharedUser.userId) {
5988 reportSettingsProblem(Log.ERROR,
5989 "Package " + p.name + " was user id " + p.userId
5990 + " but is now user " + sharedUser
5991 + " with id " + sharedUser.userId
5992 + "; I am not changing its files so it will probably fail!");
5993 }
5994
5995 sharedUser.packages.add(p);
5996 p.sharedUser = sharedUser;
5997 p.userId = sharedUser.userId;
5998 }
5999 }
6000
6001 private void updateSharedUserPerms (PackageSetting deletedPs) {
6002 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
6003 Log.i(TAG, "Trying to update info for null package. Just ignoring");
6004 return;
6005 }
6006 // No sharedUserId
6007 if (deletedPs.sharedUser == null) {
6008 return;
6009 }
6010 SharedUserSetting sus = deletedPs.sharedUser;
6011 // Update permissions
6012 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
6013 boolean used = false;
6014 if (!sus.grantedPermissions.contains (eachPerm)) {
6015 continue;
6016 }
6017 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapub97b8f82009-06-19 15:09:18 -07006018 if (pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 used = true;
6020 break;
6021 }
6022 }
6023 if (!used) {
6024 // can safely delete this permission from list
6025 sus.grantedPermissions.remove(eachPerm);
6026 sus.loadedPermissions.remove(eachPerm);
6027 }
6028 }
6029 // Update gids
6030 int newGids[] = null;
6031 for (PackageSetting pkg:sus.packages) {
6032 newGids = appendInts(newGids, pkg.gids);
6033 }
6034 sus.gids = newGids;
6035 }
6036
6037 private int removePackageLP(String name) {
6038 PackageSetting p = mPackages.get(name);
6039 if (p != null) {
6040 mPackages.remove(name);
6041 if (p.sharedUser != null) {
6042 p.sharedUser.packages.remove(p);
6043 if (p.sharedUser.packages.size() == 0) {
6044 mSharedUsers.remove(p.sharedUser.name);
6045 removeUserIdLP(p.sharedUser.userId);
6046 return p.sharedUser.userId;
6047 }
6048 } else {
6049 removeUserIdLP(p.userId);
6050 return p.userId;
6051 }
6052 }
6053 return -1;
6054 }
6055
6056 private boolean addUserIdLP(int uid, Object obj, Object name) {
6057 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
6058 return false;
6059 }
6060
6061 if (uid >= FIRST_APPLICATION_UID) {
6062 int N = mUserIds.size();
6063 final int index = uid - FIRST_APPLICATION_UID;
6064 while (index >= N) {
6065 mUserIds.add(null);
6066 N++;
6067 }
6068 if (mUserIds.get(index) != null) {
6069 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006070 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 + " name=" + name);
6072 return false;
6073 }
6074 mUserIds.set(index, obj);
6075 } else {
6076 if (mOtherUserIds.get(uid) != null) {
6077 reportSettingsProblem(Log.ERROR,
6078 "Adding duplicate shared id: " + uid
6079 + " name=" + name);
6080 return false;
6081 }
6082 mOtherUserIds.put(uid, obj);
6083 }
6084 return true;
6085 }
6086
6087 public Object getUserIdLP(int uid) {
6088 if (uid >= FIRST_APPLICATION_UID) {
6089 int N = mUserIds.size();
6090 final int index = uid - FIRST_APPLICATION_UID;
6091 return index < N ? mUserIds.get(index) : null;
6092 } else {
6093 return mOtherUserIds.get(uid);
6094 }
6095 }
6096
6097 private void removeUserIdLP(int uid) {
6098 if (uid >= FIRST_APPLICATION_UID) {
6099 int N = mUserIds.size();
6100 final int index = uid - FIRST_APPLICATION_UID;
6101 if (index < N) mUserIds.set(index, null);
6102 } else {
6103 mOtherUserIds.remove(uid);
6104 }
6105 }
6106
6107 void writeLP() {
6108 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
6109
6110 // Keep the old settings around until we know the new ones have
6111 // been successfully written.
6112 if (mSettingsFilename.exists()) {
6113 if (mBackupSettingsFilename.exists()) {
6114 mBackupSettingsFilename.delete();
6115 }
6116 mSettingsFilename.renameTo(mBackupSettingsFilename);
6117 }
6118
6119 mPastSignatures.clear();
6120
6121 try {
6122 FileOutputStream str = new FileOutputStream(mSettingsFilename);
6123
6124 //XmlSerializer serializer = XmlUtils.serializerInstance();
6125 XmlSerializer serializer = new FastXmlSerializer();
6126 serializer.setOutput(str, "utf-8");
6127 serializer.startDocument(null, true);
6128 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
6129
6130 serializer.startTag(null, "packages");
6131
6132 serializer.startTag(null, "permission-trees");
6133 for (BasePermission bp : mPermissionTrees.values()) {
6134 writePermission(serializer, bp);
6135 }
6136 serializer.endTag(null, "permission-trees");
6137
6138 serializer.startTag(null, "permissions");
6139 for (BasePermission bp : mPermissions.values()) {
6140 writePermission(serializer, bp);
6141 }
6142 serializer.endTag(null, "permissions");
6143
6144 for (PackageSetting pkg : mPackages.values()) {
6145 writePackage(serializer, pkg);
6146 }
6147
6148 for (PackageSetting pkg : mDisabledSysPackages.values()) {
6149 writeDisabledSysPackage(serializer, pkg);
6150 }
6151
6152 serializer.startTag(null, "preferred-packages");
6153 int N = mPreferredPackages.size();
6154 for (int i=0; i<N; i++) {
6155 PackageSetting pkg = mPreferredPackages.get(i);
6156 serializer.startTag(null, "item");
6157 serializer.attribute(null, "name", pkg.name);
6158 serializer.endTag(null, "item");
6159 }
6160 serializer.endTag(null, "preferred-packages");
6161
6162 serializer.startTag(null, "preferred-activities");
6163 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
6164 serializer.startTag(null, "item");
6165 pa.writeToXml(serializer);
6166 serializer.endTag(null, "item");
6167 }
6168 serializer.endTag(null, "preferred-activities");
6169
6170 for (SharedUserSetting usr : mSharedUsers.values()) {
6171 serializer.startTag(null, "shared-user");
6172 serializer.attribute(null, "name", usr.name);
6173 serializer.attribute(null, "userId",
6174 Integer.toString(usr.userId));
6175 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
6176 serializer.startTag(null, "perms");
6177 for (String name : usr.grantedPermissions) {
6178 serializer.startTag(null, "item");
6179 serializer.attribute(null, "name", name);
6180 serializer.endTag(null, "item");
6181 }
6182 serializer.endTag(null, "perms");
6183 serializer.endTag(null, "shared-user");
6184 }
6185
6186 serializer.endTag(null, "packages");
6187
6188 serializer.endDocument();
6189
6190 str.flush();
6191 str.close();
6192
6193 // New settings successfully written, old ones are no longer
6194 // needed.
6195 mBackupSettingsFilename.delete();
6196 FileUtils.setPermissions(mSettingsFilename.toString(),
6197 FileUtils.S_IRUSR|FileUtils.S_IWUSR
6198 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
6199 |FileUtils.S_IROTH,
6200 -1, -1);
6201
6202 } catch(XmlPullParserException e) {
6203 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
6204
6205 } catch(java.io.IOException e) {
6206 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
6207
6208 }
6209
6210 //Debug.stopMethodTracing();
6211 }
6212
6213 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
6214 throws java.io.IOException {
6215 serializer.startTag(null, "updated-package");
6216 serializer.attribute(null, "name", pkg.name);
6217 serializer.attribute(null, "codePath", pkg.codePathString);
6218 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006219 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6221 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6222 }
6223 if (pkg.sharedUser == null) {
6224 serializer.attribute(null, "userId",
6225 Integer.toString(pkg.userId));
6226 } else {
6227 serializer.attribute(null, "sharedUserId",
6228 Integer.toString(pkg.userId));
6229 }
6230 serializer.startTag(null, "perms");
6231 if (pkg.sharedUser == null) {
6232 // If this is a shared user, the permissions will
6233 // be written there. We still need to write an
6234 // empty permissions list so permissionsFixed will
6235 // be set.
6236 for (final String name : pkg.grantedPermissions) {
6237 BasePermission bp = mPermissions.get(name);
6238 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
6239 // We only need to write signature or system permissions but this wont
6240 // match the semantics of grantedPermissions. So write all permissions.
6241 serializer.startTag(null, "item");
6242 serializer.attribute(null, "name", name);
6243 serializer.endTag(null, "item");
6244 }
6245 }
6246 }
6247 serializer.endTag(null, "perms");
6248 serializer.endTag(null, "updated-package");
6249 }
6250
6251 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
6252 throws java.io.IOException {
6253 serializer.startTag(null, "package");
6254 serializer.attribute(null, "name", pkg.name);
6255 serializer.attribute(null, "codePath", pkg.codePathString);
6256 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6257 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6258 }
6259 serializer.attribute(null, "system",
6260 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6261 ? "true" : "false");
6262 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006263 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 if (pkg.sharedUser == null) {
6265 serializer.attribute(null, "userId",
6266 Integer.toString(pkg.userId));
6267 } else {
6268 serializer.attribute(null, "sharedUserId",
6269 Integer.toString(pkg.userId));
6270 }
6271 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6272 serializer.attribute(null, "enabled",
6273 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6274 ? "true" : "false");
6275 }
6276 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6277 serializer.attribute(null, "installStatus", "false");
6278 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006279 if (pkg.installerPackageName != null) {
6280 serializer.attribute(null, "installer", pkg.installerPackageName);
6281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6283 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6284 serializer.startTag(null, "perms");
6285 if (pkg.sharedUser == null) {
6286 // If this is a shared user, the permissions will
6287 // be written there. We still need to write an
6288 // empty permissions list so permissionsFixed will
6289 // be set.
6290 for (final String name : pkg.grantedPermissions) {
6291 serializer.startTag(null, "item");
6292 serializer.attribute(null, "name", name);
6293 serializer.endTag(null, "item");
6294 }
6295 }
6296 serializer.endTag(null, "perms");
6297 }
6298 if (pkg.disabledComponents.size() > 0) {
6299 serializer.startTag(null, "disabled-components");
6300 for (final String name : pkg.disabledComponents) {
6301 serializer.startTag(null, "item");
6302 serializer.attribute(null, "name", name);
6303 serializer.endTag(null, "item");
6304 }
6305 serializer.endTag(null, "disabled-components");
6306 }
6307 if (pkg.enabledComponents.size() > 0) {
6308 serializer.startTag(null, "enabled-components");
6309 for (final String name : pkg.enabledComponents) {
6310 serializer.startTag(null, "item");
6311 serializer.attribute(null, "name", name);
6312 serializer.endTag(null, "item");
6313 }
6314 serializer.endTag(null, "enabled-components");
6315 }
Jacek Surazski65e13172009-04-28 15:26:38 +02006316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 serializer.endTag(null, "package");
6318 }
6319
6320 void writePermission(XmlSerializer serializer, BasePermission bp)
6321 throws XmlPullParserException, java.io.IOException {
6322 if (bp.type != BasePermission.TYPE_BUILTIN
6323 && bp.sourcePackage != null) {
6324 serializer.startTag(null, "item");
6325 serializer.attribute(null, "name", bp.name);
6326 serializer.attribute(null, "package", bp.sourcePackage);
6327 if (DEBUG_SETTINGS) Log.v(TAG,
6328 "Writing perm: name=" + bp.name + " type=" + bp.type);
6329 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6330 PermissionInfo pi = bp.perm != null ? bp.perm.info
6331 : bp.pendingInfo;
6332 if (pi != null) {
6333 serializer.attribute(null, "type", "dynamic");
6334 if (pi.icon != 0) {
6335 serializer.attribute(null, "icon",
6336 Integer.toString(pi.icon));
6337 }
6338 if (pi.nonLocalizedLabel != null) {
6339 serializer.attribute(null, "label",
6340 pi.nonLocalizedLabel.toString());
6341 }
6342 if (pi.protectionLevel !=
6343 PermissionInfo.PROTECTION_NORMAL) {
6344 serializer.attribute(null, "protection",
6345 Integer.toString(pi.protectionLevel));
6346 }
6347 }
6348 }
6349 serializer.endTag(null, "item");
6350 }
6351 }
6352
6353 String getReadMessagesLP() {
6354 return mReadMessages.toString();
6355 }
6356
6357 ArrayList<String> getListOfIncompleteInstallPackages() {
6358 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6359 Iterator<String> its = kList.iterator();
6360 ArrayList<String> ret = new ArrayList<String>();
6361 while(its.hasNext()) {
6362 String key = its.next();
6363 PackageSetting ps = mPackages.get(key);
6364 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
6365 ret.add(key);
6366 }
6367 }
6368 return ret;
6369 }
6370
6371 boolean readLP() {
6372 FileInputStream str = null;
6373 if (mBackupSettingsFilename.exists()) {
6374 try {
6375 str = new FileInputStream(mBackupSettingsFilename);
6376 mReadMessages.append("Reading from backup settings file\n");
6377 Log.i(TAG, "Reading from backup settings file!");
6378 } catch (java.io.IOException e) {
6379 // We'll try for the normal settings file.
6380 }
6381 }
6382
6383 mPastSignatures.clear();
6384
6385 try {
6386 if (str == null) {
6387 if (!mSettingsFilename.exists()) {
6388 mReadMessages.append("No settings file found\n");
6389 Log.i(TAG, "No current settings file!");
6390 return false;
6391 }
6392 str = new FileInputStream(mSettingsFilename);
6393 }
6394 XmlPullParser parser = Xml.newPullParser();
6395 parser.setInput(str, null);
6396
6397 int type;
6398 while ((type=parser.next()) != XmlPullParser.START_TAG
6399 && type != XmlPullParser.END_DOCUMENT) {
6400 ;
6401 }
6402
6403 if (type != XmlPullParser.START_TAG) {
6404 mReadMessages.append("No start tag found in settings file\n");
6405 Log.e(TAG, "No start tag found in package manager settings");
6406 return false;
6407 }
6408
6409 int outerDepth = parser.getDepth();
6410 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6411 && (type != XmlPullParser.END_TAG
6412 || parser.getDepth() > outerDepth)) {
6413 if (type == XmlPullParser.END_TAG
6414 || type == XmlPullParser.TEXT) {
6415 continue;
6416 }
6417
6418 String tagName = parser.getName();
6419 if (tagName.equals("package")) {
6420 readPackageLP(parser);
6421 } else if (tagName.equals("permissions")) {
6422 readPermissionsLP(mPermissions, parser);
6423 } else if (tagName.equals("permission-trees")) {
6424 readPermissionsLP(mPermissionTrees, parser);
6425 } else if (tagName.equals("shared-user")) {
6426 readSharedUserLP(parser);
6427 } else if (tagName.equals("preferred-packages")) {
6428 readPreferredPackagesLP(parser);
6429 } else if (tagName.equals("preferred-activities")) {
6430 readPreferredActivitiesLP(parser);
6431 } else if(tagName.equals("updated-package")) {
6432 readDisabledSysPackageLP(parser);
6433 } else {
6434 Log.w(TAG, "Unknown element under <packages>: "
6435 + parser.getName());
6436 XmlUtils.skipCurrentTag(parser);
6437 }
6438 }
6439
6440 str.close();
6441
6442 } catch(XmlPullParserException e) {
6443 mReadMessages.append("Error reading: " + e.toString());
6444 Log.e(TAG, "Error reading package manager settings", e);
6445
6446 } catch(java.io.IOException e) {
6447 mReadMessages.append("Error reading: " + e.toString());
6448 Log.e(TAG, "Error reading package manager settings", e);
6449
6450 }
6451
6452 int N = mPendingPackages.size();
6453 for (int i=0; i<N; i++) {
6454 final PendingPackage pp = mPendingPackages.get(i);
6455 Object idObj = getUserIdLP(pp.sharedId);
6456 if (idObj != null && idObj instanceof SharedUserSetting) {
6457 PackageSetting p = getPackageLP(pp.name,
6458 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006459 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006460 if (p == null) {
6461 Log.w(TAG, "Unable to create application package for "
6462 + pp.name);
6463 continue;
6464 }
6465 p.copyFrom(pp);
6466 } else if (idObj != null) {
6467 String msg = "Bad package setting: package " + pp.name
6468 + " has shared uid " + pp.sharedId
6469 + " that is not a shared uid\n";
6470 mReadMessages.append(msg);
6471 Log.e(TAG, msg);
6472 } else {
6473 String msg = "Bad package setting: package " + pp.name
6474 + " has shared uid " + pp.sharedId
6475 + " that is not defined\n";
6476 mReadMessages.append(msg);
6477 Log.e(TAG, msg);
6478 }
6479 }
6480 mPendingPackages.clear();
6481
6482 N = mPendingPreferredPackages.size();
6483 mPreferredPackages.clear();
6484 for (int i=0; i<N; i++) {
6485 final String name = mPendingPreferredPackages.get(i);
6486 final PackageSetting p = mPackages.get(name);
6487 if (p != null) {
6488 mPreferredPackages.add(p);
6489 } else {
6490 Log.w(TAG, "Unknown preferred package: " + name);
6491 }
6492 }
6493 mPendingPreferredPackages.clear();
6494
6495 mReadMessages.append("Read completed successfully: "
6496 + mPackages.size() + " packages, "
6497 + mSharedUsers.size() + " shared uids\n");
6498
6499 return true;
6500 }
6501
6502 private int readInt(XmlPullParser parser, String ns, String name,
6503 int defValue) {
6504 String v = parser.getAttributeValue(ns, name);
6505 try {
6506 if (v == null) {
6507 return defValue;
6508 }
6509 return Integer.parseInt(v);
6510 } catch (NumberFormatException e) {
6511 reportSettingsProblem(Log.WARN,
6512 "Error in package manager settings: attribute " +
6513 name + " has bad integer value " + v + " at "
6514 + parser.getPositionDescription());
6515 }
6516 return defValue;
6517 }
6518
6519 private void readPermissionsLP(HashMap<String, BasePermission> out,
6520 XmlPullParser parser)
6521 throws IOException, XmlPullParserException {
6522 int outerDepth = parser.getDepth();
6523 int type;
6524 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6525 && (type != XmlPullParser.END_TAG
6526 || parser.getDepth() > outerDepth)) {
6527 if (type == XmlPullParser.END_TAG
6528 || type == XmlPullParser.TEXT) {
6529 continue;
6530 }
6531
6532 String tagName = parser.getName();
6533 if (tagName.equals("item")) {
6534 String name = parser.getAttributeValue(null, "name");
6535 String sourcePackage = parser.getAttributeValue(null, "package");
6536 String ptype = parser.getAttributeValue(null, "type");
6537 if (name != null && sourcePackage != null) {
6538 boolean dynamic = "dynamic".equals(ptype);
6539 BasePermission bp = new BasePermission(name, sourcePackage,
6540 dynamic
6541 ? BasePermission.TYPE_DYNAMIC
6542 : BasePermission.TYPE_NORMAL);
6543 if (dynamic) {
6544 PermissionInfo pi = new PermissionInfo();
6545 pi.packageName = sourcePackage.intern();
6546 pi.name = name.intern();
6547 pi.icon = readInt(parser, null, "icon", 0);
6548 pi.nonLocalizedLabel = parser.getAttributeValue(
6549 null, "label");
6550 pi.protectionLevel = readInt(parser, null, "protection",
6551 PermissionInfo.PROTECTION_NORMAL);
6552 bp.pendingInfo = pi;
6553 }
6554 out.put(bp.name, bp);
6555 } else {
6556 reportSettingsProblem(Log.WARN,
6557 "Error in package manager settings: permissions has"
6558 + " no name at " + parser.getPositionDescription());
6559 }
6560 } else {
6561 reportSettingsProblem(Log.WARN,
6562 "Unknown element reading permissions: "
6563 + parser.getName() + " at "
6564 + parser.getPositionDescription());
6565 }
6566 XmlUtils.skipCurrentTag(parser);
6567 }
6568 }
6569
6570 private void readDisabledSysPackageLP(XmlPullParser parser)
6571 throws XmlPullParserException, IOException {
6572 String name = parser.getAttributeValue(null, "name");
6573 String codePathStr = parser.getAttributeValue(null, "codePath");
6574 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6575 if(resourcePathStr == null) {
6576 resourcePathStr = codePathStr;
6577 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006578 String version = parser.getAttributeValue(null, "version");
6579 int versionCode = 0;
6580 if (version != null) {
6581 try {
6582 versionCode = Integer.parseInt(version);
6583 } catch (NumberFormatException e) {
6584 }
6585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586
6587 int pkgFlags = 0;
6588 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6589 PackageSetting ps = new PackageSetting(name,
6590 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006591 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 String timeStampStr = parser.getAttributeValue(null, "ts");
6593 if (timeStampStr != null) {
6594 try {
6595 long timeStamp = Long.parseLong(timeStampStr);
6596 ps.setTimeStamp(timeStamp, timeStampStr);
6597 } catch (NumberFormatException e) {
6598 }
6599 }
6600 String idStr = parser.getAttributeValue(null, "userId");
6601 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
6602 if(ps.userId <= 0) {
6603 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6604 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
6605 }
6606 int outerDepth = parser.getDepth();
6607 int type;
6608 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6609 && (type != XmlPullParser.END_TAG
6610 || parser.getDepth() > outerDepth)) {
6611 if (type == XmlPullParser.END_TAG
6612 || type == XmlPullParser.TEXT) {
6613 continue;
6614 }
6615
6616 String tagName = parser.getName();
6617 if (tagName.equals("perms")) {
6618 readGrantedPermissionsLP(parser,
6619 ps.grantedPermissions);
6620 } else {
6621 reportSettingsProblem(Log.WARN,
6622 "Unknown element under <updated-package>: "
6623 + parser.getName());
6624 XmlUtils.skipCurrentTag(parser);
6625 }
6626 }
6627 mDisabledSysPackages.put(name, ps);
6628 }
6629
6630 private void readPackageLP(XmlPullParser parser)
6631 throws XmlPullParserException, IOException {
6632 String name = null;
6633 String idStr = null;
6634 String sharedIdStr = null;
6635 String codePathStr = null;
6636 String resourcePathStr = null;
6637 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02006638 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 int pkgFlags = 0;
6640 String timeStampStr;
6641 long timeStamp = 0;
6642 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006643 String version = null;
6644 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 try {
6646 name = parser.getAttributeValue(null, "name");
6647 idStr = parser.getAttributeValue(null, "userId");
6648 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6649 codePathStr = parser.getAttributeValue(null, "codePath");
6650 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006651 version = parser.getAttributeValue(null, "version");
6652 if (version != null) {
6653 try {
6654 versionCode = Integer.parseInt(version);
6655 } catch (NumberFormatException e) {
6656 }
6657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazski65e13172009-04-28 15:26:38 +02006659 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660 if (systemStr != null) {
6661 if ("true".equals(systemStr)) {
6662 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6663 }
6664 } else {
6665 // Old settings that don't specify system... just treat
6666 // them as system, good enough.
6667 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6668 }
6669 timeStampStr = parser.getAttributeValue(null, "ts");
6670 if (timeStampStr != null) {
6671 try {
6672 timeStamp = Long.parseLong(timeStampStr);
6673 } catch (NumberFormatException e) {
6674 }
6675 }
6676 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
6677 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
6678 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
6679 if (resourcePathStr == null) {
6680 resourcePathStr = codePathStr;
6681 }
6682 if (name == null) {
6683 reportSettingsProblem(Log.WARN,
6684 "Error in package manager settings: <package> has no name at "
6685 + parser.getPositionDescription());
6686 } else if (codePathStr == null) {
6687 reportSettingsProblem(Log.WARN,
6688 "Error in package manager settings: <package> has no codePath at "
6689 + parser.getPositionDescription());
6690 } else if (userId > 0) {
6691 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006692 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
6694 + ": userId=" + userId + " pkg=" + packageSetting);
6695 if (packageSetting == null) {
6696 reportSettingsProblem(Log.ERROR,
6697 "Failure adding uid " + userId
6698 + " while parsing settings at "
6699 + parser.getPositionDescription());
6700 } else {
6701 packageSetting.setTimeStamp(timeStamp, timeStampStr);
6702 }
6703 } else if (sharedIdStr != null) {
6704 userId = sharedIdStr != null
6705 ? Integer.parseInt(sharedIdStr) : 0;
6706 if (userId > 0) {
6707 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006708 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 packageSetting.setTimeStamp(timeStamp, timeStampStr);
6710 mPendingPackages.add((PendingPackage) packageSetting);
6711 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
6712 + ": sharedUserId=" + userId + " pkg="
6713 + packageSetting);
6714 } else {
6715 reportSettingsProblem(Log.WARN,
6716 "Error in package manager settings: package "
6717 + name + " has bad sharedId " + sharedIdStr
6718 + " at " + parser.getPositionDescription());
6719 }
6720 } else {
6721 reportSettingsProblem(Log.WARN,
6722 "Error in package manager settings: package "
6723 + name + " has bad userId " + idStr + " at "
6724 + parser.getPositionDescription());
6725 }
6726 } catch (NumberFormatException e) {
6727 reportSettingsProblem(Log.WARN,
6728 "Error in package manager settings: package "
6729 + name + " has bad userId " + idStr + " at "
6730 + parser.getPositionDescription());
6731 }
6732 if (packageSetting != null) {
Jacek Surazski65e13172009-04-28 15:26:38 +02006733 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 final String enabledStr = parser.getAttributeValue(null, "enabled");
6735 if (enabledStr != null) {
6736 if (enabledStr.equalsIgnoreCase("true")) {
6737 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
6738 } else if (enabledStr.equalsIgnoreCase("false")) {
6739 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
6740 } else if (enabledStr.equalsIgnoreCase("default")) {
6741 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6742 } else {
6743 reportSettingsProblem(Log.WARN,
6744 "Error in package manager settings: package "
6745 + name + " has bad enabled value: " + idStr
6746 + " at " + parser.getPositionDescription());
6747 }
6748 } else {
6749 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6750 }
6751 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
6752 if (installStatusStr != null) {
6753 if (installStatusStr.equalsIgnoreCase("false")) {
6754 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
6755 } else {
6756 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
6757 }
6758 }
6759
6760 int outerDepth = parser.getDepth();
6761 int type;
6762 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6763 && (type != XmlPullParser.END_TAG
6764 || parser.getDepth() > outerDepth)) {
6765 if (type == XmlPullParser.END_TAG
6766 || type == XmlPullParser.TEXT) {
6767 continue;
6768 }
6769
6770 String tagName = parser.getName();
6771 if (tagName.equals("disabled-components")) {
6772 readDisabledComponentsLP(packageSetting, parser);
6773 } else if (tagName.equals("enabled-components")) {
6774 readEnabledComponentsLP(packageSetting, parser);
6775 } else if (tagName.equals("sigs")) {
6776 packageSetting.signatures.readXml(parser, mPastSignatures);
6777 } else if (tagName.equals("perms")) {
6778 readGrantedPermissionsLP(parser,
6779 packageSetting.loadedPermissions);
6780 packageSetting.permissionsFixed = true;
6781 } else {
6782 reportSettingsProblem(Log.WARN,
6783 "Unknown element under <package>: "
6784 + parser.getName());
6785 XmlUtils.skipCurrentTag(parser);
6786 }
6787 }
6788 } else {
6789 XmlUtils.skipCurrentTag(parser);
6790 }
6791 }
6792
6793 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
6794 XmlPullParser parser)
6795 throws IOException, XmlPullParserException {
6796 int outerDepth = parser.getDepth();
6797 int type;
6798 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6799 && (type != XmlPullParser.END_TAG
6800 || parser.getDepth() > outerDepth)) {
6801 if (type == XmlPullParser.END_TAG
6802 || type == XmlPullParser.TEXT) {
6803 continue;
6804 }
6805
6806 String tagName = parser.getName();
6807 if (tagName.equals("item")) {
6808 String name = parser.getAttributeValue(null, "name");
6809 if (name != null) {
6810 packageSetting.disabledComponents.add(name.intern());
6811 } else {
6812 reportSettingsProblem(Log.WARN,
6813 "Error in package manager settings: <disabled-components> has"
6814 + " no name at " + parser.getPositionDescription());
6815 }
6816 } else {
6817 reportSettingsProblem(Log.WARN,
6818 "Unknown element under <disabled-components>: "
6819 + parser.getName());
6820 }
6821 XmlUtils.skipCurrentTag(parser);
6822 }
6823 }
6824
6825 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
6826 XmlPullParser parser)
6827 throws IOException, XmlPullParserException {
6828 int outerDepth = parser.getDepth();
6829 int type;
6830 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6831 && (type != XmlPullParser.END_TAG
6832 || parser.getDepth() > outerDepth)) {
6833 if (type == XmlPullParser.END_TAG
6834 || type == XmlPullParser.TEXT) {
6835 continue;
6836 }
6837
6838 String tagName = parser.getName();
6839 if (tagName.equals("item")) {
6840 String name = parser.getAttributeValue(null, "name");
6841 if (name != null) {
6842 packageSetting.enabledComponents.add(name.intern());
6843 } else {
6844 reportSettingsProblem(Log.WARN,
6845 "Error in package manager settings: <enabled-components> has"
6846 + " no name at " + parser.getPositionDescription());
6847 }
6848 } else {
6849 reportSettingsProblem(Log.WARN,
6850 "Unknown element under <enabled-components>: "
6851 + parser.getName());
6852 }
6853 XmlUtils.skipCurrentTag(parser);
6854 }
6855 }
6856
6857 private void readSharedUserLP(XmlPullParser parser)
6858 throws XmlPullParserException, IOException {
6859 String name = null;
6860 String idStr = null;
6861 int pkgFlags = 0;
6862 SharedUserSetting su = null;
6863 try {
6864 name = parser.getAttributeValue(null, "name");
6865 idStr = parser.getAttributeValue(null, "userId");
6866 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
6867 if ("true".equals(parser.getAttributeValue(null, "system"))) {
6868 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6869 }
6870 if (name == null) {
6871 reportSettingsProblem(Log.WARN,
6872 "Error in package manager settings: <shared-user> has no name at "
6873 + parser.getPositionDescription());
6874 } else if (userId == 0) {
6875 reportSettingsProblem(Log.WARN,
6876 "Error in package manager settings: shared-user "
6877 + name + " has bad userId " + idStr + " at "
6878 + parser.getPositionDescription());
6879 } else {
6880 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
6881 reportSettingsProblem(Log.ERROR,
6882 "Occurred while parsing settings at "
6883 + parser.getPositionDescription());
6884 }
6885 }
6886 } catch (NumberFormatException e) {
6887 reportSettingsProblem(Log.WARN,
6888 "Error in package manager settings: package "
6889 + name + " has bad userId " + idStr + " at "
6890 + parser.getPositionDescription());
6891 };
6892
6893 if (su != null) {
6894 int outerDepth = parser.getDepth();
6895 int type;
6896 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6897 && (type != XmlPullParser.END_TAG
6898 || parser.getDepth() > outerDepth)) {
6899 if (type == XmlPullParser.END_TAG
6900 || type == XmlPullParser.TEXT) {
6901 continue;
6902 }
6903
6904 String tagName = parser.getName();
6905 if (tagName.equals("sigs")) {
6906 su.signatures.readXml(parser, mPastSignatures);
6907 } else if (tagName.equals("perms")) {
6908 readGrantedPermissionsLP(parser, su.loadedPermissions);
6909 } else {
6910 reportSettingsProblem(Log.WARN,
6911 "Unknown element under <shared-user>: "
6912 + parser.getName());
6913 XmlUtils.skipCurrentTag(parser);
6914 }
6915 }
6916
6917 } else {
6918 XmlUtils.skipCurrentTag(parser);
6919 }
6920 }
6921
6922 private void readGrantedPermissionsLP(XmlPullParser parser,
6923 HashSet<String> outPerms) throws IOException, XmlPullParserException {
6924 int outerDepth = parser.getDepth();
6925 int type;
6926 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6927 && (type != XmlPullParser.END_TAG
6928 || parser.getDepth() > outerDepth)) {
6929 if (type == XmlPullParser.END_TAG
6930 || type == XmlPullParser.TEXT) {
6931 continue;
6932 }
6933
6934 String tagName = parser.getName();
6935 if (tagName.equals("item")) {
6936 String name = parser.getAttributeValue(null, "name");
6937 if (name != null) {
6938 outPerms.add(name.intern());
6939 } else {
6940 reportSettingsProblem(Log.WARN,
6941 "Error in package manager settings: <perms> has"
6942 + " no name at " + parser.getPositionDescription());
6943 }
6944 } else {
6945 reportSettingsProblem(Log.WARN,
6946 "Unknown element under <perms>: "
6947 + parser.getName());
6948 }
6949 XmlUtils.skipCurrentTag(parser);
6950 }
6951 }
6952
6953 private void readPreferredPackagesLP(XmlPullParser parser)
6954 throws XmlPullParserException, IOException {
6955 int outerDepth = parser.getDepth();
6956 int type;
6957 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6958 && (type != XmlPullParser.END_TAG
6959 || parser.getDepth() > outerDepth)) {
6960 if (type == XmlPullParser.END_TAG
6961 || type == XmlPullParser.TEXT) {
6962 continue;
6963 }
6964
6965 String tagName = parser.getName();
6966 if (tagName.equals("item")) {
6967 String name = parser.getAttributeValue(null, "name");
6968 if (name != null) {
6969 mPendingPreferredPackages.add(name);
6970 } else {
6971 reportSettingsProblem(Log.WARN,
6972 "Error in package manager settings: <preferred-package> has no name at "
6973 + parser.getPositionDescription());
6974 }
6975 } else {
6976 reportSettingsProblem(Log.WARN,
6977 "Unknown element under <preferred-packages>: "
6978 + parser.getName());
6979 }
6980 XmlUtils.skipCurrentTag(parser);
6981 }
6982 }
6983
6984 private void readPreferredActivitiesLP(XmlPullParser parser)
6985 throws XmlPullParserException, IOException {
6986 int outerDepth = parser.getDepth();
6987 int type;
6988 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6989 && (type != XmlPullParser.END_TAG
6990 || parser.getDepth() > outerDepth)) {
6991 if (type == XmlPullParser.END_TAG
6992 || type == XmlPullParser.TEXT) {
6993 continue;
6994 }
6995
6996 String tagName = parser.getName();
6997 if (tagName.equals("item")) {
6998 PreferredActivity pa = new PreferredActivity(parser);
6999 if (pa.mParseError == null) {
7000 mPreferredActivities.addFilter(pa);
7001 } else {
7002 reportSettingsProblem(Log.WARN,
7003 "Error in package manager settings: <preferred-activity> "
7004 + pa.mParseError + " at "
7005 + parser.getPositionDescription());
7006 }
7007 } else {
7008 reportSettingsProblem(Log.WARN,
7009 "Unknown element under <preferred-activities>: "
7010 + parser.getName());
7011 XmlUtils.skipCurrentTag(parser);
7012 }
7013 }
7014 }
7015
7016 // Returns -1 if we could not find an available UserId to assign
7017 private int newUserIdLP(Object obj) {
7018 // Let's be stupidly inefficient for now...
7019 final int N = mUserIds.size();
7020 for (int i=0; i<N; i++) {
7021 if (mUserIds.get(i) == null) {
7022 mUserIds.set(i, obj);
7023 return FIRST_APPLICATION_UID + i;
7024 }
7025 }
7026
7027 // None left?
7028 if (N >= MAX_APPLICATION_UIDS) {
7029 return -1;
7030 }
7031
7032 mUserIds.add(obj);
7033 return FIRST_APPLICATION_UID + N;
7034 }
7035
7036 public PackageSetting getDisabledSystemPkg(String name) {
7037 synchronized(mPackages) {
7038 PackageSetting ps = mDisabledSysPackages.get(name);
7039 return ps;
7040 }
7041 }
7042
7043 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
7044 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
7045 if (Config.LOGV) {
7046 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
7047 + " componentName = " + componentInfo.name);
7048 Log.v(TAG, "enabledComponents: "
7049 + Arrays.toString(packageSettings.enabledComponents.toArray()));
7050 Log.v(TAG, "disabledComponents: "
7051 + Arrays.toString(packageSettings.disabledComponents.toArray()));
7052 }
7053 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
7054 || ((componentInfo.enabled
7055 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
7056 || (componentInfo.applicationInfo.enabled
7057 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
7058 && !packageSettings.disabledComponents.contains(componentInfo.name))
7059 || packageSettings.enabledComponents.contains(componentInfo.name));
7060 }
7061 }
7062}