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