blob: a3c702f51ea65da5a2bea8bec25702ccd2e019c0 [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 =
Mihai Preda074edef2009-05-18 17:13:31 +02001273 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1275 if (prefs != null && prefs.size() > 0) {
1276 // First figure out how good the original match set is.
1277 // We will only allow preferred activities that came
1278 // from the same match quality.
1279 int match = 0;
1280 final int N = query.size();
1281 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1282 for (int j=0; j<N; j++) {
1283 ResolveInfo ri = query.get(j);
1284 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1285 + ": 0x" + Integer.toHexString(match));
1286 if (ri.match > match) match = ri.match;
1287 }
1288 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1289 + Integer.toHexString(match));
1290 match &= IntentFilter.MATCH_CATEGORY_MASK;
1291 final int M = prefs.size();
1292 for (int i=0; i<M; i++) {
1293 PreferredActivity pa = prefs.get(i);
1294 if (pa.mMatch != match) {
1295 continue;
1296 }
1297 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1298 if (DEBUG_PREFERRED) {
1299 Log.v(TAG, "Got preferred activity:");
1300 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1301 }
1302 if (ai != null) {
1303 for (int j=0; j<N; j++) {
1304 ResolveInfo ri = query.get(j);
1305 if (!ri.activityInfo.applicationInfo.packageName
1306 .equals(ai.applicationInfo.packageName)) {
1307 continue;
1308 }
1309 if (!ri.activityInfo.name.equals(ai.name)) {
1310 continue;
1311 }
1312
1313 // Okay we found a previously set preferred app.
1314 // If the result set is different from when this
1315 // was created, we need to clear it and re-ask the
1316 // user their preference.
1317 if (!pa.sameSet(query, priority)) {
1318 Log.i(TAG, "Result set changed, dropping preferred activity for "
1319 + intent + " type " + resolvedType);
1320 mSettings.mPreferredActivities.removeFilter(pa);
1321 return null;
1322 }
1323
1324 // Yay!
1325 return ri;
1326 }
1327 }
1328 }
1329 }
1330 }
1331 return null;
1332 }
1333
1334 public List<ResolveInfo> queryIntentActivities(Intent intent,
1335 String resolvedType, int flags) {
1336 ComponentName comp = intent.getComponent();
1337 if (comp != null) {
1338 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1339 ActivityInfo ai = getActivityInfo(comp, flags);
1340 if (ai != null) {
1341 ResolveInfo ri = new ResolveInfo();
1342 ri.activityInfo = ai;
1343 list.add(ri);
1344 }
1345 return list;
1346 }
1347
1348 synchronized (mPackages) {
1349 return (List<ResolveInfo>)mActivities.
Mihai Preda074edef2009-05-18 17:13:31 +02001350 queryIntent(intent, resolvedType, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 }
1352 }
1353
1354 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1355 Intent[] specifics, String[] specificTypes, Intent intent,
1356 String resolvedType, int flags) {
1357 final String resultsAction = intent.getAction();
1358
1359 List<ResolveInfo> results = queryIntentActivities(
1360 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1361 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1362
1363 int specificsPos = 0;
1364 int N;
1365
1366 // todo: note that the algorithm used here is O(N^2). This
1367 // isn't a problem in our current environment, but if we start running
1368 // into situations where we have more than 5 or 10 matches then this
1369 // should probably be changed to something smarter...
1370
1371 // First we go through and resolve each of the specific items
1372 // that were supplied, taking care of removing any corresponding
1373 // duplicate items in the generic resolve list.
1374 if (specifics != null) {
1375 for (int i=0; i<specifics.length; i++) {
1376 final Intent sintent = specifics[i];
1377 if (sintent == null) {
1378 continue;
1379 }
1380
1381 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1382 String action = sintent.getAction();
1383 if (resultsAction != null && resultsAction.equals(action)) {
1384 // If this action was explicitly requested, then don't
1385 // remove things that have it.
1386 action = null;
1387 }
1388 ComponentName comp = sintent.getComponent();
1389 ResolveInfo ri = null;
1390 ActivityInfo ai = null;
1391 if (comp == null) {
1392 ri = resolveIntent(
1393 sintent,
1394 specificTypes != null ? specificTypes[i] : null,
1395 flags);
1396 if (ri == null) {
1397 continue;
1398 }
1399 if (ri == mResolveInfo) {
1400 // ACK! Must do something better with this.
1401 }
1402 ai = ri.activityInfo;
1403 comp = new ComponentName(ai.applicationInfo.packageName,
1404 ai.name);
1405 } else {
1406 ai = getActivityInfo(comp, flags);
1407 if (ai == null) {
1408 continue;
1409 }
1410 }
1411
1412 // Look for any generic query activities that are duplicates
1413 // of this specific one, and remove them from the results.
1414 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1415 N = results.size();
1416 int j;
1417 for (j=specificsPos; j<N; j++) {
1418 ResolveInfo sri = results.get(j);
1419 if ((sri.activityInfo.name.equals(comp.getClassName())
1420 && sri.activityInfo.applicationInfo.packageName.equals(
1421 comp.getPackageName()))
1422 || (action != null && sri.filter.matchAction(action))) {
1423 results.remove(j);
1424 if (Config.LOGV) Log.v(
1425 TAG, "Removing duplicate item from " + j
1426 + " due to specific " + specificsPos);
1427 if (ri == null) {
1428 ri = sri;
1429 }
1430 j--;
1431 N--;
1432 }
1433 }
1434
1435 // Add this specific item to its proper place.
1436 if (ri == null) {
1437 ri = new ResolveInfo();
1438 ri.activityInfo = ai;
1439 }
1440 results.add(specificsPos, ri);
1441 ri.specificIndex = i;
1442 specificsPos++;
1443 }
1444 }
1445
1446 // Now we go through the remaining generic results and remove any
1447 // duplicate actions that are found here.
1448 N = results.size();
1449 for (int i=specificsPos; i<N-1; i++) {
1450 final ResolveInfo rii = results.get(i);
1451 if (rii.filter == null) {
1452 continue;
1453 }
1454
1455 // Iterate over all of the actions of this result's intent
1456 // filter... typically this should be just one.
1457 final Iterator<String> it = rii.filter.actionsIterator();
1458 if (it == null) {
1459 continue;
1460 }
1461 while (it.hasNext()) {
1462 final String action = it.next();
1463 if (resultsAction != null && resultsAction.equals(action)) {
1464 // If this action was explicitly requested, then don't
1465 // remove things that have it.
1466 continue;
1467 }
1468 for (int j=i+1; j<N; j++) {
1469 final ResolveInfo rij = results.get(j);
1470 if (rij.filter != null && rij.filter.hasAction(action)) {
1471 results.remove(j);
1472 if (Config.LOGV) Log.v(
1473 TAG, "Removing duplicate item from " + j
1474 + " due to action " + action + " at " + i);
1475 j--;
1476 N--;
1477 }
1478 }
1479 }
1480
1481 // If the caller didn't request filter information, drop it now
1482 // so we don't have to marshall/unmarshall it.
1483 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1484 rii.filter = null;
1485 }
1486 }
1487
1488 // Filter out the caller activity if so requested.
1489 if (caller != null) {
1490 N = results.size();
1491 for (int i=0; i<N; i++) {
1492 ActivityInfo ainfo = results.get(i).activityInfo;
1493 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1494 && caller.getClassName().equals(ainfo.name)) {
1495 results.remove(i);
1496 break;
1497 }
1498 }
1499 }
1500
1501 // If the caller didn't request filter information,
1502 // drop them now so we don't have to
1503 // marshall/unmarshall it.
1504 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1505 N = results.size();
1506 for (int i=0; i<N; i++) {
1507 results.get(i).filter = null;
1508 }
1509 }
1510
1511 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1512 return results;
1513 }
1514
1515 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1516 String resolvedType, int flags) {
1517 synchronized (mPackages) {
1518 return (List<ResolveInfo>)mReceivers.
Mihai Preda074edef2009-05-18 17:13:31 +02001519 queryIntent(intent, resolvedType, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 }
1521 }
1522
1523 public ResolveInfo resolveService(Intent intent, String resolvedType,
1524 int flags) {
1525 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1526 flags);
1527 if (query != null) {
1528 if (query.size() >= 1) {
1529 // If there is more than one service with the same priority,
1530 // just arbitrarily pick the first one.
1531 return query.get(0);
1532 }
1533 }
1534 return null;
1535 }
1536
1537 public List<ResolveInfo> queryIntentServices(Intent intent,
1538 String resolvedType, int flags) {
1539 ComponentName comp = intent.getComponent();
1540 if (comp != null) {
1541 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1542 ServiceInfo si = getServiceInfo(comp, flags);
1543 if (si != null) {
1544 ResolveInfo ri = new ResolveInfo();
1545 ri.serviceInfo = si;
1546 list.add(ri);
1547 }
1548 return list;
1549 }
1550
1551 synchronized (mPackages) {
Mihai Preda074edef2009-05-18 17:13:31 +02001552 return (List<ResolveInfo>)mServices.queryIntent(intent, resolvedType, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 }
1554 }
1555
1556 public List<PackageInfo> getInstalledPackages(int flags) {
1557 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1558
1559 synchronized (mPackages) {
1560 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1561 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1562 while (i.hasNext()) {
1563 final PackageSetting ps = i.next();
1564 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1565 if(psPkg != null) {
1566 finalList.add(psPkg);
1567 }
1568 }
1569 }
1570 else {
1571 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1572 while (i.hasNext()) {
1573 final PackageParser.Package p = i.next();
1574 if (p.applicationInfo != null) {
1575 PackageInfo pi = generatePackageInfo(p, flags);
1576 if(pi != null) {
1577 finalList.add(pi);
1578 }
1579 }
1580 }
1581 }
1582 }
1583 return finalList;
1584 }
1585
1586 public List<ApplicationInfo> getInstalledApplications(int flags) {
1587 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1588 synchronized(mPackages) {
1589 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1590 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1591 while (i.hasNext()) {
1592 final PackageSetting ps = i.next();
1593 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
1594 if(ai != null) {
1595 finalList.add(ai);
1596 }
1597 }
1598 }
1599 else {
1600 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1601 while (i.hasNext()) {
1602 final PackageParser.Package p = i.next();
1603 if (p.applicationInfo != null) {
1604 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
1605 if(ai != null) {
1606 finalList.add(ai);
1607 }
1608 }
1609 }
1610 }
1611 }
1612 return finalList;
1613 }
1614
1615 public List<ApplicationInfo> getPersistentApplications(int flags) {
1616 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
1617
1618 synchronized (mPackages) {
1619 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1620 while (i.hasNext()) {
1621 PackageParser.Package p = i.next();
1622 if (p.applicationInfo != null
1623 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
1624 && (!mSafeMode || (p.applicationInfo.flags
1625 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1626 finalList.add(p.applicationInfo);
1627 }
1628 }
1629 }
1630
1631 return finalList;
1632 }
1633
1634 public ProviderInfo resolveContentProvider(String name, int flags) {
1635 synchronized (mPackages) {
1636 final PackageParser.Provider provider = mProviders.get(name);
1637 return provider != null
1638 && mSettings.isEnabledLP(provider.info, flags)
1639 && (!mSafeMode || (provider.info.applicationInfo.flags
1640 &ApplicationInfo.FLAG_SYSTEM) != 0)
1641 ? PackageParser.generateProviderInfo(provider, flags)
1642 : null;
1643 }
1644 }
1645
1646 public void querySyncProviders(List outNames, List outInfo) {
1647 synchronized (mPackages) {
1648 Iterator<Map.Entry<String, PackageParser.Provider>> i
1649 = mProviders.entrySet().iterator();
1650
1651 while (i.hasNext()) {
1652 Map.Entry<String, PackageParser.Provider> entry = i.next();
1653 PackageParser.Provider p = entry.getValue();
1654
1655 if (p.syncable
1656 && (!mSafeMode || (p.info.applicationInfo.flags
1657 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1658 outNames.add(entry.getKey());
1659 outInfo.add(PackageParser.generateProviderInfo(p, 0));
1660 }
1661 }
1662 }
1663 }
1664
1665 public List<ProviderInfo> queryContentProviders(String processName,
1666 int uid, int flags) {
1667 ArrayList<ProviderInfo> finalList = null;
1668
1669 synchronized (mPackages) {
1670 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
1671 while (i.hasNext()) {
1672 PackageParser.Provider p = i.next();
1673 if (p.info.authority != null
1674 && (processName == null ||
1675 (p.info.processName.equals(processName)
1676 && p.info.applicationInfo.uid == uid))
1677 && mSettings.isEnabledLP(p.info, flags)
1678 && (!mSafeMode || (p.info.applicationInfo.flags
1679 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
1680 if (finalList == null) {
1681 finalList = new ArrayList<ProviderInfo>(3);
1682 }
1683 finalList.add(PackageParser.generateProviderInfo(p,
1684 flags));
1685 }
1686 }
1687 }
1688
1689 if (finalList != null) {
1690 Collections.sort(finalList, mProviderInitOrderSorter);
1691 }
1692
1693 return finalList;
1694 }
1695
1696 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
1697 int flags) {
1698 synchronized (mPackages) {
1699 final PackageParser.Instrumentation i = mInstrumentation.get(name);
1700 return PackageParser.generateInstrumentationInfo(i, flags);
1701 }
1702 }
1703
1704 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
1705 int flags) {
1706 ArrayList<InstrumentationInfo> finalList =
1707 new ArrayList<InstrumentationInfo>();
1708
1709 synchronized (mPackages) {
1710 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
1711 while (i.hasNext()) {
1712 PackageParser.Instrumentation p = i.next();
1713 if (targetPackage == null
1714 || targetPackage.equals(p.info.targetPackage)) {
1715 finalList.add(PackageParser.generateInstrumentationInfo(p,
1716 flags));
1717 }
1718 }
1719 }
1720
1721 return finalList;
1722 }
1723
1724 private void scanDirLI(File dir, int flags, int scanMode) {
1725 Log.d(TAG, "Scanning app dir " + dir);
1726
1727 String[] files = dir.list();
1728
1729 int i;
1730 for (i=0; i<files.length; i++) {
1731 File file = new File(dir, files[i]);
1732 PackageParser.Package pkg = scanPackageLI(file, file, file,
1733 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
1734 }
1735 }
1736
1737 private static void reportSettingsProblem(int priority, String msg) {
1738 try {
1739 File dataDir = Environment.getDataDirectory();
1740 File systemDir = new File(dataDir, "system");
1741 File fname = new File(systemDir, "uiderrors.txt");
1742 FileOutputStream out = new FileOutputStream(fname, true);
1743 PrintWriter pw = new PrintWriter(out);
1744 pw.println(msg);
1745 pw.close();
1746 FileUtils.setPermissions(
1747 fname.toString(),
1748 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
1749 -1, -1);
1750 } catch (java.io.IOException e) {
1751 }
1752 Log.println(priority, TAG, msg);
1753 }
1754
1755 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
1756 PackageParser.Package pkg, File srcFile, int parseFlags) {
1757 if (GET_CERTIFICATES) {
1758 if (ps == null || !ps.codePath.equals(srcFile)
1759 || ps.getTimeStamp() != srcFile.lastModified()) {
1760 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
1761 if (!pp.collectCertificates(pkg, parseFlags)) {
1762 mLastScanError = pp.getParseError();
1763 return false;
1764 }
1765 }
1766 }
1767 return true;
1768 }
1769
1770 /*
1771 * Scan a package and return the newly parsed package.
1772 * Returns null in case of errors and the error code is stored in mLastScanError
1773 */
1774 private PackageParser.Package scanPackageLI(File scanFile,
1775 File destCodeFile, File destResourceFile, int parseFlags,
1776 int scanMode) {
1777 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
1778 parseFlags |= mDefParseFlags;
1779 PackageParser pp = new PackageParser(scanFile.getPath());
1780 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackborn851a5412009-05-08 12:06:44 -07001781 pp.setSdkVersion(mSdkVersion, mSdkCodename);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 final PackageParser.Package pkg = pp.parsePackage(scanFile,
1783 destCodeFile.getAbsolutePath(), mMetrics, parseFlags);
1784 if (pkg == null) {
1785 mLastScanError = pp.getParseError();
1786 return null;
1787 }
1788 PackageSetting ps;
1789 PackageSetting updatedPkg;
1790 synchronized (mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07001791 ps = mSettings.peekPackageLP(pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 updatedPkg = mSettings.mDisabledSysPackages.get(pkg.packageName);
1793 }
1794 if (updatedPkg != null) {
1795 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
1796 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
1797 }
1798 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
1799 // Check for updated system applications here
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07001800 if (updatedPkg != null) {
1801 if ((ps != null) && (!ps.codePath.getPath().equals(scanFile.getPath()))) {
1802 if (pkg.mVersionCode <= ps.versionCode) {
1803 // The system package has been updated and the code path does not match
1804 // Ignore entry. Just return
1805 Log.w(TAG, "Package:" + pkg.packageName +
1806 " has been updated. Ignoring the one from path:"+scanFile);
1807 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
1808 return null;
1809 } else {
1810 // Delete the older apk pointed to by ps
1811 deletePackageResourcesLI(ps.name, ps.codePathString, ps.resourcePathString);
1812 mSettings.enableSystemPackageLP(ps.name);
1813 }
1814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
1816 }
1817 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
1818 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
1819 return null;
1820 }
1821 // The apk is forward locked (not public) if its code and resources
1822 // are kept in different files.
1823 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
1824 scanMode |= SCAN_FORWARD_LOCKED;
1825 }
1826 // Note that we invoke the following method only if we are about to unpack an application
1827 return scanPackageLI(scanFile, destCodeFile, destResourceFile,
1828 pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
1829 }
1830
1831 private static String fixProcessName(String defProcessName,
1832 String processName, int uid) {
1833 if (processName == null) {
1834 return defProcessName;
1835 }
1836 return processName;
1837 }
1838
1839 private boolean verifySignaturesLP(PackageSetting pkgSetting,
1840 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
1841 if (pkg.mSignatures != null) {
1842 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
1843 updateSignature)) {
1844 Log.e(TAG, "Package " + pkg.packageName
1845 + " signatures do not match the previously installed version; ignoring!");
1846 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
1847 return false;
1848 }
1849
1850 if (pkgSetting.sharedUser != null) {
1851 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
1852 pkg.mSignatures, updateSignature)) {
1853 Log.e(TAG, "Package " + pkg.packageName
1854 + " has no signatures that match those in shared user "
1855 + pkgSetting.sharedUser.name + "; ignoring!");
1856 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
1857 return false;
1858 }
1859 }
1860 } else {
1861 pkg.mSignatures = pkgSetting.signatures.mSignatures;
1862 }
1863 return true;
1864 }
1865
1866 private PackageParser.Package scanPackageLI(
1867 File scanFile, File destCodeFile, File destResourceFile,
1868 PackageParser.Package pkg, int parseFlags, int scanMode) {
1869
1870 mScanningPath = scanFile;
1871 if (pkg == null) {
1872 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
1873 return null;
1874 }
1875
1876 final String pkgName = pkg.applicationInfo.packageName;
1877 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
1878 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
1879 }
1880
1881 if (pkgName.equals("android")) {
1882 synchronized (mPackages) {
1883 if (mAndroidApplication != null) {
1884 Log.w(TAG, "*************************************************");
1885 Log.w(TAG, "Core android package being redefined. Skipping.");
1886 Log.w(TAG, " file=" + mScanningPath);
1887 Log.w(TAG, "*************************************************");
1888 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
1889 return null;
1890 }
1891
1892 // Set up information for our fall-back user intent resolution
1893 // activity.
1894 mPlatformPackage = pkg;
1895 pkg.mVersionCode = mSdkVersion;
1896 mAndroidApplication = pkg.applicationInfo;
1897 mResolveActivity.applicationInfo = mAndroidApplication;
1898 mResolveActivity.name = ResolverActivity.class.getName();
1899 mResolveActivity.packageName = mAndroidApplication.packageName;
1900 mResolveActivity.processName = mAndroidApplication.processName;
1901 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
1902 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
1903 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
1904 mResolveActivity.exported = true;
1905 mResolveActivity.enabled = true;
1906 mResolveInfo.activityInfo = mResolveActivity;
1907 mResolveInfo.priority = 0;
1908 mResolveInfo.preferredOrder = 0;
1909 mResolveInfo.match = 0;
1910 mResolveComponentName = new ComponentName(
1911 mAndroidApplication.packageName, mResolveActivity.name);
1912 }
1913 }
1914
1915 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
1916 TAG, "Scanning package " + pkgName);
1917 if (mPackages.containsKey(pkgName) || mSharedLibraries.containsKey(pkgName)) {
1918 Log.w(TAG, "*************************************************");
1919 Log.w(TAG, "Application package " + pkgName
1920 + " already installed. Skipping duplicate.");
1921 Log.w(TAG, "*************************************************");
1922 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
1923 return null;
1924 }
1925
1926 SharedUserSetting suid = null;
1927 PackageSetting pkgSetting = null;
1928
1929 boolean removeExisting = false;
1930
1931 synchronized (mPackages) {
1932 // Check all shared libraries and map to their actual file path.
1933 if (pkg.usesLibraryFiles != null) {
1934 for (int i=0; i<pkg.usesLibraryFiles.length; i++) {
1935 String file = mSharedLibraries.get(pkg.usesLibraryFiles[i]);
1936 if (file == null) {
1937 Log.e(TAG, "Package " + pkg.packageName
1938 + " requires unavailable shared library "
1939 + pkg.usesLibraryFiles[i] + "; ignoring!");
1940 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
1941 return null;
1942 }
1943 pkg.usesLibraryFiles[i] = file;
1944 }
1945 }
1946
1947 if (pkg.mSharedUserId != null) {
1948 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
1949 pkg.applicationInfo.flags, true);
1950 if (suid == null) {
1951 Log.w(TAG, "Creating application package " + pkgName
1952 + " for shared user failed");
1953 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
1954 return null;
1955 }
1956 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
1957 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
1958 + suid.userId + "): packages=" + suid.packages);
1959 }
1960 }
1961
1962 // Just create the setting, don't add it yet
1963 pkgSetting = mSettings.getPackageLP(pkg, suid, destCodeFile,
1964 destResourceFile, pkg.applicationInfo.flags, true, false);
1965 if (pkgSetting == null) {
1966 Log.w(TAG, "Creating application package " + pkgName + " failed");
1967 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
1968 return null;
1969 }
1970 if(mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
1971 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
1972 }
1973
1974 pkg.applicationInfo.uid = pkgSetting.userId;
1975 pkg.mExtras = pkgSetting;
1976
1977 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
1978 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
1979 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
1980 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
1981 return null;
1982 }
1983 // The signature has changed, but this package is in the system
1984 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07001985 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 // However... if this package is part of a shared user, but it
1987 // doesn't match the signature of the shared user, let's fail.
1988 // What this means is that you can't change the signatures
1989 // associated with an overall shared user, which doesn't seem all
1990 // that unreasonable.
1991 if (pkgSetting.sharedUser != null) {
1992 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
1993 pkg.mSignatures, false)) {
1994 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
1995 return null;
1996 }
1997 }
1998 removeExisting = true;
1999 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002000
2001 // Verify that this new package doesn't have any content providers
2002 // that conflict with existing packages. Only do this if the
2003 // package isn't already installed, since we don't want to break
2004 // things that are installed.
2005 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2006 int N = pkg.providers.size();
2007 int i;
2008 for (i=0; i<N; i++) {
2009 PackageParser.Provider p = pkg.providers.get(i);
2010 String names[] = p.info.authority.split(";");
2011 for (int j = 0; j < names.length; j++) {
2012 if (mProviders.containsKey(names[j])) {
2013 PackageParser.Provider other = mProviders.get(names[j]);
2014 Log.w(TAG, "Can't install because provider name " + names[j] +
2015 " (in package " + pkg.applicationInfo.packageName +
2016 ") is already used by "
2017 + ((other != null && other.component != null)
2018 ? other.component.getPackageName() : "?"));
2019 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2020 return null;
2021 }
2022 }
2023 }
2024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 }
2026
2027 if (removeExisting) {
2028 if (mInstaller != null) {
2029 int ret = mInstaller.remove(pkgName);
2030 if (ret != 0) {
2031 String msg = "System package " + pkg.packageName
2032 + " could not have data directory erased after signature change.";
2033 reportSettingsProblem(Log.WARN, msg);
2034 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2035 return null;
2036 }
2037 }
2038 Log.w(TAG, "System package " + pkg.packageName
2039 + " signature changed: existing data removed.");
2040 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2041 }
2042
2043 long scanFileTime = scanFile.lastModified();
2044 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2045 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2046 pkg.applicationInfo.processName = fixProcessName(
2047 pkg.applicationInfo.packageName,
2048 pkg.applicationInfo.processName,
2049 pkg.applicationInfo.uid);
2050 pkg.applicationInfo.publicSourceDir = pkgSetting.resourcePathString;
2051
2052 File dataPath;
2053 if (mPlatformPackage == pkg) {
2054 // The system package is special.
2055 dataPath = new File (Environment.getDataDirectory(), "system");
2056 pkg.applicationInfo.dataDir = dataPath.getPath();
2057 } else {
2058 // This is a normal package, need to make its data directory.
2059 dataPath = new File(mAppDataDir, pkgName);
2060 if (dataPath.exists()) {
2061 mOutPermissions[1] = 0;
2062 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2063 if (mOutPermissions[1] == pkg.applicationInfo.uid
2064 || !Process.supportsProcesses()) {
2065 pkg.applicationInfo.dataDir = dataPath.getPath();
2066 } else {
2067 boolean recovered = false;
2068 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2069 // If this is a system app, we can at least delete its
2070 // current data so the application will still work.
2071 if (mInstaller != null) {
2072 int ret = mInstaller.remove(pkgName);
2073 if(ret >= 0) {
2074 // Old data gone!
2075 String msg = "System package " + pkg.packageName
2076 + " has changed from uid: "
2077 + mOutPermissions[1] + " to "
2078 + pkg.applicationInfo.uid + "; old data erased";
2079 reportSettingsProblem(Log.WARN, msg);
2080 recovered = true;
2081
2082 // And now re-install the app.
2083 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2084 pkg.applicationInfo.uid);
2085 if (ret == -1) {
2086 // Ack should not happen!
2087 msg = "System package " + pkg.packageName
2088 + " could not have data directory re-created after delete.";
2089 reportSettingsProblem(Log.WARN, msg);
2090 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2091 return null;
2092 }
2093 }
2094 }
2095 if (!recovered) {
2096 mHasSystemUidErrors = true;
2097 }
2098 }
2099 if (!recovered) {
2100 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2101 + pkg.applicationInfo.uid + "/fs_"
2102 + mOutPermissions[1];
2103 String msg = "Package " + pkg.packageName
2104 + " has mismatched uid: "
2105 + mOutPermissions[1] + " on disk, "
2106 + pkg.applicationInfo.uid + " in settings";
2107 synchronized (mPackages) {
2108 if (!mReportedUidError) {
2109 mReportedUidError = true;
2110 msg = msg + "; read messages:\n"
2111 + mSettings.getReadMessagesLP();
2112 }
2113 reportSettingsProblem(Log.ERROR, msg);
2114 }
2115 }
2116 }
2117 pkg.applicationInfo.dataDir = dataPath.getPath();
2118 } else {
2119 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2120 Log.v(TAG, "Want this data dir: " + dataPath);
2121 //invoke installer to do the actual installation
2122 if (mInstaller != null) {
2123 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
2124 pkg.applicationInfo.uid);
2125 if(ret < 0) {
2126 // Error from installer
2127 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2128 return null;
2129 }
2130 } else {
2131 dataPath.mkdirs();
2132 if (dataPath.exists()) {
2133 FileUtils.setPermissions(
2134 dataPath.toString(),
2135 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2136 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2137 }
2138 }
2139 if (dataPath.exists()) {
2140 pkg.applicationInfo.dataDir = dataPath.getPath();
2141 } else {
2142 Log.w(TAG, "Unable to create data directory: " + dataPath);
2143 pkg.applicationInfo.dataDir = null;
2144 }
2145 }
2146 }
2147
2148 // Perform shared library installation and dex validation and
2149 // optimization, if this is not a system app.
2150 if (mInstaller != null) {
2151 String path = scanFile.getPath();
2152 if (scanFileNewer) {
2153 Log.i(TAG, path + " changed; unpacking");
2154 try {
2155 cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2156 } catch (IOException e) {
2157 Log.e(TAG, "Failure extracting shared libs", e);
2158 if(mInstaller != null) {
2159 mInstaller.remove(pkgName);
2160 } else {
2161 dataPath.delete();
2162 }
2163 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2164 return null;
2165 }
2166 }
2167
2168 if ((scanMode&SCAN_NO_DEX) == 0
2169 && (pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
2170 int ret = 0;
2171 try {
2172 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
2173 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
2174 (scanMode&SCAN_FORWARD_LOCKED) == 0);
2175 }
2176 } catch (FileNotFoundException e) {
2177 Log.w(TAG, "Apk not found for dexopt: " + path);
2178 ret = -1;
2179 } catch (IOException e) {
2180 Log.w(TAG, "Exception reading apk: " + path, e);
2181 ret = -1;
2182 }
2183 if (ret < 0) {
2184 //error from installer
2185 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2186 return null;
2187 }
2188 }
2189 }
2190
2191 if (mFactoryTest && pkg.requestedPermissions.contains(
2192 android.Manifest.permission.FACTORY_TEST)) {
2193 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2194 }
2195
2196 if ((scanMode&SCAN_MONITOR) != 0) {
2197 pkg.mPath = destCodeFile.getAbsolutePath();
2198 mAppDirs.put(pkg.mPath, pkg);
2199 }
2200
2201 synchronized (mPackages) {
2202 // We don't expect installation to fail beyond this point
2203 // Add the new setting to mSettings
2204 mSettings.insertPackageSettingLP(pkgSetting, pkg.packageName, suid);
2205 // Add the new setting to mPackages
2206 mPackages.put(pkg.applicationInfo.packageName, pkg);
2207 int N = pkg.providers.size();
2208 StringBuilder r = null;
2209 int i;
2210 for (i=0; i<N; i++) {
2211 PackageParser.Provider p = pkg.providers.get(i);
2212 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2213 p.info.processName, pkg.applicationInfo.uid);
2214 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2215 p.info.name), p);
2216 p.syncable = p.info.isSyncable;
2217 String names[] = p.info.authority.split(";");
2218 p.info.authority = null;
2219 for (int j = 0; j < names.length; j++) {
2220 if (j == 1 && p.syncable) {
2221 // We only want the first authority for a provider to possibly be
2222 // syncable, so if we already added this provider using a different
2223 // authority clear the syncable flag. We copy the provider before
2224 // changing it because the mProviders object contains a reference
2225 // to a provider that we don't want to change.
2226 // Only do this for the second authority since the resulting provider
2227 // object can be the same for all future authorities for this provider.
2228 p = new PackageParser.Provider(p);
2229 p.syncable = false;
2230 }
2231 if (!mProviders.containsKey(names[j])) {
2232 mProviders.put(names[j], p);
2233 if (p.info.authority == null) {
2234 p.info.authority = names[j];
2235 } else {
2236 p.info.authority = p.info.authority + ";" + names[j];
2237 }
2238 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2239 Log.d(TAG, "Registered content provider: " + names[j] +
2240 ", className = " + p.info.name +
2241 ", isSyncable = " + p.info.isSyncable);
2242 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002243 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 Log.w(TAG, "Skipping provider name " + names[j] +
2245 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002246 "): name already used by "
2247 + ((other != null && other.component != null)
2248 ? other.component.getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 }
2250 }
2251 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2252 if (r == null) {
2253 r = new StringBuilder(256);
2254 } else {
2255 r.append(' ');
2256 }
2257 r.append(p.info.name);
2258 }
2259 }
2260 if (r != null) {
2261 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2262 }
2263
2264 N = pkg.services.size();
2265 r = null;
2266 for (i=0; i<N; i++) {
2267 PackageParser.Service s = pkg.services.get(i);
2268 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2269 s.info.processName, pkg.applicationInfo.uid);
2270 mServices.addService(s);
2271 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2272 if (r == null) {
2273 r = new StringBuilder(256);
2274 } else {
2275 r.append(' ');
2276 }
2277 r.append(s.info.name);
2278 }
2279 }
2280 if (r != null) {
2281 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2282 }
2283
2284 N = pkg.receivers.size();
2285 r = null;
2286 for (i=0; i<N; i++) {
2287 PackageParser.Activity a = pkg.receivers.get(i);
2288 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2289 a.info.processName, pkg.applicationInfo.uid);
2290 mReceivers.addActivity(a, "receiver");
2291 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2292 if (r == null) {
2293 r = new StringBuilder(256);
2294 } else {
2295 r.append(' ');
2296 }
2297 r.append(a.info.name);
2298 }
2299 }
2300 if (r != null) {
2301 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2302 }
2303
2304 N = pkg.activities.size();
2305 r = null;
2306 for (i=0; i<N; i++) {
2307 PackageParser.Activity a = pkg.activities.get(i);
2308 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
2309 a.info.processName, pkg.applicationInfo.uid);
2310 mActivities.addActivity(a, "activity");
2311 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2312 if (r == null) {
2313 r = new StringBuilder(256);
2314 } else {
2315 r.append(' ');
2316 }
2317 r.append(a.info.name);
2318 }
2319 }
2320 if (r != null) {
2321 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2322 }
2323
2324 N = pkg.permissionGroups.size();
2325 r = null;
2326 for (i=0; i<N; i++) {
2327 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
2328 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
2329 if (cur == null) {
2330 mPermissionGroups.put(pg.info.name, pg);
2331 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2332 if (r == null) {
2333 r = new StringBuilder(256);
2334 } else {
2335 r.append(' ');
2336 }
2337 r.append(pg.info.name);
2338 }
2339 } else {
2340 Log.w(TAG, "Permission group " + pg.info.name + " from package "
2341 + pg.info.packageName + " ignored: original from "
2342 + cur.info.packageName);
2343 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2344 if (r == null) {
2345 r = new StringBuilder(256);
2346 } else {
2347 r.append(' ');
2348 }
2349 r.append("DUP:");
2350 r.append(pg.info.name);
2351 }
2352 }
2353 }
2354 if (r != null) {
2355 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
2356 }
2357
2358 N = pkg.permissions.size();
2359 r = null;
2360 for (i=0; i<N; i++) {
2361 PackageParser.Permission p = pkg.permissions.get(i);
2362 HashMap<String, BasePermission> permissionMap =
2363 p.tree ? mSettings.mPermissionTrees
2364 : mSettings.mPermissions;
2365 p.group = mPermissionGroups.get(p.info.group);
2366 if (p.info.group == null || p.group != null) {
2367 BasePermission bp = permissionMap.get(p.info.name);
2368 if (bp == null) {
2369 bp = new BasePermission(p.info.name, p.info.packageName,
2370 BasePermission.TYPE_NORMAL);
2371 permissionMap.put(p.info.name, bp);
2372 }
2373 if (bp.perm == null) {
2374 if (bp.sourcePackage == null
2375 || bp.sourcePackage.equals(p.info.packageName)) {
2376 BasePermission tree = findPermissionTreeLP(p.info.name);
2377 if (tree == null
2378 || tree.sourcePackage.equals(p.info.packageName)) {
2379 bp.perm = p;
2380 bp.uid = pkg.applicationInfo.uid;
2381 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2382 if (r == null) {
2383 r = new StringBuilder(256);
2384 } else {
2385 r.append(' ');
2386 }
2387 r.append(p.info.name);
2388 }
2389 } else {
2390 Log.w(TAG, "Permission " + p.info.name + " from package "
2391 + p.info.packageName + " ignored: base tree "
2392 + tree.name + " is from package "
2393 + tree.sourcePackage);
2394 }
2395 } else {
2396 Log.w(TAG, "Permission " + p.info.name + " from package "
2397 + p.info.packageName + " ignored: original from "
2398 + bp.sourcePackage);
2399 }
2400 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2401 if (r == null) {
2402 r = new StringBuilder(256);
2403 } else {
2404 r.append(' ');
2405 }
2406 r.append("DUP:");
2407 r.append(p.info.name);
2408 }
2409 } else {
2410 Log.w(TAG, "Permission " + p.info.name + " from package "
2411 + p.info.packageName + " ignored: no group "
2412 + p.group);
2413 }
2414 }
2415 if (r != null) {
2416 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2417 }
2418
2419 N = pkg.instrumentation.size();
2420 r = null;
2421 for (i=0; i<N; i++) {
2422 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2423 a.info.packageName = pkg.applicationInfo.packageName;
2424 a.info.sourceDir = pkg.applicationInfo.sourceDir;
2425 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
2426 a.info.dataDir = pkg.applicationInfo.dataDir;
2427 mInstrumentation.put(a.component, a);
2428 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2429 if (r == null) {
2430 r = new StringBuilder(256);
2431 } else {
2432 r.append(' ');
2433 }
2434 r.append(a.info.name);
2435 }
2436 }
2437 if (r != null) {
2438 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2439 }
2440
2441 pkgSetting.setTimeStamp(scanFileTime);
2442 }
2443
2444 return pkg;
2445 }
2446
2447 private void cachePackageSharedLibsLI(PackageParser.Package pkg,
2448 File dataPath, File scanFile) throws IOException {
2449 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
2450 final String sharedLibraryABI = "armeabi";
2451 final String apkLibraryDirectory = "lib/" + sharedLibraryABI + "/";
2452 final String apkSharedLibraryPrefix = apkLibraryDirectory + "lib";
2453 final String sharedLibrarySuffix = ".so";
2454 boolean createdSharedLib = false;
2455 try {
2456 ZipFile zipFile = new ZipFile(scanFile);
2457 Enumeration<ZipEntry> entries =
2458 (Enumeration<ZipEntry>) zipFile.entries();
2459
2460 while (entries.hasMoreElements()) {
2461 ZipEntry entry = entries.nextElement();
2462 if (entry.isDirectory()) {
2463 continue;
2464 }
2465 String entryName = entry.getName();
2466 if (! (entryName.startsWith(apkSharedLibraryPrefix)
2467 && entryName.endsWith(sharedLibrarySuffix))) {
2468 continue;
2469 }
2470 String libFileName = entryName.substring(
2471 apkLibraryDirectory.length());
2472 if (libFileName.contains("/")
2473 || (!FileUtils.isFilenameSafe(new File(libFileName)))) {
2474 continue;
2475 }
2476 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
2477 File.separator + libFileName;
2478 File sharedLibraryFile = new File(sharedLibraryFilePath);
2479 if (! sharedLibraryFile.exists() ||
2480 sharedLibraryFile.length() != entry.getSize() ||
2481 sharedLibraryFile.lastModified() != entry.getTime()) {
2482 if (Config.LOGD) {
2483 Log.d(TAG, "Caching shared lib " + entry.getName());
2484 }
2485 if (mInstaller == null) {
2486 sharedLibraryDir.mkdir();
2487 createdSharedLib = true;
2488 }
2489 cacheSharedLibLI(pkg, zipFile, entry, sharedLibraryDir,
2490 sharedLibraryFile);
2491 }
2492 }
2493 } catch (IOException e) {
2494 Log.e(TAG, "Failed to cache package shared libs", e);
2495 if(createdSharedLib) {
2496 sharedLibraryDir.delete();
2497 }
2498 throw e;
2499 }
2500 }
2501
2502 private void cacheSharedLibLI(PackageParser.Package pkg,
2503 ZipFile zipFile, ZipEntry entry,
2504 File sharedLibraryDir,
2505 File sharedLibraryFile) throws IOException {
2506 InputStream inputStream = zipFile.getInputStream(entry);
2507 try {
2508 File tempFile = File.createTempFile("tmp", "tmp", sharedLibraryDir);
2509 String tempFilePath = tempFile.getPath();
2510 // XXX package manager can't change owner, so the lib files for
2511 // now need to be left as world readable and owned by the system.
2512 if (! FileUtils.copyToFile(inputStream, tempFile) ||
2513 ! tempFile.setLastModified(entry.getTime()) ||
2514 FileUtils.setPermissions(tempFilePath,
2515 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
2516 |FileUtils.S_IROTH, -1, -1) != 0 ||
2517 ! tempFile.renameTo(sharedLibraryFile)) {
2518 // Failed to properly write file.
2519 tempFile.delete();
2520 throw new IOException("Couldn't create cached shared lib "
2521 + sharedLibraryFile + " in " + sharedLibraryDir);
2522 }
2523 } finally {
2524 inputStream.close();
2525 }
2526 }
2527
2528 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
2529 if (chatty && Config.LOGD) Log.d(
2530 TAG, "Removing package " + pkg.applicationInfo.packageName );
2531
2532 synchronized (mPackages) {
2533 if (pkg.mPreferredOrder > 0) {
2534 mSettings.mPreferredPackages.remove(pkg);
2535 pkg.mPreferredOrder = 0;
2536 updatePreferredIndicesLP();
2537 }
2538
2539 clearPackagePreferredActivitiesLP(pkg.packageName);
2540
2541 mPackages.remove(pkg.applicationInfo.packageName);
2542 if (pkg.mPath != null) {
2543 mAppDirs.remove(pkg.mPath);
2544 }
2545
2546 PackageSetting ps = (PackageSetting)pkg.mExtras;
2547 if (ps != null && ps.sharedUser != null) {
2548 // XXX don't do this until the data is removed.
2549 if (false) {
2550 ps.sharedUser.packages.remove(ps);
2551 if (ps.sharedUser.packages.size() == 0) {
2552 // Remove.
2553 }
2554 }
2555 }
2556
2557 int N = pkg.providers.size();
2558 StringBuilder r = null;
2559 int i;
2560 for (i=0; i<N; i++) {
2561 PackageParser.Provider p = pkg.providers.get(i);
2562 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
2563 p.info.name));
2564 if (p.info.authority == null) {
2565
2566 /* The is another ContentProvider with this authority when
2567 * this app was installed so this authority is null,
2568 * Ignore it as we don't have to unregister the provider.
2569 */
2570 continue;
2571 }
2572 String names[] = p.info.authority.split(";");
2573 for (int j = 0; j < names.length; j++) {
2574 if (mProviders.get(names[j]) == p) {
2575 mProviders.remove(names[j]);
2576 if (chatty && Config.LOGD) Log.d(
2577 TAG, "Unregistered content provider: " + names[j] +
2578 ", className = " + p.info.name +
2579 ", isSyncable = " + p.info.isSyncable);
2580 }
2581 }
2582 if (chatty) {
2583 if (r == null) {
2584 r = new StringBuilder(256);
2585 } else {
2586 r.append(' ');
2587 }
2588 r.append(p.info.name);
2589 }
2590 }
2591 if (r != null) {
2592 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2593 }
2594
2595 N = pkg.services.size();
2596 r = null;
2597 for (i=0; i<N; i++) {
2598 PackageParser.Service s = pkg.services.get(i);
2599 mServices.removeService(s);
2600 if (chatty) {
2601 if (r == null) {
2602 r = new StringBuilder(256);
2603 } else {
2604 r.append(' ');
2605 }
2606 r.append(s.info.name);
2607 }
2608 }
2609 if (r != null) {
2610 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2611 }
2612
2613 N = pkg.receivers.size();
2614 r = null;
2615 for (i=0; i<N; i++) {
2616 PackageParser.Activity a = pkg.receivers.get(i);
2617 mReceivers.removeActivity(a, "receiver");
2618 if (chatty) {
2619 if (r == null) {
2620 r = new StringBuilder(256);
2621 } else {
2622 r.append(' ');
2623 }
2624 r.append(a.info.name);
2625 }
2626 }
2627 if (r != null) {
2628 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
2629 }
2630
2631 N = pkg.activities.size();
2632 r = null;
2633 for (i=0; i<N; i++) {
2634 PackageParser.Activity a = pkg.activities.get(i);
2635 mActivities.removeActivity(a, "activity");
2636 if (chatty) {
2637 if (r == null) {
2638 r = new StringBuilder(256);
2639 } else {
2640 r.append(' ');
2641 }
2642 r.append(a.info.name);
2643 }
2644 }
2645 if (r != null) {
2646 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
2647 }
2648
2649 N = pkg.permissions.size();
2650 r = null;
2651 for (i=0; i<N; i++) {
2652 PackageParser.Permission p = pkg.permissions.get(i);
2653 boolean tree = false;
2654 BasePermission bp = mSettings.mPermissions.get(p.info.name);
2655 if (bp == null) {
2656 tree = true;
2657 bp = mSettings.mPermissionTrees.get(p.info.name);
2658 }
2659 if (bp != null && bp.perm == p) {
2660 if (bp.type != BasePermission.TYPE_BUILTIN) {
2661 if (tree) {
2662 mSettings.mPermissionTrees.remove(p.info.name);
2663 } else {
2664 mSettings.mPermissions.remove(p.info.name);
2665 }
2666 } else {
2667 bp.perm = null;
2668 }
2669 if (chatty) {
2670 if (r == null) {
2671 r = new StringBuilder(256);
2672 } else {
2673 r.append(' ');
2674 }
2675 r.append(p.info.name);
2676 }
2677 }
2678 }
2679 if (r != null) {
2680 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
2681 }
2682
2683 N = pkg.instrumentation.size();
2684 r = null;
2685 for (i=0; i<N; i++) {
2686 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
2687 mInstrumentation.remove(a.component);
2688 if (chatty) {
2689 if (r == null) {
2690 r = new StringBuilder(256);
2691 } else {
2692 r.append(' ');
2693 }
2694 r.append(a.info.name);
2695 }
2696 }
2697 if (r != null) {
2698 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
2699 }
2700 }
2701 }
2702
2703 private static final boolean isPackageFilename(String name) {
2704 return name != null && name.endsWith(".apk");
2705 }
2706
2707 private void updatePermissionsLP() {
2708 // Make sure there are no dangling permission trees.
2709 Iterator<BasePermission> it = mSettings.mPermissionTrees
2710 .values().iterator();
2711 while (it.hasNext()) {
2712 BasePermission bp = it.next();
2713 if (bp.perm == null) {
2714 Log.w(TAG, "Removing dangling permission tree: " + bp.name
2715 + " from package " + bp.sourcePackage);
2716 it.remove();
2717 }
2718 }
2719
2720 // Make sure all dynamic permissions have been assigned to a package,
2721 // and make sure there are no dangling permissions.
2722 it = mSettings.mPermissions.values().iterator();
2723 while (it.hasNext()) {
2724 BasePermission bp = it.next();
2725 if (bp.type == BasePermission.TYPE_DYNAMIC) {
2726 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
2727 + bp.name + " pkg=" + bp.sourcePackage
2728 + " info=" + bp.pendingInfo);
2729 if (bp.perm == null && bp.pendingInfo != null) {
2730 BasePermission tree = findPermissionTreeLP(bp.name);
2731 if (tree != null) {
2732 bp.perm = new PackageParser.Permission(tree.perm.owner,
2733 new PermissionInfo(bp.pendingInfo));
2734 bp.perm.info.packageName = tree.perm.info.packageName;
2735 bp.perm.info.name = bp.name;
2736 bp.uid = tree.uid;
2737 }
2738 }
2739 }
2740 if (bp.perm == null) {
2741 Log.w(TAG, "Removing dangling permission: " + bp.name
2742 + " from package " + bp.sourcePackage);
2743 it.remove();
2744 }
2745 }
2746
2747 // Now update the permissions for all packages, in particular
2748 // replace the granted permissions of the system packages.
2749 for (PackageParser.Package pkg : mPackages.values()) {
2750 grantPermissionsLP(pkg, false);
2751 }
2752 }
2753
2754 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
2755 final PackageSetting ps = (PackageSetting)pkg.mExtras;
2756 if (ps == null) {
2757 return;
2758 }
2759 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2760 boolean addedPermission = false;
2761
2762 if (replace) {
2763 ps.permissionsFixed = false;
2764 if (gp == ps) {
2765 gp.grantedPermissions.clear();
2766 gp.gids = mGlobalGids;
2767 }
2768 }
2769
2770 if (gp.gids == null) {
2771 gp.gids = mGlobalGids;
2772 }
2773
2774 final int N = pkg.requestedPermissions.size();
2775 for (int i=0; i<N; i++) {
2776 String name = pkg.requestedPermissions.get(i);
2777 BasePermission bp = mSettings.mPermissions.get(name);
2778 PackageParser.Permission p = bp != null ? bp.perm : null;
2779 if (false) {
2780 if (gp != ps) {
2781 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
2782 + ": " + p);
2783 }
2784 }
2785 if (p != null) {
2786 final String perm = p.info.name;
2787 boolean allowed;
2788 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
2789 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
2790 allowed = true;
2791 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
2792 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
2793 allowed = (checkSignaturesLP(p.owner, pkg)
2794 == PackageManager.SIGNATURE_MATCH)
2795 || (checkSignaturesLP(mPlatformPackage, pkg)
2796 == PackageManager.SIGNATURE_MATCH);
2797 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
2798 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
2799 // For updated system applications, the signatureOrSystem permission
2800 // is granted only if it had been defined by the original application.
2801 if ((pkg.applicationInfo.flags
2802 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
2803 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
2804 if(sysPs.grantedPermissions.contains(perm)) {
2805 allowed = true;
2806 } else {
2807 allowed = false;
2808 }
2809 } else {
2810 allowed = true;
2811 }
2812 }
2813 }
2814 } else {
2815 allowed = false;
2816 }
2817 if (false) {
2818 if (gp != ps) {
2819 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
2820 }
2821 }
2822 if (allowed) {
2823 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
2824 && ps.permissionsFixed) {
2825 // If this is an existing, non-system package, then
2826 // we can't add any new permissions to it.
2827 if (!gp.loadedPermissions.contains(perm)) {
2828 allowed = false;
Dianne Hackborna96cbb42009-05-13 15:06:13 -07002829 // Except... if this is a permission that was added
2830 // to the platform (note: need to only do this when
2831 // updating the platform).
2832 final int NP = PackageParser.NEW_PERMISSIONS.length;
2833 for (int ip=0; ip<NP; ip++) {
2834 final PackageParser.NewPermissionInfo npi
2835 = PackageParser.NEW_PERMISSIONS[ip];
2836 if (npi.name.equals(perm)
2837 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
2838 allowed = true;
2839 Log.i(TAG, "Auto-granting WRITE_SDCARD to old pkg "
2840 + pkg.packageName);
2841 break;
2842 }
2843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 }
2845 }
2846 if (allowed) {
2847 if (!gp.grantedPermissions.contains(perm)) {
2848 addedPermission = true;
2849 gp.grantedPermissions.add(perm);
2850 gp.gids = appendInts(gp.gids, bp.gids);
2851 }
2852 } else {
2853 Log.w(TAG, "Not granting permission " + perm
2854 + " to package " + pkg.packageName
2855 + " because it was previously installed without");
2856 }
2857 } else {
2858 Log.w(TAG, "Not granting permission " + perm
2859 + " to package " + pkg.packageName
2860 + " (protectionLevel=" + p.info.protectionLevel
2861 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
2862 + ")");
2863 }
2864 } else {
2865 Log.w(TAG, "Unknown permission " + name
2866 + " in package " + pkg.packageName);
2867 }
2868 }
2869
2870 if ((addedPermission || replace) && !ps.permissionsFixed &&
2871 (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2872 // This is the first that we have heard about this package, so the
2873 // permissions we have now selected are fixed until explicitly
2874 // changed.
2875 ps.permissionsFixed = true;
2876 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
2877 }
2878 }
2879
2880 private final class ActivityIntentResolver
2881 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02002882 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02002884 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 }
2886
Mihai Preda074edef2009-05-18 17:13:31 +02002887 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02002889 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2891 }
2892
Mihai Predaeae850c2009-05-13 10:13:48 +02002893 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
2894 ArrayList<PackageParser.Activity> packageActivities) {
2895 if (packageActivities == null) {
2896 return null;
2897 }
2898 mFlags = flags;
2899 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
2900 int N = packageActivities.size();
2901 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
2902 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
2903 for (int i = 0; i < N; ++i) {
2904 listCut.add(packageActivities.get(i).intents);
2905 }
2906 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
2907 }
2908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 public final void addActivity(PackageParser.Activity a, String type) {
2910 mActivities.put(a.component, a);
2911 if (SHOW_INFO || Config.LOGV) Log.v(
2912 TAG, " " + type + " " +
2913 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
2914 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
2915 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02002916 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
2918 if (SHOW_INFO || Config.LOGV) {
2919 Log.v(TAG, " IntentFilter:");
2920 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2921 }
2922 if (!intent.debugCheck()) {
2923 Log.w(TAG, "==> For Activity " + a.info.name);
2924 }
2925 addFilter(intent);
2926 }
2927 }
2928
2929 public final void removeActivity(PackageParser.Activity a, String type) {
2930 mActivities.remove(a.component);
2931 if (SHOW_INFO || Config.LOGV) Log.v(
2932 TAG, " " + type + " " +
2933 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
2934 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
2935 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02002936 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
2938 if (SHOW_INFO || Config.LOGV) {
2939 Log.v(TAG, " IntentFilter:");
2940 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2941 }
2942 removeFilter(intent);
2943 }
2944 }
2945
2946 @Override
2947 protected boolean allowFilterResult(
2948 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
2949 ActivityInfo filterAi = filter.activity.info;
2950 for (int i=dest.size()-1; i>=0; i--) {
2951 ActivityInfo destAi = dest.get(i).activityInfo;
2952 if (destAi.name == filterAi.name
2953 && destAi.packageName == filterAi.packageName) {
2954 return false;
2955 }
2956 }
2957 return true;
2958 }
2959
2960 @Override
2961 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
2962 int match) {
2963 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
2964 return null;
2965 }
2966 final PackageParser.Activity activity = info.activity;
2967 if (mSafeMode && (activity.info.applicationInfo.flags
2968 &ApplicationInfo.FLAG_SYSTEM) == 0) {
2969 return null;
2970 }
2971 final ResolveInfo res = new ResolveInfo();
2972 res.activityInfo = PackageParser.generateActivityInfo(activity,
2973 mFlags);
2974 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
2975 res.filter = info;
2976 }
2977 res.priority = info.getPriority();
2978 res.preferredOrder = activity.owner.mPreferredOrder;
2979 //System.out.println("Result: " + res.activityInfo.className +
2980 // " = " + res.priority);
2981 res.match = match;
2982 res.isDefault = info.hasDefault;
2983 res.labelRes = info.labelRes;
2984 res.nonLocalizedLabel = info.nonLocalizedLabel;
2985 res.icon = info.icon;
2986 return res;
2987 }
2988
2989 @Override
2990 protected void sortResults(List<ResolveInfo> results) {
2991 Collections.sort(results, mResolvePrioritySorter);
2992 }
2993
2994 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002995 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002997 out.print(prefix); out.print(
2998 Integer.toHexString(System.identityHashCode(filter.activity)));
2999 out.print(' ');
3000 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 }
3002
3003// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3004// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3005// final List<ResolveInfo> retList = Lists.newArrayList();
3006// while (i.hasNext()) {
3007// final ResolveInfo resolveInfo = i.next();
3008// if (isEnabledLP(resolveInfo.activityInfo)) {
3009// retList.add(resolveInfo);
3010// }
3011// }
3012// return retList;
3013// }
3014
3015 // Keys are String (activity class name), values are Activity.
3016 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3017 = new HashMap<ComponentName, PackageParser.Activity>();
3018 private int mFlags;
3019 }
3020
3021 private final class ServiceIntentResolver
3022 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003023 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003025 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 }
3027
Mihai Preda074edef2009-05-18 17:13:31 +02003028 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003030 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3032 }
3033
3034 public final void addService(PackageParser.Service s) {
3035 mServices.put(s.component, s);
3036 if (SHOW_INFO || Config.LOGV) Log.v(
3037 TAG, " " + (s.info.nonLocalizedLabel != null
3038 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3039 if (SHOW_INFO || Config.LOGV) Log.v(
3040 TAG, " Class=" + s.info.name);
3041 int NI = s.intents.size();
3042 int j;
3043 for (j=0; j<NI; j++) {
3044 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3045 if (SHOW_INFO || Config.LOGV) {
3046 Log.v(TAG, " IntentFilter:");
3047 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3048 }
3049 if (!intent.debugCheck()) {
3050 Log.w(TAG, "==> For Service " + s.info.name);
3051 }
3052 addFilter(intent);
3053 }
3054 }
3055
3056 public final void removeService(PackageParser.Service s) {
3057 mServices.remove(s.component);
3058 if (SHOW_INFO || Config.LOGV) Log.v(
3059 TAG, " " + (s.info.nonLocalizedLabel != null
3060 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3061 if (SHOW_INFO || Config.LOGV) Log.v(
3062 TAG, " Class=" + s.info.name);
3063 int NI = s.intents.size();
3064 int j;
3065 for (j=0; j<NI; j++) {
3066 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3067 if (SHOW_INFO || Config.LOGV) {
3068 Log.v(TAG, " IntentFilter:");
3069 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3070 }
3071 removeFilter(intent);
3072 }
3073 }
3074
3075 @Override
3076 protected boolean allowFilterResult(
3077 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3078 ServiceInfo filterSi = filter.service.info;
3079 for (int i=dest.size()-1; i>=0; i--) {
3080 ServiceInfo destAi = dest.get(i).serviceInfo;
3081 if (destAi.name == filterSi.name
3082 && destAi.packageName == filterSi.packageName) {
3083 return false;
3084 }
3085 }
3086 return true;
3087 }
3088
3089 @Override
3090 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3091 int match) {
3092 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3093 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3094 return null;
3095 }
3096 final PackageParser.Service service = info.service;
3097 if (mSafeMode && (service.info.applicationInfo.flags
3098 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3099 return null;
3100 }
3101 final ResolveInfo res = new ResolveInfo();
3102 res.serviceInfo = PackageParser.generateServiceInfo(service,
3103 mFlags);
3104 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3105 res.filter = filter;
3106 }
3107 res.priority = info.getPriority();
3108 res.preferredOrder = service.owner.mPreferredOrder;
3109 //System.out.println("Result: " + res.activityInfo.className +
3110 // " = " + res.priority);
3111 res.match = match;
3112 res.isDefault = info.hasDefault;
3113 res.labelRes = info.labelRes;
3114 res.nonLocalizedLabel = info.nonLocalizedLabel;
3115 res.icon = info.icon;
3116 return res;
3117 }
3118
3119 @Override
3120 protected void sortResults(List<ResolveInfo> results) {
3121 Collections.sort(results, mResolvePrioritySorter);
3122 }
3123
3124 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003125 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003127 out.print(prefix); out.print(
3128 Integer.toHexString(System.identityHashCode(filter.service)));
3129 out.print(' ');
3130 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 }
3132
3133// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3134// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3135// final List<ResolveInfo> retList = Lists.newArrayList();
3136// while (i.hasNext()) {
3137// final ResolveInfo resolveInfo = (ResolveInfo) i;
3138// if (isEnabledLP(resolveInfo.serviceInfo)) {
3139// retList.add(resolveInfo);
3140// }
3141// }
3142// return retList;
3143// }
3144
3145 // Keys are String (activity class name), values are Activity.
3146 private final HashMap<ComponentName, PackageParser.Service> mServices
3147 = new HashMap<ComponentName, PackageParser.Service>();
3148 private int mFlags;
3149 };
3150
3151 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3152 new Comparator<ResolveInfo>() {
3153 public int compare(ResolveInfo r1, ResolveInfo r2) {
3154 int v1 = r1.priority;
3155 int v2 = r2.priority;
3156 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3157 if (v1 != v2) {
3158 return (v1 > v2) ? -1 : 1;
3159 }
3160 v1 = r1.preferredOrder;
3161 v2 = r2.preferredOrder;
3162 if (v1 != v2) {
3163 return (v1 > v2) ? -1 : 1;
3164 }
3165 if (r1.isDefault != r2.isDefault) {
3166 return r1.isDefault ? -1 : 1;
3167 }
3168 v1 = r1.match;
3169 v2 = r2.match;
3170 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3171 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3172 }
3173 };
3174
3175 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3176 new Comparator<ProviderInfo>() {
3177 public int compare(ProviderInfo p1, ProviderInfo p2) {
3178 final int v1 = p1.initOrder;
3179 final int v2 = p2.initOrder;
3180 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3181 }
3182 };
3183
3184 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3185 IActivityManager am = ActivityManagerNative.getDefault();
3186 if (am != null) {
3187 try {
3188 final Intent intent = new Intent(action,
3189 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3190 if (extras != null) {
3191 intent.putExtras(extras);
3192 }
3193 am.broadcastIntent(
3194 null, intent,
3195 null, null, 0, null, null, null, false, false);
3196 } catch (RemoteException ex) {
3197 }
3198 }
3199 }
3200
3201 private final class AppDirObserver extends FileObserver {
3202 public AppDirObserver(String path, int mask, boolean isrom) {
3203 super(path, mask);
3204 mRootDir = path;
3205 mIsRom = isrom;
3206 }
3207
3208 public void onEvent(int event, String path) {
3209 String removedPackage = null;
3210 int removedUid = -1;
3211 String addedPackage = null;
3212 int addedUid = -1;
3213
3214 synchronized (mInstallLock) {
3215 String fullPathStr = null;
3216 File fullPath = null;
3217 if (path != null) {
3218 fullPath = new File(mRootDir, path);
3219 fullPathStr = fullPath.getPath();
3220 }
3221
3222 if (Config.LOGV) Log.v(
3223 TAG, "File " + fullPathStr + " changed: "
3224 + Integer.toHexString(event));
3225
3226 if (!isPackageFilename(path)) {
3227 if (Config.LOGV) Log.v(
3228 TAG, "Ignoring change of non-package file: " + fullPathStr);
3229 return;
3230 }
3231
3232 if ((event&REMOVE_EVENTS) != 0) {
3233 synchronized (mInstallLock) {
3234 PackageParser.Package p = mAppDirs.get(fullPathStr);
3235 if (p != null) {
3236 removePackageLI(p, true);
3237 removedPackage = p.applicationInfo.packageName;
3238 removedUid = p.applicationInfo.uid;
3239 }
3240 }
3241 }
3242
3243 if ((event&ADD_EVENTS) != 0) {
3244 PackageParser.Package p = mAppDirs.get(fullPathStr);
3245 if (p == null) {
3246 p = scanPackageLI(fullPath, fullPath, fullPath,
3247 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3248 PackageParser.PARSE_CHATTY |
3249 PackageParser.PARSE_MUST_BE_APK,
3250 SCAN_MONITOR);
3251 if (p != null) {
3252 synchronized (mPackages) {
3253 grantPermissionsLP(p, false);
3254 }
3255 addedPackage = p.applicationInfo.packageName;
3256 addedUid = p.applicationInfo.uid;
3257 }
3258 }
3259 }
3260
3261 synchronized (mPackages) {
3262 mSettings.writeLP();
3263 }
3264 }
3265
3266 if (removedPackage != null) {
3267 Bundle extras = new Bundle(1);
3268 extras.putInt(Intent.EXTRA_UID, removedUid);
3269 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3270 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3271 }
3272 if (addedPackage != null) {
3273 Bundle extras = new Bundle(1);
3274 extras.putInt(Intent.EXTRA_UID, addedUid);
3275 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3276 }
3277 }
3278
3279 private final String mRootDir;
3280 private final boolean mIsRom;
3281 }
Jacek Surazskic64322c2009-04-28 15:26:38 +02003282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 /* Called when a downloaded package installation has been confirmed by the user */
3284 public void installPackage(
3285 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazskic64322c2009-04-28 15:26:38 +02003286 installPackage(packageURI, observer, flags, null);
3287 }
3288
3289 /* Called when a downloaded package installation has been confirmed by the user */
3290 public void installPackage(
3291 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3292 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 mContext.enforceCallingOrSelfPermission(
3294 android.Manifest.permission.INSTALL_PACKAGES, null);
Jacek Surazskic64322c2009-04-28 15:26:38 +02003295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 // Queue up an async operation since the package installation may take a little while.
3297 mHandler.post(new Runnable() {
3298 public void run() {
3299 mHandler.removeCallbacks(this);
3300 PackageInstalledInfo res;
3301 synchronized (mInstallLock) {
Jacek Surazskic64322c2009-04-28 15:26:38 +02003302 res = installPackageLI(packageURI, flags, true, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 }
3304 if (observer != null) {
3305 try {
3306 observer.packageInstalled(res.name, res.returnCode);
3307 } catch (RemoteException e) {
3308 Log.i(TAG, "Observer no longer exists.");
3309 }
3310 }
3311 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
3312 // call appears in the synchronized block above.
3313 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3314 res.removedInfo.sendBroadcast(false, true);
3315 Bundle extras = new Bundle(1);
3316 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003317 final boolean update = res.removedInfo.removedPackage != null;
3318 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 extras.putBoolean(Intent.EXTRA_REPLACING, true);
3320 }
3321 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
3322 res.pkg.applicationInfo.packageName,
3323 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003324 if (update) {
3325 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
3326 res.pkg.applicationInfo.packageName,
3327 extras);
3328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 }
3330 Runtime.getRuntime().gc();
3331 }
3332 });
3333 }
3334
3335 class PackageInstalledInfo {
3336 String name;
3337 int uid;
3338 PackageParser.Package pkg;
3339 int returnCode;
3340 PackageRemovedInfo removedInfo;
3341 }
3342
3343 /*
3344 * Install a non-existing package.
3345 */
3346 private void installNewPackageLI(String pkgName,
3347 File tmpPackageFile,
3348 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003349 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003350 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 // Remember this for later, in case we need to rollback this install
3352 boolean dataDirExists = (new File(mAppDataDir, pkgName)).exists();
3353 res.name = pkgName;
3354 synchronized(mPackages) {
3355 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(destFilePath)) {
3356 // Don't allow installation over an existing package with the same name.
3357 Log.w(TAG, "Attempt to re-install " + pkgName
3358 + " without first uninstalling.");
3359 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
3360 return;
3361 }
3362 }
3363 if (destPackageFile.exists()) {
3364 // It's safe to do this because we know (from the above check) that the file
3365 // isn't currently used for an installed package.
3366 destPackageFile.delete();
3367 }
3368 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3369 PackageParser.Package newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3370 destResourceFile, pkg, 0,
3371 SCAN_MONITOR | SCAN_FORCE_DEX
3372 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003373 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3374 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 if (newPackage == null) {
3376 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3377 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3378 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3379 }
3380 } else {
3381 updateSettingsLI(pkgName, tmpPackageFile,
3382 destFilePath, destPackageFile,
3383 destResourceFile, pkg,
3384 newPackage,
3385 true,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003386 forwardLocked,
3387 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 res);
3389 // delete the partially installed application. the data directory will have to be
3390 // restored if it was already existing
3391 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3392 // remove package from internal structures. Note that we want deletePackageX to
3393 // delete the package data and cache directories that it created in
3394 // scanPackageLocked, unless those directories existed before we even tried to
3395 // install.
3396 deletePackageLI(
3397 pkgName, true,
3398 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
3399 res.removedInfo);
3400 }
3401 }
3402 }
3403
3404 private void replacePackageLI(String pkgName,
3405 File tmpPackageFile,
3406 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003407 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003408 String installerPackageName, PackageInstalledInfo res) {
3409
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003410 PackageParser.Package oldPackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 // First find the old package info and check signatures
3412 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003413 oldPackage = mPackages.get(pkgName);
3414 if(checkSignaturesLP(pkg, oldPackage) != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3416 return;
3417 }
3418 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003419 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 if(sysPkg) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003421 replaceSystemPackageLI(oldPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003423 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003424 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 } else {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003426 replaceNonSystemPackageLI(oldPackage, tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003427 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003428 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 }
3430 }
3431
3432 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
3433 File tmpPackageFile,
3434 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003435 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003436 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 PackageParser.Package newPackage = null;
3438 String pkgName = deletedPackage.packageName;
3439 boolean deletedPkg = true;
3440 boolean updatedSettings = false;
Jacek Surazskic64322c2009-04-28 15:26:38 +02003441
3442 String oldInstallerPackageName = null;
3443 synchronized (mPackages) {
3444 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
3445 }
3446
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003447 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 // First delete the existing package while retaining the data directory
3449 if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
3450 res.removedInfo)) {
3451 // If the existing package was'nt successfully deleted
3452 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3453 deletedPkg = false;
3454 } else {
3455 // Successfully deleted the old package. Now proceed with re-installation
3456 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3457 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3458 destResourceFile, pkg, parseFlags,
3459 SCAN_MONITOR | SCAN_FORCE_DEX
3460 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003461 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3462 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 if (newPackage == null) {
3464 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3465 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3466 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3467 }
3468 } else {
3469 updateSettingsLI(pkgName, tmpPackageFile,
3470 destFilePath, destPackageFile,
3471 destResourceFile, pkg,
3472 newPackage,
3473 true,
3474 forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003475 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 res);
3477 updatedSettings = true;
3478 }
3479 }
3480
3481 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3482 // If we deleted an exisiting package, the old source and resource files that we
3483 // were keeping around in case we needed them (see below) can now be deleted
3484 final ApplicationInfo deletedPackageAppInfo = deletedPackage.applicationInfo;
3485 final ApplicationInfo installedPackageAppInfo =
3486 newPackage.applicationInfo;
3487 if (!deletedPackageAppInfo.sourceDir
3488 .equals(installedPackageAppInfo.sourceDir)) {
3489 new File(deletedPackageAppInfo.sourceDir).delete();
3490 }
3491 if (!deletedPackageAppInfo.publicSourceDir
3492 .equals(installedPackageAppInfo.publicSourceDir)) {
3493 new File(deletedPackageAppInfo.publicSourceDir).delete();
3494 }
3495 //update signature on the new package setting
3496 //this should always succeed, since we checked the
3497 //signature earlier.
3498 synchronized(mPackages) {
3499 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
3500 parseFlags, true);
3501 }
3502 } else {
3503 // remove package from internal structures. Note that we want deletePackageX to
3504 // delete the package data and cache directories that it created in
3505 // scanPackageLocked, unless those directories existed before we even tried to
3506 // install.
3507 if(updatedSettings) {
3508 deletePackageLI(
3509 pkgName, true,
3510 PackageManager.DONT_DELETE_DATA,
3511 res.removedInfo);
3512 }
3513 // Since we failed to install the new package we need to restore the old
3514 // package that we deleted.
3515 if(deletedPkg) {
3516 installPackageLI(
3517 Uri.fromFile(new File(deletedPackage.mPath)),
3518 isForwardLocked(deletedPackage)
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003519 ? PackageManager.INSTALL_FORWARD_LOCK
Jacek Surazskic64322c2009-04-28 15:26:38 +02003520 : 0, false, oldInstallerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 }
3522 }
3523 }
3524
3525 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
3526 File tmpPackageFile,
3527 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003528 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003529 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 PackageParser.Package newPackage = null;
3531 boolean updatedSettings = false;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003532 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 PackageParser.PARSE_IS_SYSTEM;
3534 String packageName = deletedPackage.packageName;
3535 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3536 if (packageName == null) {
3537 Log.w(TAG, "Attempt to delete null packageName.");
3538 return;
3539 }
3540 PackageParser.Package oldPkg;
3541 PackageSetting oldPkgSetting;
3542 synchronized (mPackages) {
3543 oldPkg = mPackages.get(packageName);
3544 oldPkgSetting = mSettings.mPackages.get(packageName);
3545 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
3546 (oldPkgSetting == null)) {
3547 Log.w(TAG, "Could'nt find package:"+packageName+" information");
3548 return;
3549 }
3550 }
3551 res.removedInfo.uid = oldPkg.applicationInfo.uid;
3552 res.removedInfo.removedPackage = packageName;
3553 // Remove existing system package
3554 removePackageLI(oldPkg, true);
3555 synchronized (mPackages) {
3556 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
3557 }
3558
3559 // Successfully disabled the old package. Now proceed with re-installation
3560 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3561 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3562 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3563 destResourceFile, pkg, parseFlags,
3564 SCAN_MONITOR | SCAN_FORCE_DEX
3565 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003566 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3567 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 if (newPackage == null) {
3569 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3570 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3571 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3572 }
3573 } else {
3574 updateSettingsLI(packageName, tmpPackageFile,
3575 destFilePath, destPackageFile,
3576 destResourceFile, pkg,
3577 newPackage,
3578 true,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003579 forwardLocked,
3580 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 res);
3582 updatedSettings = true;
3583 }
3584
3585 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3586 //update signature on the new package setting
3587 //this should always succeed, since we checked the
3588 //signature earlier.
3589 synchronized(mPackages) {
3590 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
3591 parseFlags, true);
3592 }
3593 } else {
3594 // Re installation failed. Restore old information
3595 // Remove new pkg information
Dianne Hackborna96cbb42009-05-13 15:06:13 -07003596 if (newPackage != null) {
3597 removePackageLI(newPackage, true);
3598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 // Add back the old system package
3600 scanPackageLI(oldPkgSetting.codePath, oldPkgSetting.codePath,
3601 oldPkgSetting.resourcePath,
3602 oldPkg, parseFlags,
3603 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07003604 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003605 // Restore the old system information in Settings
3606 synchronized(mPackages) {
3607 if(updatedSettings) {
3608 mSettings.enableSystemPackageLP(packageName);
Jacek Surazskic64322c2009-04-28 15:26:38 +02003609 mSettings.setInstallerPackageName(packageName,
3610 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 }
3612 mSettings.writeLP();
3613 }
3614 }
3615 }
3616
3617 private void updateSettingsLI(String pkgName, File tmpPackageFile,
3618 String destFilePath, File destPackageFile,
3619 File destResourceFile,
3620 PackageParser.Package pkg,
3621 PackageParser.Package newPackage,
3622 boolean replacingExistingPackage,
3623 boolean forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003624 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 synchronized (mPackages) {
3626 //write settings. the installStatus will be incomplete at this stage.
3627 //note that the new package setting would have already been
3628 //added to mPackages. It hasn't been persisted yet.
3629 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
3630 mSettings.writeLP();
3631 }
3632
3633 int retCode = 0;
3634 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
3635 retCode = mInstaller.movedex(tmpPackageFile.toString(),
3636 destPackageFile.toString());
3637 if (retCode != 0) {
3638 Log.e(TAG, "Couldn't rename dex file: " + destPackageFile);
3639 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3640 return;
3641 }
3642 }
3643 // XXX There are probably some big issues here: upon doing
3644 // the rename, we have reached the point of no return (the
3645 // original .apk is gone!), so we can't fail. Yet... we can.
3646 if (!tmpPackageFile.renameTo(destPackageFile)) {
3647 Log.e(TAG, "Couldn't move package file to: " + destPackageFile);
3648 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3649 } else {
3650 res.returnCode = setPermissionsLI(pkgName, newPackage, destFilePath,
3651 destResourceFile,
3652 forwardLocked);
3653 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3654 return;
3655 } else {
3656 Log.d(TAG, "New package installed in " + destPackageFile);
3657 }
3658 }
3659 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3660 if (mInstaller != null) {
3661 mInstaller.rmdex(tmpPackageFile.getPath());
3662 }
3663 }
3664
3665 synchronized (mPackages) {
3666 grantPermissionsLP(newPackage, true);
3667 res.name = pkgName;
3668 res.uid = newPackage.applicationInfo.uid;
3669 res.pkg = newPackage;
3670 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazskic64322c2009-04-28 15:26:38 +02003671 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3673 //to update install status
3674 mSettings.writeLP();
3675 }
3676 }
3677
The Android Open Source Project10592532009-03-18 17:39:46 -07003678 private PackageInstalledInfo installPackageLI(Uri pPackageURI,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003679 int pFlags, boolean newInstall, String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 File tmpPackageFile = null;
3681 String pkgName = null;
3682 boolean forwardLocked = false;
3683 boolean replacingExistingPackage = false;
3684 // Result object to be returned
3685 PackageInstalledInfo res = new PackageInstalledInfo();
3686 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3687 res.uid = -1;
3688 res.pkg = null;
3689 res.removedInfo = new PackageRemovedInfo();
3690
3691 main_flow: try {
3692 tmpPackageFile = createTempPackageFile();
3693 if (tmpPackageFile == null) {
3694 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3695 break main_flow;
3696 }
3697 tmpPackageFile.deleteOnExit(); // paranoia
3698 if (pPackageURI.getScheme().equals("file")) {
3699 final File srcPackageFile = new File(pPackageURI.getPath());
3700 // We copy the source package file to a temp file and then rename it to the
3701 // destination file in order to eliminate a window where the package directory
3702 // scanner notices the new package file but it's not completely copied yet.
3703 if (!FileUtils.copyFile(srcPackageFile, tmpPackageFile)) {
3704 Log.e(TAG, "Couldn't copy package file to temp file.");
3705 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3706 break main_flow;
3707 }
3708 } else if (pPackageURI.getScheme().equals("content")) {
3709 ParcelFileDescriptor fd;
3710 try {
3711 fd = mContext.getContentResolver().openFileDescriptor(pPackageURI, "r");
3712 } catch (FileNotFoundException e) {
3713 Log.e(TAG, "Couldn't open file descriptor from download service.");
3714 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3715 break main_flow;
3716 }
3717 if (fd == null) {
3718 Log.e(TAG, "Couldn't open file descriptor from download service (null).");
3719 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3720 break main_flow;
3721 }
3722 if (Config.LOGV) {
3723 Log.v(TAG, "Opened file descriptor from download service.");
3724 }
3725 ParcelFileDescriptor.AutoCloseInputStream
3726 dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
3727 // We copy the source package file to a temp file and then rename it to the
3728 // destination file in order to eliminate a window where the package directory
3729 // scanner notices the new package file but it's not completely copied yet.
3730 if (!FileUtils.copyToFile(dlStream, tmpPackageFile)) {
3731 Log.e(TAG, "Couldn't copy package stream to temp file.");
3732 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3733 break main_flow;
3734 }
3735 } else {
3736 Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
3737 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_URI;
3738 break main_flow;
3739 }
3740 pkgName = PackageParser.parsePackageName(
3741 tmpPackageFile.getAbsolutePath(), 0);
3742 if (pkgName == null) {
3743 Log.e(TAG, "Couldn't find a package name in : " + tmpPackageFile);
3744 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3745 break main_flow;
3746 }
3747 res.name = pkgName;
3748 //initialize some variables before installing pkg
3749 final String pkgFileName = pkgName + ".apk";
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003750 final File destDir = ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 ? mDrmAppPrivateInstallDir
3752 : mAppInstallDir;
3753 final File destPackageFile = new File(destDir, pkgFileName);
3754 final String destFilePath = destPackageFile.getAbsolutePath();
3755 File destResourceFile;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003756 if ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 final String publicZipFileName = pkgName + ".zip";
3758 destResourceFile = new File(mAppInstallDir, publicZipFileName);
3759 forwardLocked = true;
3760 } else {
3761 destResourceFile = destPackageFile;
3762 }
3763 // Retrieve PackageSettings and parse package
3764 int parseFlags = PackageParser.PARSE_CHATTY;
3765 parseFlags |= mDefParseFlags;
3766 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
3767 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackborn851a5412009-05-08 12:06:44 -07003768 pp.setSdkVersion(mSdkVersion, mSdkCodename);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
3770 destPackageFile.getAbsolutePath(), mMetrics, parseFlags);
3771 if (pkg == null) {
3772 res.returnCode = pp.getParseError();
3773 break main_flow;
3774 }
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003775 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
3776 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
3777 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
3778 break main_flow;
3779 }
3780 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
3782 res.returnCode = pp.getParseError();
3783 break main_flow;
3784 }
3785
3786 synchronized (mPackages) {
3787 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003788 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 && mPackages.containsKey(pkgName)) {
3790 replacingExistingPackage = true;
3791 }
3792 }
3793
3794 if(replacingExistingPackage) {
3795 replacePackageLI(pkgName,
3796 tmpPackageFile,
3797 destFilePath, destPackageFile, destResourceFile,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003798 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 res);
3800 } else {
3801 installNewPackageLI(pkgName,
3802 tmpPackageFile,
3803 destFilePath, destPackageFile, destResourceFile,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003804 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 res);
3806 }
3807 } finally {
3808 if (tmpPackageFile != null && tmpPackageFile.exists()) {
3809 tmpPackageFile.delete();
3810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003812 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 }
3814
3815 private int setPermissionsLI(String pkgName,
3816 PackageParser.Package newPackage,
3817 String destFilePath,
3818 File destResourceFile,
3819 boolean forwardLocked) {
3820 int retCode;
3821 if (forwardLocked) {
3822 try {
3823 extractPublicFiles(newPackage, destResourceFile);
3824 } catch (IOException e) {
3825 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
3826 " forward-locked app.");
3827 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3828 } finally {
3829 //TODO clean up the extracted public files
3830 }
3831 if (mInstaller != null) {
3832 retCode = mInstaller.setForwardLockPerm(pkgName,
3833 newPackage.applicationInfo.uid);
3834 } else {
3835 final int filePermissions =
3836 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
3837 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1,
3838 newPackage.applicationInfo.uid);
3839 }
3840 } else {
3841 final int filePermissions =
3842 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
3843 |FileUtils.S_IROTH;
3844 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1, -1);
3845 }
3846 if (retCode != 0) {
3847 Log.e(TAG, "Couldn't set new package file permissions for " + destFilePath
3848 + ". The return code was: " + retCode);
3849 }
3850 return PackageManager.INSTALL_SUCCEEDED;
3851 }
3852
3853 private boolean isForwardLocked(PackageParser.Package deletedPackage) {
3854 final ApplicationInfo applicationInfo = deletedPackage.applicationInfo;
3855 return applicationInfo.sourceDir.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath());
3856 }
3857
3858 private void extractPublicFiles(PackageParser.Package newPackage,
3859 File publicZipFile) throws IOException {
3860 final ZipOutputStream publicZipOutStream =
3861 new ZipOutputStream(new FileOutputStream(publicZipFile));
3862 final ZipFile privateZip = new ZipFile(newPackage.mPath);
3863
3864 // Copy manifest, resources.arsc and res directory to public zip
3865
3866 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
3867 while (privateZipEntries.hasMoreElements()) {
3868 final ZipEntry zipEntry = privateZipEntries.nextElement();
3869 final String zipEntryName = zipEntry.getName();
3870 if ("AndroidManifest.xml".equals(zipEntryName)
3871 || "resources.arsc".equals(zipEntryName)
3872 || zipEntryName.startsWith("res/")) {
3873 try {
3874 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
3875 } catch (IOException e) {
3876 try {
3877 publicZipOutStream.close();
3878 throw e;
3879 } finally {
3880 publicZipFile.delete();
3881 }
3882 }
3883 }
3884 }
3885
3886 publicZipOutStream.close();
3887 FileUtils.setPermissions(
3888 publicZipFile.getAbsolutePath(),
3889 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
3890 -1, -1);
3891 }
3892
3893 private static void copyZipEntry(ZipEntry zipEntry,
3894 ZipFile inZipFile,
3895 ZipOutputStream outZipStream) throws IOException {
3896 byte[] buffer = new byte[4096];
3897 int num;
3898
3899 ZipEntry newEntry;
3900 if (zipEntry.getMethod() == ZipEntry.STORED) {
3901 // Preserve the STORED method of the input entry.
3902 newEntry = new ZipEntry(zipEntry);
3903 } else {
3904 // Create a new entry so that the compressed len is recomputed.
3905 newEntry = new ZipEntry(zipEntry.getName());
3906 }
3907 outZipStream.putNextEntry(newEntry);
3908
3909 InputStream data = inZipFile.getInputStream(zipEntry);
3910 while ((num = data.read(buffer)) > 0) {
3911 outZipStream.write(buffer, 0, num);
3912 }
3913 outZipStream.flush();
3914 }
3915
3916 private void deleteTempPackageFiles() {
3917 FilenameFilter filter = new FilenameFilter() {
3918 public boolean accept(File dir, String name) {
3919 return name.startsWith("vmdl") && name.endsWith(".tmp");
3920 }
3921 };
3922 String tmpFilesList[] = mAppInstallDir.list(filter);
3923 if(tmpFilesList == null) {
3924 return;
3925 }
3926 for(int i = 0; i < tmpFilesList.length; i++) {
3927 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
3928 tmpFile.delete();
3929 }
3930 }
3931
3932 private File createTempPackageFile() {
3933 File tmpPackageFile;
3934 try {
3935 tmpPackageFile = File.createTempFile("vmdl", ".tmp", mAppInstallDir);
3936 } catch (IOException e) {
3937 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
3938 return null;
3939 }
3940 try {
3941 FileUtils.setPermissions(
3942 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
3943 -1, -1);
3944 } catch (IOException e) {
3945 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
3946 return null;
3947 }
3948 return tmpPackageFile;
3949 }
3950
3951 public void deletePackage(final String packageName,
3952 final IPackageDeleteObserver observer,
3953 final int flags) {
3954 mContext.enforceCallingOrSelfPermission(
3955 android.Manifest.permission.DELETE_PACKAGES, null);
3956 // Queue up an async operation since the package deletion may take a little while.
3957 mHandler.post(new Runnable() {
3958 public void run() {
3959 mHandler.removeCallbacks(this);
3960 final boolean succeded = deletePackageX(packageName, true, true, flags);
3961 if (observer != null) {
3962 try {
3963 observer.packageDeleted(succeded);
3964 } catch (RemoteException e) {
3965 Log.i(TAG, "Observer no longer exists.");
3966 } //end catch
3967 } //end if
3968 } //end run
3969 });
3970 }
3971
3972 /**
3973 * This method is an internal method that could be get invoked either
3974 * to delete an installed package or to clean up a failed installation.
3975 * After deleting an installed package, a broadcast is sent to notify any
3976 * listeners that the package has been installed. For cleaning up a failed
3977 * installation, the broadcast is not necessary since the package's
3978 * installation wouldn't have sent the initial broadcast either
3979 * The key steps in deleting a package are
3980 * deleting the package information in internal structures like mPackages,
3981 * deleting the packages base directories through installd
3982 * updating mSettings to reflect current status
3983 * persisting settings for later use
3984 * sending a broadcast if necessary
3985 */
3986
3987 private boolean deletePackageX(String packageName, boolean sendBroadCast,
3988 boolean deleteCodeAndResources, int flags) {
3989 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07003990 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991
3992 synchronized (mInstallLock) {
3993 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
3994 }
3995
3996 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07003997 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
3998 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
3999
4000 // If the removed package was a system update, the old system packaged
4001 // was re-enabled; we need to broadcast this information
4002 if (systemUpdate) {
4003 Bundle extras = new Bundle(1);
4004 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4005 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4006
4007 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4008 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 }
4011 return res;
4012 }
4013
4014 static class PackageRemovedInfo {
4015 String removedPackage;
4016 int uid = -1;
4017 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004018 boolean isRemovedPackageSystemUpdate = false;
4019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 void sendBroadcast(boolean fullRemove, boolean replacing) {
4021 Bundle extras = new Bundle(1);
4022 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4023 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4024 if (replacing) {
4025 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4026 }
4027 if (removedPackage != null) {
4028 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4029 }
4030 if (removedUid >= 0) {
4031 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
4032 }
4033 }
4034 }
4035
4036 /*
4037 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
4038 * flag is not set, the data directory is removed as well.
4039 * make sure this flag is set for partially installed apps. If not its meaningless to
4040 * delete a partially installed application.
4041 */
4042 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
4043 int flags) {
4044 String packageName = p.packageName;
4045 outInfo.removedPackage = packageName;
4046 removePackageLI(p, true);
4047 // Retrieve object to delete permissions for shared user later on
4048 PackageSetting deletedPs;
4049 synchronized (mPackages) {
4050 deletedPs = mSettings.mPackages.get(packageName);
4051 }
4052 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
4053 if (mInstaller != null) {
4054 int retCode = mInstaller.remove(packageName);
4055 if (retCode < 0) {
4056 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
4057 + packageName + ", retcode=" + retCode);
4058 // we don't consider this to be a failure of the core package deletion
4059 }
4060 } else {
4061 //for emulator
4062 PackageParser.Package pkg = mPackages.get(packageName);
4063 File dataDir = new File(pkg.applicationInfo.dataDir);
4064 dataDir.delete();
4065 }
4066 synchronized (mPackages) {
4067 outInfo.removedUid = mSettings.removePackageLP(packageName);
4068 }
4069 }
4070 synchronized (mPackages) {
4071 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
4072 // remove permissions associated with package
4073 mSettings.updateSharedUserPerms (deletedPs);
4074 }
4075 // Save settings now
4076 mSettings.writeLP ();
4077 }
4078 }
4079
4080 /*
4081 * Tries to delete system package.
4082 */
4083 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004084 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 ApplicationInfo applicationInfo = p.applicationInfo;
4086 //applicable for non-partially installed applications only
4087 if (applicationInfo == null) {
4088 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4089 return false;
4090 }
4091 PackageSetting ps = null;
4092 // Confirm if the system package has been updated
4093 // An updated system app can be deleted. This will also have to restore
4094 // the system pkg from system partition
4095 synchronized (mPackages) {
4096 ps = mSettings.getDisabledSystemPkg(p.packageName);
4097 }
4098 if (ps == null) {
4099 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
4100 return false;
4101 } else {
4102 Log.i(TAG, "Deleting system pkg from data partition");
4103 }
4104 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07004105 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004106 boolean deleteCodeAndResources = false;
4107 if (ps.versionCode < p.mVersionCode) {
4108 // Delete code and resources for downgrades
4109 deleteCodeAndResources = true;
4110 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4111 flags &= ~PackageManager.DONT_DELETE_DATA;
4112 }
4113 } else {
4114 // Preserve data by setting flag
4115 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4116 flags |= PackageManager.DONT_DELETE_DATA;
4117 }
4118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
4120 if (!ret) {
4121 return false;
4122 }
4123 synchronized (mPackages) {
4124 // Reinstate the old system package
4125 mSettings.enableSystemPackageLP(p.packageName);
4126 }
4127 // Install the system package
4128 PackageParser.Package newPkg = scanPackageLI(ps.codePath, ps.codePath, ps.resourcePath,
4129 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
4130 SCAN_MONITOR);
4131
4132 if (newPkg == null) {
4133 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
4134 return false;
4135 }
4136 synchronized (mPackages) {
4137 mSettings.writeLP();
4138 }
4139 return true;
4140 }
4141
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004142 private void deletePackageResourcesLI(String packageName,
4143 String sourceDir, String publicSourceDir) {
4144 File sourceFile = new File(sourceDir);
4145 if (!sourceFile.exists()) {
4146 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4147 }
4148 // Delete application's code and resources
4149 sourceFile.delete();
4150 final File publicSourceFile = new File(publicSourceDir);
4151 if (publicSourceFile.exists()) {
4152 publicSourceFile.delete();
4153 }
4154 if (mInstaller != null) {
4155 int retCode = mInstaller.rmdex(sourceFile.toString());
4156 if (retCode < 0) {
4157 Log.w(TAG, "Couldn't remove dex file for package: "
4158 + packageName + " at location " + sourceFile.toString() + ", retcode=" + retCode);
4159 // we don't consider this to be a failure of the core package deletion
4160 }
4161 }
4162 }
4163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 private boolean deleteInstalledPackageLI(PackageParser.Package p,
4165 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4166 ApplicationInfo applicationInfo = p.applicationInfo;
4167 if (applicationInfo == null) {
4168 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4169 return false;
4170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 outInfo.uid = applicationInfo.uid;
4172
4173 // Delete package data from internal structures and also remove data if flag is set
4174 removePackageDataLI(p, outInfo, flags);
4175
4176 // Delete application code and resources
4177 if (deleteCodeAndResources) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004178 deletePackageResourcesLI(applicationInfo.packageName,
4179 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 }
4181 return true;
4182 }
4183
4184 /*
4185 * This method handles package deletion in general
4186 */
4187 private boolean deletePackageLI(String packageName,
4188 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4189 if (packageName == null) {
4190 Log.w(TAG, "Attempt to delete null packageName.");
4191 return false;
4192 }
4193 PackageParser.Package p;
4194 boolean dataOnly = false;
4195 synchronized (mPackages) {
4196 p = mPackages.get(packageName);
4197 if (p == null) {
4198 //this retrieves partially installed apps
4199 dataOnly = true;
4200 PackageSetting ps = mSettings.mPackages.get(packageName);
4201 if (ps == null) {
4202 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4203 return false;
4204 }
4205 p = ps.pkg;
4206 }
4207 }
4208 if (p == null) {
4209 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4210 return false;
4211 }
4212
4213 if (dataOnly) {
4214 // Delete application data first
4215 removePackageDataLI(p, outInfo, flags);
4216 return true;
4217 }
4218 // At this point the package should have ApplicationInfo associated with it
4219 if (p.applicationInfo == null) {
4220 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4221 return false;
4222 }
4223 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4224 Log.i(TAG, "Removing system package:"+p.packageName);
4225 // When an updated system application is deleted we delete the existing resources as well and
4226 // fall back to existing code in system partition
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004227 return deleteSystemPackageLI(p, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 }
4229 Log.i(TAG, "Removing non-system package:"+p.packageName);
4230 return deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
4231 }
4232
4233 public void clearApplicationUserData(final String packageName,
4234 final IPackageDataObserver observer) {
4235 mContext.enforceCallingOrSelfPermission(
4236 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4237 // Queue up an async operation since the package deletion may take a little while.
4238 mHandler.post(new Runnable() {
4239 public void run() {
4240 mHandler.removeCallbacks(this);
4241 final boolean succeeded;
4242 synchronized (mInstallLock) {
4243 succeeded = clearApplicationUserDataLI(packageName);
4244 }
4245 if (succeeded) {
4246 // invoke DeviceStorageMonitor's update method to clear any notifications
4247 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4248 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4249 if (dsm != null) {
4250 dsm.updateMemory();
4251 }
4252 }
4253 if(observer != null) {
4254 try {
4255 observer.onRemoveCompleted(packageName, succeeded);
4256 } catch (RemoteException e) {
4257 Log.i(TAG, "Observer no longer exists.");
4258 }
4259 } //end if observer
4260 } //end run
4261 });
4262 }
4263
4264 private boolean clearApplicationUserDataLI(String packageName) {
4265 if (packageName == null) {
4266 Log.w(TAG, "Attempt to delete null packageName.");
4267 return false;
4268 }
4269 PackageParser.Package p;
4270 boolean dataOnly = false;
4271 synchronized (mPackages) {
4272 p = mPackages.get(packageName);
4273 if(p == null) {
4274 dataOnly = true;
4275 PackageSetting ps = mSettings.mPackages.get(packageName);
4276 if((ps == null) || (ps.pkg == null)) {
4277 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4278 return false;
4279 }
4280 p = ps.pkg;
4281 }
4282 }
4283 if(!dataOnly) {
4284 //need to check this only for fully installed applications
4285 if (p == null) {
4286 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4287 return false;
4288 }
4289 final ApplicationInfo applicationInfo = p.applicationInfo;
4290 if (applicationInfo == null) {
4291 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4292 return false;
4293 }
4294 }
4295 if (mInstaller != null) {
4296 int retCode = mInstaller.clearUserData(packageName);
4297 if (retCode < 0) {
4298 Log.w(TAG, "Couldn't remove cache files for package: "
4299 + packageName);
4300 return false;
4301 }
4302 }
4303 return true;
4304 }
4305
4306 public void deleteApplicationCacheFiles(final String packageName,
4307 final IPackageDataObserver observer) {
4308 mContext.enforceCallingOrSelfPermission(
4309 android.Manifest.permission.DELETE_CACHE_FILES, null);
4310 // Queue up an async operation since the package deletion may take a little while.
4311 mHandler.post(new Runnable() {
4312 public void run() {
4313 mHandler.removeCallbacks(this);
4314 final boolean succeded;
4315 synchronized (mInstallLock) {
4316 succeded = deleteApplicationCacheFilesLI(packageName);
4317 }
4318 if(observer != null) {
4319 try {
4320 observer.onRemoveCompleted(packageName, succeded);
4321 } catch (RemoteException e) {
4322 Log.i(TAG, "Observer no longer exists.");
4323 }
4324 } //end if observer
4325 } //end run
4326 });
4327 }
4328
4329 private boolean deleteApplicationCacheFilesLI(String packageName) {
4330 if (packageName == null) {
4331 Log.w(TAG, "Attempt to delete null packageName.");
4332 return false;
4333 }
4334 PackageParser.Package p;
4335 synchronized (mPackages) {
4336 p = mPackages.get(packageName);
4337 }
4338 if (p == null) {
4339 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4340 return false;
4341 }
4342 final ApplicationInfo applicationInfo = p.applicationInfo;
4343 if (applicationInfo == null) {
4344 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4345 return false;
4346 }
4347 if (mInstaller != null) {
4348 int retCode = mInstaller.deleteCacheFiles(packageName);
4349 if (retCode < 0) {
4350 Log.w(TAG, "Couldn't remove cache files for package: "
4351 + packageName);
4352 return false;
4353 }
4354 }
4355 return true;
4356 }
4357
4358 public void getPackageSizeInfo(final String packageName,
4359 final IPackageStatsObserver observer) {
4360 mContext.enforceCallingOrSelfPermission(
4361 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4362 // Queue up an async operation since the package deletion may take a little while.
4363 mHandler.post(new Runnable() {
4364 public void run() {
4365 mHandler.removeCallbacks(this);
4366 PackageStats lStats = new PackageStats(packageName);
4367 final boolean succeded;
4368 synchronized (mInstallLock) {
4369 succeded = getPackageSizeInfoLI(packageName, lStats);
4370 }
4371 if(observer != null) {
4372 try {
4373 observer.onGetStatsCompleted(lStats, succeded);
4374 } catch (RemoteException e) {
4375 Log.i(TAG, "Observer no longer exists.");
4376 }
4377 } //end if observer
4378 } //end run
4379 });
4380 }
4381
4382 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4383 if (packageName == null) {
4384 Log.w(TAG, "Attempt to get size of null packageName.");
4385 return false;
4386 }
4387 PackageParser.Package p;
4388 boolean dataOnly = false;
4389 synchronized (mPackages) {
4390 p = mPackages.get(packageName);
4391 if(p == null) {
4392 dataOnly = true;
4393 PackageSetting ps = mSettings.mPackages.get(packageName);
4394 if((ps == null) || (ps.pkg == null)) {
4395 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4396 return false;
4397 }
4398 p = ps.pkg;
4399 }
4400 }
4401 String publicSrcDir = null;
4402 if(!dataOnly) {
4403 final ApplicationInfo applicationInfo = p.applicationInfo;
4404 if (applicationInfo == null) {
4405 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4406 return false;
4407 }
4408 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4409 }
4410 if (mInstaller != null) {
4411 int res = mInstaller.getSizeInfo(packageName, p.mPath,
4412 publicSrcDir, pStats);
4413 if (res < 0) {
4414 return false;
4415 } else {
4416 return true;
4417 }
4418 }
4419 return true;
4420 }
4421
4422
4423 public void addPackageToPreferred(String packageName) {
4424 mContext.enforceCallingOrSelfPermission(
4425 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4426
4427 synchronized (mPackages) {
4428 PackageParser.Package p = mPackages.get(packageName);
4429 if (p == null) {
4430 return;
4431 }
4432 PackageSetting ps = (PackageSetting)p.mExtras;
4433 if (ps != null) {
4434 mSettings.mPreferredPackages.remove(ps);
4435 mSettings.mPreferredPackages.add(0, ps);
4436 updatePreferredIndicesLP();
4437 mSettings.writeLP();
4438 }
4439 }
4440 }
4441
4442 public void removePackageFromPreferred(String packageName) {
4443 mContext.enforceCallingOrSelfPermission(
4444 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4445
4446 synchronized (mPackages) {
4447 PackageParser.Package p = mPackages.get(packageName);
4448 if (p == null) {
4449 return;
4450 }
4451 if (p.mPreferredOrder > 0) {
4452 PackageSetting ps = (PackageSetting)p.mExtras;
4453 if (ps != null) {
4454 mSettings.mPreferredPackages.remove(ps);
4455 p.mPreferredOrder = 0;
4456 updatePreferredIndicesLP();
4457 mSettings.writeLP();
4458 }
4459 }
4460 }
4461 }
4462
4463 private void updatePreferredIndicesLP() {
4464 final ArrayList<PackageSetting> pkgs
4465 = mSettings.mPreferredPackages;
4466 final int N = pkgs.size();
4467 for (int i=0; i<N; i++) {
4468 pkgs.get(i).pkg.mPreferredOrder = N - i;
4469 }
4470 }
4471
4472 public List<PackageInfo> getPreferredPackages(int flags) {
4473 synchronized (mPackages) {
4474 final ArrayList<PackageInfo> res = new ArrayList<PackageInfo>();
4475 final ArrayList<PackageSetting> pref = mSettings.mPreferredPackages;
4476 final int N = pref.size();
4477 for (int i=0; i<N; i++) {
4478 res.add(generatePackageInfo(pref.get(i).pkg, flags));
4479 }
4480 return res;
4481 }
4482 }
4483
4484 public void addPreferredActivity(IntentFilter filter, int match,
4485 ComponentName[] set, ComponentName activity) {
4486 mContext.enforceCallingOrSelfPermission(
4487 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4488
4489 synchronized (mPackages) {
4490 Log.i(TAG, "Adding preferred activity " + activity + ":");
4491 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4492 mSettings.mPreferredActivities.addFilter(
4493 new PreferredActivity(filter, match, set, activity));
4494 mSettings.writeLP();
4495 }
4496 }
4497
4498 public void clearPackagePreferredActivities(String packageName) {
4499 mContext.enforceCallingOrSelfPermission(
4500 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4501
4502 synchronized (mPackages) {
4503 if (clearPackagePreferredActivitiesLP(packageName)) {
4504 mSettings.writeLP();
4505 }
4506 }
4507 }
4508
4509 boolean clearPackagePreferredActivitiesLP(String packageName) {
4510 boolean changed = false;
4511 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4512 while (it.hasNext()) {
4513 PreferredActivity pa = it.next();
4514 if (pa.mActivity.getPackageName().equals(packageName)) {
4515 it.remove();
4516 changed = true;
4517 }
4518 }
4519 return changed;
4520 }
4521
4522 public int getPreferredActivities(List<IntentFilter> outFilters,
4523 List<ComponentName> outActivities, String packageName) {
4524
4525 int num = 0;
4526 synchronized (mPackages) {
4527 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4528 while (it.hasNext()) {
4529 PreferredActivity pa = it.next();
4530 if (packageName == null
4531 || pa.mActivity.getPackageName().equals(packageName)) {
4532 if (outFilters != null) {
4533 outFilters.add(new IntentFilter(pa));
4534 }
4535 if (outActivities != null) {
4536 outActivities.add(pa.mActivity);
4537 }
4538 }
4539 }
4540 }
4541
4542 return num;
4543 }
4544
4545 public void setApplicationEnabledSetting(String appPackageName,
4546 int newState, int flags) {
4547 setEnabledSetting(appPackageName, null, newState, flags);
4548 }
4549
4550 public void setComponentEnabledSetting(ComponentName componentName,
4551 int newState, int flags) {
4552 setEnabledSetting(componentName.getPackageName(),
4553 componentName.getClassName(), newState, flags);
4554 }
4555
4556 private void setEnabledSetting(
4557 final String packageNameStr, String classNameStr, int newState, final int flags) {
4558 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
4559 || newState == COMPONENT_ENABLED_STATE_ENABLED
4560 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
4561 throw new IllegalArgumentException("Invalid new component state: "
4562 + newState);
4563 }
4564 PackageSetting pkgSetting;
4565 final int uid = Binder.getCallingUid();
4566 final int permission = mContext.checkCallingPermission(
4567 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
4568 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4569 int packageUid = -1;
4570 synchronized (mPackages) {
4571 pkgSetting = mSettings.mPackages.get(packageNameStr);
4572 if (pkgSetting == null) {
4573 if (classNameStr == null) {
4574 throw new IllegalArgumentException(
4575 "Unknown package: " + packageNameStr);
4576 }
4577 throw new IllegalArgumentException(
4578 "Unknown component: " + packageNameStr
4579 + "/" + classNameStr);
4580 }
4581 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4582 throw new SecurityException(
4583 "Permission Denial: attempt to change component state from pid="
4584 + Binder.getCallingPid()
4585 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
4586 }
4587 packageUid = pkgSetting.userId;
4588 if (classNameStr == null) {
4589 // We're dealing with an application/package level state change
4590 pkgSetting.enabled = newState;
4591 } else {
4592 // We're dealing with a component level state change
4593 switch (newState) {
4594 case COMPONENT_ENABLED_STATE_ENABLED:
4595 pkgSetting.enableComponentLP(classNameStr);
4596 break;
4597 case COMPONENT_ENABLED_STATE_DISABLED:
4598 pkgSetting.disableComponentLP(classNameStr);
4599 break;
4600 case COMPONENT_ENABLED_STATE_DEFAULT:
4601 pkgSetting.restoreComponentLP(classNameStr);
4602 break;
4603 default:
4604 Log.e(TAG, "Invalid new component state: " + newState);
4605 }
4606 }
4607 mSettings.writeLP();
4608 }
4609
4610 long callingId = Binder.clearCallingIdentity();
4611 try {
4612 Bundle extras = new Bundle(2);
4613 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP,
4614 (flags&PackageManager.DONT_KILL_APP) != 0);
4615 extras.putInt(Intent.EXTRA_UID, packageUid);
4616 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageNameStr, extras);
4617 } finally {
4618 Binder.restoreCallingIdentity(callingId);
4619 }
4620 }
4621
Jacek Surazskic64322c2009-04-28 15:26:38 +02004622 public String getInstallerPackageName(String packageName) {
4623 synchronized (mPackages) {
4624 PackageSetting pkg = mSettings.mPackages.get(packageName);
4625 if (pkg == null) {
4626 throw new IllegalArgumentException("Unknown package: " + packageName);
4627 }
4628 return pkg.installerPackageName;
4629 }
4630 }
4631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 public int getApplicationEnabledSetting(String appPackageName) {
4633 synchronized (mPackages) {
4634 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
4635 if (pkg == null) {
4636 throw new IllegalArgumentException("Unknown package: " + appPackageName);
4637 }
4638 return pkg.enabled;
4639 }
4640 }
4641
4642 public int getComponentEnabledSetting(ComponentName componentName) {
4643 synchronized (mPackages) {
4644 final String packageNameStr = componentName.getPackageName();
4645 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
4646 if (pkg == null) {
4647 throw new IllegalArgumentException("Unknown component: " + componentName);
4648 }
4649 final String classNameStr = componentName.getClassName();
4650 return pkg.currentEnabledStateLP(classNameStr);
4651 }
4652 }
4653
4654 public void enterSafeMode() {
4655 if (!mSystemReady) {
4656 mSafeMode = true;
4657 }
4658 }
4659
4660 public void systemReady() {
4661 mSystemReady = true;
4662 }
4663
4664 public boolean isSafeMode() {
4665 return mSafeMode;
4666 }
4667
4668 public boolean hasSystemUidErrors() {
4669 return mHasSystemUidErrors;
4670 }
4671
4672 static String arrayToString(int[] array) {
4673 StringBuffer buf = new StringBuffer(128);
4674 buf.append('[');
4675 if (array != null) {
4676 for (int i=0; i<array.length; i++) {
4677 if (i > 0) buf.append(", ");
4678 buf.append(array[i]);
4679 }
4680 }
4681 buf.append(']');
4682 return buf.toString();
4683 }
4684
4685 @Override
4686 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4687 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4688 != PackageManager.PERMISSION_GRANTED) {
4689 pw.println("Permission Denial: can't dump ActivityManager from from pid="
4690 + Binder.getCallingPid()
4691 + ", uid=" + Binder.getCallingUid()
4692 + " without permission "
4693 + android.Manifest.permission.DUMP);
4694 return;
4695 }
4696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004697 synchronized (mPackages) {
4698 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004699 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 pw.println(" ");
4701 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004702 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703 pw.println(" ");
4704 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004705 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004706 pw.println(" ");
4707 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004708 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004709 pw.println(" ");
4710 pw.println("Preferred Packages:");
4711 {
4712 for (PackageSetting ps : mSettings.mPreferredPackages) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004713 pw.print(" "); pw.println(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004714 }
4715 }
4716 pw.println(" ");
4717 pw.println("Permissions:");
4718 {
4719 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004720 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
4721 pw.print(Integer.toHexString(System.identityHashCode(p)));
4722 pw.println("):");
4723 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
4724 pw.print(" uid="); pw.print(p.uid);
4725 pw.print(" gids="); pw.print(arrayToString(p.gids));
4726 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 }
4728 }
4729 pw.println(" ");
4730 pw.println("Packages:");
4731 {
4732 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004733 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
4734 pw.print(Integer.toHexString(System.identityHashCode(ps)));
4735 pw.println("):");
4736 pw.print(" userId="); pw.print(ps.userId);
4737 pw.print(" gids="); pw.println(arrayToString(ps.gids));
4738 pw.print(" sharedUser="); pw.println(ps.sharedUser);
4739 pw.print(" pkg="); pw.println(ps.pkg);
4740 pw.print(" codePath="); pw.println(ps.codePathString);
4741 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004743 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004744 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004745 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
4746 pw.print(" signatures="); pw.println(ps.signatures);
4747 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
4748 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
4749 pw.print(" installStatus="); pw.print(ps.installStatus);
4750 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004751 if (ps.disabledComponents.size() > 0) {
4752 pw.println(" disabledComponents:");
4753 for (String s : ps.disabledComponents) {
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 }
4757 if (ps.enabledComponents.size() > 0) {
4758 pw.println(" enabledComponents:");
4759 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004760 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004761 }
4762 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004763 if (ps.grantedPermissions.size() > 0) {
4764 pw.println(" grantedPermissions:");
4765 for (String s : ps.grantedPermissions) {
4766 pw.print(" "); pw.println(s);
4767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004768 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004769 if (ps.loadedPermissions.size() > 0) {
4770 pw.println(" loadedPermissions:");
4771 for (String s : ps.loadedPermissions) {
4772 pw.print(" "); pw.println(s);
4773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004774 }
4775 }
4776 }
4777 pw.println(" ");
4778 pw.println("Shared Users:");
4779 {
4780 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004781 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
4782 pw.print(Integer.toHexString(System.identityHashCode(su)));
4783 pw.println("):");
4784 pw.print(" userId="); pw.print(su.userId);
4785 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004786 pw.println(" grantedPermissions:");
4787 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004788 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 }
4790 pw.println(" loadedPermissions:");
4791 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004792 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004793 }
4794 }
4795 }
4796 pw.println(" ");
4797 pw.println("Settings parse messages:");
4798 pw.println(mSettings.mReadMessages.toString());
4799 }
4800 }
4801
4802 static final class BasePermission {
4803 final static int TYPE_NORMAL = 0;
4804 final static int TYPE_BUILTIN = 1;
4805 final static int TYPE_DYNAMIC = 2;
4806
4807 final String name;
4808 final String sourcePackage;
4809 final int type;
4810 PackageParser.Permission perm;
4811 PermissionInfo pendingInfo;
4812 int uid;
4813 int[] gids;
4814
4815 BasePermission(String _name, String _sourcePackage, int _type) {
4816 name = _name;
4817 sourcePackage = _sourcePackage;
4818 type = _type;
4819 }
4820 }
4821
4822 static class PackageSignatures {
4823 private Signature[] mSignatures;
4824
4825 PackageSignatures(Signature[] sigs) {
4826 assignSignatures(sigs);
4827 }
4828
4829 PackageSignatures() {
4830 }
4831
4832 void writeXml(XmlSerializer serializer, String tagName,
4833 ArrayList<Signature> pastSignatures) throws IOException {
4834 if (mSignatures == null) {
4835 return;
4836 }
4837 serializer.startTag(null, tagName);
4838 serializer.attribute(null, "count",
4839 Integer.toString(mSignatures.length));
4840 for (int i=0; i<mSignatures.length; i++) {
4841 serializer.startTag(null, "cert");
4842 final Signature sig = mSignatures[i];
4843 final int sigHash = sig.hashCode();
4844 final int numPast = pastSignatures.size();
4845 int j;
4846 for (j=0; j<numPast; j++) {
4847 Signature pastSig = pastSignatures.get(j);
4848 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
4849 serializer.attribute(null, "index", Integer.toString(j));
4850 break;
4851 }
4852 }
4853 if (j >= numPast) {
4854 pastSignatures.add(sig);
4855 serializer.attribute(null, "index", Integer.toString(numPast));
4856 serializer.attribute(null, "key", sig.toCharsString());
4857 }
4858 serializer.endTag(null, "cert");
4859 }
4860 serializer.endTag(null, tagName);
4861 }
4862
4863 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
4864 throws IOException, XmlPullParserException {
4865 String countStr = parser.getAttributeValue(null, "count");
4866 if (countStr == null) {
4867 reportSettingsProblem(Log.WARN,
4868 "Error in package manager settings: <signatures> has"
4869 + " no count at " + parser.getPositionDescription());
4870 XmlUtils.skipCurrentTag(parser);
4871 }
4872 final int count = Integer.parseInt(countStr);
4873 mSignatures = new Signature[count];
4874 int pos = 0;
4875
4876 int outerDepth = parser.getDepth();
4877 int type;
4878 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
4879 && (type != XmlPullParser.END_TAG
4880 || parser.getDepth() > outerDepth)) {
4881 if (type == XmlPullParser.END_TAG
4882 || type == XmlPullParser.TEXT) {
4883 continue;
4884 }
4885
4886 String tagName = parser.getName();
4887 if (tagName.equals("cert")) {
4888 if (pos < count) {
4889 String index = parser.getAttributeValue(null, "index");
4890 if (index != null) {
4891 try {
4892 int idx = Integer.parseInt(index);
4893 String key = parser.getAttributeValue(null, "key");
4894 if (key == null) {
4895 if (idx >= 0 && idx < pastSignatures.size()) {
4896 Signature sig = pastSignatures.get(idx);
4897 if (sig != null) {
4898 mSignatures[pos] = pastSignatures.get(idx);
4899 pos++;
4900 } else {
4901 reportSettingsProblem(Log.WARN,
4902 "Error in package manager settings: <cert> "
4903 + "index " + index + " is not defined at "
4904 + parser.getPositionDescription());
4905 }
4906 } else {
4907 reportSettingsProblem(Log.WARN,
4908 "Error in package manager settings: <cert> "
4909 + "index " + index + " is out of bounds at "
4910 + parser.getPositionDescription());
4911 }
4912 } else {
4913 while (pastSignatures.size() <= idx) {
4914 pastSignatures.add(null);
4915 }
4916 Signature sig = new Signature(key);
4917 pastSignatures.set(idx, sig);
4918 mSignatures[pos] = sig;
4919 pos++;
4920 }
4921 } catch (NumberFormatException e) {
4922 reportSettingsProblem(Log.WARN,
4923 "Error in package manager settings: <cert> "
4924 + "index " + index + " is not a number at "
4925 + parser.getPositionDescription());
4926 }
4927 } else {
4928 reportSettingsProblem(Log.WARN,
4929 "Error in package manager settings: <cert> has"
4930 + " no index at " + parser.getPositionDescription());
4931 }
4932 } else {
4933 reportSettingsProblem(Log.WARN,
4934 "Error in package manager settings: too "
4935 + "many <cert> tags, expected " + count
4936 + " at " + parser.getPositionDescription());
4937 }
4938 } else {
4939 reportSettingsProblem(Log.WARN,
4940 "Unknown element under <cert>: "
4941 + parser.getName());
4942 }
4943 XmlUtils.skipCurrentTag(parser);
4944 }
4945
4946 if (pos < count) {
4947 // Should never happen -- there is an error in the written
4948 // settings -- but if it does we don't want to generate
4949 // a bad array.
4950 Signature[] newSigs = new Signature[pos];
4951 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
4952 mSignatures = newSigs;
4953 }
4954 }
4955
4956 /**
4957 * If any of the given 'sigs' is contained in the existing signatures,
4958 * then completely replace the current signatures with the ones in
4959 * 'sigs'. This is used for updating an existing package to a newly
4960 * installed version.
4961 */
4962 boolean updateSignatures(Signature[] sigs, boolean update) {
4963 if (mSignatures == null) {
4964 if (update) {
4965 assignSignatures(sigs);
4966 }
4967 return true;
4968 }
4969 if (sigs == null) {
4970 return false;
4971 }
4972
4973 for (int i=0; i<sigs.length; i++) {
4974 Signature sig = sigs[i];
4975 for (int j=0; j<mSignatures.length; j++) {
4976 if (mSignatures[j].equals(sig)) {
4977 if (update) {
4978 assignSignatures(sigs);
4979 }
4980 return true;
4981 }
4982 }
4983 }
4984 return false;
4985 }
4986
4987 /**
4988 * If any of the given 'sigs' is contained in the existing signatures,
4989 * then add in any new signatures found in 'sigs'. This is used for
4990 * including a new package into an existing shared user id.
4991 */
4992 boolean mergeSignatures(Signature[] sigs, boolean update) {
4993 if (mSignatures == null) {
4994 if (update) {
4995 assignSignatures(sigs);
4996 }
4997 return true;
4998 }
4999 if (sigs == null) {
5000 return false;
5001 }
5002
5003 Signature[] added = null;
5004 int addedCount = 0;
5005 boolean haveMatch = false;
5006 for (int i=0; i<sigs.length; i++) {
5007 Signature sig = sigs[i];
5008 boolean found = false;
5009 for (int j=0; j<mSignatures.length; j++) {
5010 if (mSignatures[j].equals(sig)) {
5011 found = true;
5012 haveMatch = true;
5013 break;
5014 }
5015 }
5016
5017 if (!found) {
5018 if (added == null) {
5019 added = new Signature[sigs.length];
5020 }
5021 added[i] = sig;
5022 addedCount++;
5023 }
5024 }
5025
5026 if (!haveMatch) {
5027 // Nothing matched -- reject the new signatures.
5028 return false;
5029 }
5030 if (added == null) {
5031 // Completely matched -- nothing else to do.
5032 return true;
5033 }
5034
5035 // Add additional signatures in.
5036 if (update) {
5037 Signature[] total = new Signature[addedCount+mSignatures.length];
5038 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5039 int j = mSignatures.length;
5040 for (int i=0; i<added.length; i++) {
5041 if (added[i] != null) {
5042 total[j] = added[i];
5043 j++;
5044 }
5045 }
5046 mSignatures = total;
5047 }
5048 return true;
5049 }
5050
5051 private void assignSignatures(Signature[] sigs) {
5052 if (sigs == null) {
5053 mSignatures = null;
5054 return;
5055 }
5056 mSignatures = new Signature[sigs.length];
5057 for (int i=0; i<sigs.length; i++) {
5058 mSignatures[i] = sigs[i];
5059 }
5060 }
5061
5062 @Override
5063 public String toString() {
5064 StringBuffer buf = new StringBuffer(128);
5065 buf.append("PackageSignatures{");
5066 buf.append(Integer.toHexString(System.identityHashCode(this)));
5067 buf.append(" [");
5068 if (mSignatures != null) {
5069 for (int i=0; i<mSignatures.length; i++) {
5070 if (i > 0) buf.append(", ");
5071 buf.append(Integer.toHexString(
5072 System.identityHashCode(mSignatures[i])));
5073 }
5074 }
5075 buf.append("]}");
5076 return buf.toString();
5077 }
5078 }
5079
5080 static class PreferredActivity extends IntentFilter {
5081 final int mMatch;
5082 final String[] mSetPackages;
5083 final String[] mSetClasses;
5084 final String[] mSetComponents;
5085 final ComponentName mActivity;
5086 final String mShortActivity;
5087 String mParseError;
5088
5089 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5090 ComponentName activity) {
5091 super(filter);
5092 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5093 mActivity = activity;
5094 mShortActivity = activity.flattenToShortString();
5095 mParseError = null;
5096 if (set != null) {
5097 final int N = set.length;
5098 String[] myPackages = new String[N];
5099 String[] myClasses = new String[N];
5100 String[] myComponents = new String[N];
5101 for (int i=0; i<N; i++) {
5102 ComponentName cn = set[i];
5103 if (cn == null) {
5104 mSetPackages = null;
5105 mSetClasses = null;
5106 mSetComponents = null;
5107 return;
5108 }
5109 myPackages[i] = cn.getPackageName().intern();
5110 myClasses[i] = cn.getClassName().intern();
5111 myComponents[i] = cn.flattenToShortString().intern();
5112 }
5113 mSetPackages = myPackages;
5114 mSetClasses = myClasses;
5115 mSetComponents = myComponents;
5116 } else {
5117 mSetPackages = null;
5118 mSetClasses = null;
5119 mSetComponents = null;
5120 }
5121 }
5122
5123 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5124 IOException {
5125 mShortActivity = parser.getAttributeValue(null, "name");
5126 mActivity = ComponentName.unflattenFromString(mShortActivity);
5127 if (mActivity == null) {
5128 mParseError = "Bad activity name " + mShortActivity;
5129 }
5130 String matchStr = parser.getAttributeValue(null, "match");
5131 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5132 String setCountStr = parser.getAttributeValue(null, "set");
5133 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5134
5135 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5136 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5137 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5138
5139 int setPos = 0;
5140
5141 int outerDepth = parser.getDepth();
5142 int type;
5143 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5144 && (type != XmlPullParser.END_TAG
5145 || parser.getDepth() > outerDepth)) {
5146 if (type == XmlPullParser.END_TAG
5147 || type == XmlPullParser.TEXT) {
5148 continue;
5149 }
5150
5151 String tagName = parser.getName();
5152 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5153 // + parser.getDepth() + " tag=" + tagName);
5154 if (tagName.equals("set")) {
5155 String name = parser.getAttributeValue(null, "name");
5156 if (name == null) {
5157 if (mParseError == null) {
5158 mParseError = "No name in set tag in preferred activity "
5159 + mShortActivity;
5160 }
5161 } else if (setPos >= setCount) {
5162 if (mParseError == null) {
5163 mParseError = "Too many set tags in preferred activity "
5164 + mShortActivity;
5165 }
5166 } else {
5167 ComponentName cn = ComponentName.unflattenFromString(name);
5168 if (cn == null) {
5169 if (mParseError == null) {
5170 mParseError = "Bad set name " + name + " in preferred activity "
5171 + mShortActivity;
5172 }
5173 } else {
5174 myPackages[setPos] = cn.getPackageName();
5175 myClasses[setPos] = cn.getClassName();
5176 myComponents[setPos] = name;
5177 setPos++;
5178 }
5179 }
5180 XmlUtils.skipCurrentTag(parser);
5181 } else if (tagName.equals("filter")) {
5182 //Log.i(TAG, "Starting to parse filter...");
5183 readFromXml(parser);
5184 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5185 // + parser.getDepth() + " tag=" + parser.getName());
5186 } else {
5187 reportSettingsProblem(Log.WARN,
5188 "Unknown element under <preferred-activities>: "
5189 + parser.getName());
5190 XmlUtils.skipCurrentTag(parser);
5191 }
5192 }
5193
5194 if (setPos != setCount) {
5195 if (mParseError == null) {
5196 mParseError = "Not enough set tags (expected " + setCount
5197 + " but found " + setPos + ") in " + mShortActivity;
5198 }
5199 }
5200
5201 mSetPackages = myPackages;
5202 mSetClasses = myClasses;
5203 mSetComponents = myComponents;
5204 }
5205
5206 public void writeToXml(XmlSerializer serializer) throws IOException {
5207 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5208 serializer.attribute(null, "name", mShortActivity);
5209 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5210 serializer.attribute(null, "set", Integer.toString(NS));
5211 for (int s=0; s<NS; s++) {
5212 serializer.startTag(null, "set");
5213 serializer.attribute(null, "name", mSetComponents[s]);
5214 serializer.endTag(null, "set");
5215 }
5216 serializer.startTag(null, "filter");
5217 super.writeToXml(serializer);
5218 serializer.endTag(null, "filter");
5219 }
5220
5221 boolean sameSet(List<ResolveInfo> query, int priority) {
5222 if (mSetPackages == null) return false;
5223 final int NQ = query.size();
5224 final int NS = mSetPackages.length;
5225 int numMatch = 0;
5226 for (int i=0; i<NQ; i++) {
5227 ResolveInfo ri = query.get(i);
5228 if (ri.priority != priority) continue;
5229 ActivityInfo ai = ri.activityInfo;
5230 boolean good = false;
5231 for (int j=0; j<NS; j++) {
5232 if (mSetPackages[j].equals(ai.packageName)
5233 && mSetClasses[j].equals(ai.name)) {
5234 numMatch++;
5235 good = true;
5236 break;
5237 }
5238 }
5239 if (!good) return false;
5240 }
5241 return numMatch == NS;
5242 }
5243 }
5244
5245 static class GrantedPermissions {
5246 final int pkgFlags;
5247
5248 HashSet<String> grantedPermissions = new HashSet<String>();
5249 int[] gids;
5250
5251 HashSet<String> loadedPermissions = new HashSet<String>();
5252
5253 GrantedPermissions(int pkgFlags) {
5254 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5255 }
5256 }
5257
5258 /**
5259 * Settings base class for pending and resolved classes.
5260 */
5261 static class PackageSettingBase extends GrantedPermissions {
5262 final String name;
5263 final File codePath;
5264 final String codePathString;
5265 final File resourcePath;
5266 final String resourcePathString;
5267 private long timeStamp;
5268 private String timeStampString = "0";
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005269 final int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005270
5271 PackageSignatures signatures = new PackageSignatures();
5272
5273 boolean permissionsFixed;
5274
5275 /* Explicitly disabled components */
5276 HashSet<String> disabledComponents = new HashSet<String>(0);
5277 /* Explicitly enabled components */
5278 HashSet<String> enabledComponents = new HashSet<String>(0);
5279 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5280 int installStatus = PKG_INSTALL_COMPLETE;
Jacek Surazskic64322c2009-04-28 15:26:38 +02005281
5282 /* package name of the app that installed this package */
5283 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005284
5285 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005286 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 super(pkgFlags);
5288 this.name = name;
5289 this.codePath = codePath;
5290 this.codePathString = codePath.toString();
5291 this.resourcePath = resourcePath;
5292 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005293 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 }
5295
Jacek Surazskic64322c2009-04-28 15:26:38 +02005296 public void setInstallerPackageName(String packageName) {
5297 installerPackageName = packageName;
5298 }
5299
5300 String getInstallerPackageName() {
5301 return installerPackageName;
5302 }
5303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005304 public void setInstallStatus(int newStatus) {
5305 installStatus = newStatus;
5306 }
5307
5308 public int getInstallStatus() {
5309 return installStatus;
5310 }
5311
5312 public void setTimeStamp(long newStamp) {
5313 if (newStamp != timeStamp) {
5314 timeStamp = newStamp;
5315 timeStampString = Long.toString(newStamp);
5316 }
5317 }
5318
5319 public void setTimeStamp(long newStamp, String newStampStr) {
5320 timeStamp = newStamp;
5321 timeStampString = newStampStr;
5322 }
5323
5324 public long getTimeStamp() {
5325 return timeStamp;
5326 }
5327
5328 public String getTimeStampStr() {
5329 return timeStampString;
5330 }
5331
5332 public void copyFrom(PackageSettingBase base) {
5333 grantedPermissions = base.grantedPermissions;
5334 gids = base.gids;
5335 loadedPermissions = base.loadedPermissions;
5336
5337 timeStamp = base.timeStamp;
5338 timeStampString = base.timeStampString;
5339 signatures = base.signatures;
5340 permissionsFixed = base.permissionsFixed;
5341 disabledComponents = base.disabledComponents;
5342 enabledComponents = base.enabledComponents;
5343 enabled = base.enabled;
5344 installStatus = base.installStatus;
5345 }
5346
5347 void enableComponentLP(String componentClassName) {
5348 disabledComponents.remove(componentClassName);
5349 enabledComponents.add(componentClassName);
5350 }
5351
5352 void disableComponentLP(String componentClassName) {
5353 enabledComponents.remove(componentClassName);
5354 disabledComponents.add(componentClassName);
5355 }
5356
5357 void restoreComponentLP(String componentClassName) {
5358 enabledComponents.remove(componentClassName);
5359 disabledComponents.remove(componentClassName);
5360 }
5361
5362 int currentEnabledStateLP(String componentName) {
5363 if (enabledComponents.contains(componentName)) {
5364 return COMPONENT_ENABLED_STATE_ENABLED;
5365 } else if (disabledComponents.contains(componentName)) {
5366 return COMPONENT_ENABLED_STATE_DISABLED;
5367 } else {
5368 return COMPONENT_ENABLED_STATE_DEFAULT;
5369 }
5370 }
5371 }
5372
5373 /**
5374 * Settings data for a particular package we know about.
5375 */
5376 static final class PackageSetting extends PackageSettingBase {
5377 int userId;
5378 PackageParser.Package pkg;
5379 SharedUserSetting sharedUser;
5380
5381 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005382 int pVersionCode, int pkgFlags) {
5383 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 }
5385
5386 @Override
5387 public String toString() {
5388 return "PackageSetting{"
5389 + Integer.toHexString(System.identityHashCode(this))
5390 + " " + name + "/" + userId + "}";
5391 }
5392 }
5393
5394 /**
5395 * Settings data for a particular shared user ID we know about.
5396 */
5397 static final class SharedUserSetting extends GrantedPermissions {
5398 final String name;
5399 int userId;
5400 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
5401 final PackageSignatures signatures = new PackageSignatures();
5402
5403 SharedUserSetting(String _name, int _pkgFlags) {
5404 super(_pkgFlags);
5405 name = _name;
5406 }
5407
5408 @Override
5409 public String toString() {
5410 return "SharedUserSetting{"
5411 + Integer.toHexString(System.identityHashCode(this))
5412 + " " + name + "/" + userId + "}";
5413 }
5414 }
5415
5416 /**
5417 * Holds information about dynamic settings.
5418 */
5419 private static final class Settings {
5420 private final File mSettingsFilename;
5421 private final File mBackupSettingsFilename;
5422 private final HashMap<String, PackageSetting> mPackages =
5423 new HashMap<String, PackageSetting>();
5424 // The user's preferred packages/applications, in order of preference.
5425 // First is the most preferred.
5426 private final ArrayList<PackageSetting> mPreferredPackages =
5427 new ArrayList<PackageSetting>();
5428 // List of replaced system applications
5429 final HashMap<String, PackageSetting> mDisabledSysPackages =
5430 new HashMap<String, PackageSetting>();
5431
5432 // The user's preferred activities associated with particular intent
5433 // filters.
5434 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
5435 new IntentResolver<PreferredActivity, PreferredActivity>() {
5436 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005437 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005439 out.print(prefix); out.print(
5440 Integer.toHexString(System.identityHashCode(filter)));
5441 out.print(' ');
5442 out.print(filter.mActivity.flattenToShortString());
5443 out.print(" match=0x");
5444 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005446 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005448 out.print(prefix); out.print(" ");
5449 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 }
5451 }
5452 }
5453 };
5454 private final HashMap<String, SharedUserSetting> mSharedUsers =
5455 new HashMap<String, SharedUserSetting>();
5456 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
5457 private final SparseArray<Object> mOtherUserIds =
5458 new SparseArray<Object>();
5459
5460 // For reading/writing settings file.
5461 private final ArrayList<Signature> mPastSignatures =
5462 new ArrayList<Signature>();
5463
5464 // Mapping from permission names to info about them.
5465 final HashMap<String, BasePermission> mPermissions =
5466 new HashMap<String, BasePermission>();
5467
5468 // Mapping from permission tree names to info about them.
5469 final HashMap<String, BasePermission> mPermissionTrees =
5470 new HashMap<String, BasePermission>();
5471
5472 private final ArrayList<String> mPendingPreferredPackages
5473 = new ArrayList<String>();
5474
5475 private final StringBuilder mReadMessages = new StringBuilder();
5476
5477 private static final class PendingPackage extends PackageSettingBase {
5478 final int sharedId;
5479
5480 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005481 int sharedId, int pVersionCode, int pkgFlags) {
5482 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 this.sharedId = sharedId;
5484 }
5485 }
5486 private final ArrayList<PendingPackage> mPendingPackages
5487 = new ArrayList<PendingPackage>();
5488
5489 Settings() {
5490 File dataDir = Environment.getDataDirectory();
5491 File systemDir = new File(dataDir, "system");
5492 systemDir.mkdirs();
5493 FileUtils.setPermissions(systemDir.toString(),
5494 FileUtils.S_IRWXU|FileUtils.S_IRWXG
5495 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
5496 -1, -1);
5497 mSettingsFilename = new File(systemDir, "packages.xml");
5498 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
5499 }
5500
5501 PackageSetting getPackageLP(PackageParser.Package pkg,
5502 SharedUserSetting sharedUser, File codePath, File resourcePath,
5503 int pkgFlags, boolean create, boolean add) {
5504 final String name = pkg.packageName;
5505 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005506 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507
5508 if (p != null) {
5509 p.pkg = pkg;
5510 }
5511 return p;
5512 }
5513
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005514 PackageSetting peekPackageLP(String name) {
5515 return mPackages.get(name);
5516 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 PackageSetting p = mPackages.get(name);
5518 if (p != null && p.codePath.getPath().equals(codePath)) {
5519 return p;
5520 }
5521 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005522 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 }
5524
5525 void setInstallStatus(String pkgName, int status) {
5526 PackageSetting p = mPackages.get(pkgName);
5527 if(p != null) {
5528 if(p.getInstallStatus() != status) {
5529 p.setInstallStatus(status);
5530 }
5531 }
5532 }
5533
Jacek Surazskic64322c2009-04-28 15:26:38 +02005534 void setInstallerPackageName(String pkgName,
5535 String installerPkgName) {
5536 PackageSetting p = mPackages.get(pkgName);
5537 if(p != null) {
5538 p.setInstallerPackageName(installerPkgName);
5539 }
5540 }
5541
5542 String getInstallerPackageName(String pkgName) {
5543 PackageSetting p = mPackages.get(pkgName);
5544 return (p == null) ? null : p.getInstallerPackageName();
5545 }
5546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 int getInstallStatus(String pkgName) {
5548 PackageSetting p = mPackages.get(pkgName);
5549 if(p != null) {
5550 return p.getInstallStatus();
5551 }
5552 return -1;
5553 }
5554
5555 SharedUserSetting getSharedUserLP(String name,
5556 int pkgFlags, boolean create) {
5557 SharedUserSetting s = mSharedUsers.get(name);
5558 if (s == null) {
5559 if (!create) {
5560 return null;
5561 }
5562 s = new SharedUserSetting(name, pkgFlags);
5563 if (MULTIPLE_APPLICATION_UIDS) {
5564 s.userId = newUserIdLP(s);
5565 } else {
5566 s.userId = FIRST_APPLICATION_UID;
5567 }
5568 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
5569 // < 0 means we couldn't assign a userid; fall out and return
5570 // s, which is currently null
5571 if (s.userId >= 0) {
5572 mSharedUsers.put(name, s);
5573 }
5574 }
5575
5576 return s;
5577 }
5578
5579 int disableSystemPackageLP(String name) {
5580 PackageSetting p = mPackages.get(name);
5581 if(p == null) {
5582 Log.w(TAG, "Package:"+name+" is not an installed package");
5583 return -1;
5584 }
5585 PackageSetting dp = mDisabledSysPackages.get(name);
5586 // always make sure the system package code and resource paths dont change
5587 if(dp == null) {
5588 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
5589 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5590 }
5591 mDisabledSysPackages.put(name, p);
5592 }
5593 return removePackageLP(name);
5594 }
5595
5596 PackageSetting enableSystemPackageLP(String name) {
5597 PackageSetting p = mDisabledSysPackages.get(name);
5598 if(p == null) {
5599 Log.w(TAG, "Package:"+name+" is not disabled");
5600 return null;
5601 }
5602 // Reset flag in ApplicationInfo object
5603 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
5604 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5605 }
5606 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005607 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 mDisabledSysPackages.remove(name);
5609 return ret;
5610 }
5611
5612 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005613 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 PackageSetting p = mPackages.get(name);
5615 if (p != null) {
5616 if (p.userId == uid) {
5617 return p;
5618 }
5619 reportSettingsProblem(Log.ERROR,
5620 "Adding duplicate package, keeping first: " + name);
5621 return null;
5622 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005623 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 p.userId = uid;
5625 if (addUserIdLP(uid, p, name)) {
5626 mPackages.put(name, p);
5627 return p;
5628 }
5629 return null;
5630 }
5631
5632 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
5633 SharedUserSetting s = mSharedUsers.get(name);
5634 if (s != null) {
5635 if (s.userId == uid) {
5636 return s;
5637 }
5638 reportSettingsProblem(Log.ERROR,
5639 "Adding duplicate shared user, keeping first: " + name);
5640 return null;
5641 }
5642 s = new SharedUserSetting(name, pkgFlags);
5643 s.userId = uid;
5644 if (addUserIdLP(uid, s, name)) {
5645 mSharedUsers.put(name, s);
5646 return s;
5647 }
5648 return null;
5649 }
5650
5651 private PackageSetting getPackageLP(String name,
5652 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005653 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 PackageSetting p = mPackages.get(name);
5655 if (p != null) {
5656 if (!p.codePath.equals(codePath)) {
5657 // Check to see if its a disabled system app
5658 PackageSetting ps = mDisabledSysPackages.get(name);
5659 if((ps != null) && ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5660 // Could be a replaced system package
5661 // Note that if the user replaced a system app, the user has to physically
5662 // delete the new one in order to revert to the system app. So even
5663 // if the user updated the system app via an update, the user still
5664 // has to delete the one installed in the data partition in order to pick up the
5665 // new system package.
5666 return p;
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07005667 } else if ((p.pkg != null) && (p.pkg.applicationInfo != null) &&
5668 ((p.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)) {
5669 // Check for non-system apps
5670 reportSettingsProblem(Log.WARN,
5671 "Package " + name + " codePath changed from " + p.codePath
5672 + " to " + codePath + "; Retaining data and using new code");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 } else {
5674 reportSettingsProblem(Log.WARN,
5675 "Package " + name + " codePath changed from " + p.codePath
5676 + " to " + codePath + "; replacing with new");
5677 p = null;
5678 }
5679 } else if (p.sharedUser != sharedUser) {
5680 reportSettingsProblem(Log.WARN,
5681 "Package " + name + " shared user changed from "
5682 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
5683 + " to "
5684 + (sharedUser != null ? sharedUser.name : "<nothing>")
5685 + "; replacing with new");
5686 p = null;
5687 }
5688 }
5689 if (p == null) {
5690 // Create a new PackageSettings entry. this can end up here because
5691 // of code path mismatch or user id mismatch of an updated system partition
5692 if (!create) {
5693 return null;
5694 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005695 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07005697 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005698 if (sharedUser != null) {
5699 p.userId = sharedUser.userId;
5700 } else if (MULTIPLE_APPLICATION_UIDS) {
5701 p.userId = newUserIdLP(p);
5702 } else {
5703 p.userId = FIRST_APPLICATION_UID;
5704 }
5705 if (p.userId < 0) {
5706 reportSettingsProblem(Log.WARN,
5707 "Package " + name + " could not be assigned a valid uid");
5708 return null;
5709 }
5710 if (add) {
5711 // Finish adding new package by adding it and updating shared
5712 // user preferences
5713 insertPackageSettingLP(p, name, sharedUser);
5714 }
5715 }
5716 return p;
5717 }
5718
5719 // Utility method that adds a PackageSetting to mPackages and
5720 // completes updating the shared user attributes
5721 private void insertPackageSettingLP(PackageSetting p, String name,
5722 SharedUserSetting sharedUser) {
5723 mPackages.put(name, p);
5724 if (sharedUser != null) {
5725 if (p.sharedUser != null && p.sharedUser != sharedUser) {
5726 reportSettingsProblem(Log.ERROR,
5727 "Package " + p.name + " was user "
5728 + p.sharedUser + " but is now " + sharedUser
5729 + "; I am not changing its files so it will probably fail!");
5730 p.sharedUser.packages.remove(p);
5731 } else if (p.userId != sharedUser.userId) {
5732 reportSettingsProblem(Log.ERROR,
5733 "Package " + p.name + " was user id " + p.userId
5734 + " but is now user " + sharedUser
5735 + " with id " + sharedUser.userId
5736 + "; I am not changing its files so it will probably fail!");
5737 }
5738
5739 sharedUser.packages.add(p);
5740 p.sharedUser = sharedUser;
5741 p.userId = sharedUser.userId;
5742 }
5743 }
5744
5745 private void updateSharedUserPerms (PackageSetting deletedPs) {
5746 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
5747 Log.i(TAG, "Trying to update info for null package. Just ignoring");
5748 return;
5749 }
5750 // No sharedUserId
5751 if (deletedPs.sharedUser == null) {
5752 return;
5753 }
5754 SharedUserSetting sus = deletedPs.sharedUser;
5755 // Update permissions
5756 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
5757 boolean used = false;
5758 if (!sus.grantedPermissions.contains (eachPerm)) {
5759 continue;
5760 }
5761 for (PackageSetting pkg:sus.packages) {
5762 if (pkg.grantedPermissions.contains (eachPerm)) {
5763 used = true;
5764 break;
5765 }
5766 }
5767 if (!used) {
5768 // can safely delete this permission from list
5769 sus.grantedPermissions.remove(eachPerm);
5770 sus.loadedPermissions.remove(eachPerm);
5771 }
5772 }
5773 // Update gids
5774 int newGids[] = null;
5775 for (PackageSetting pkg:sus.packages) {
5776 newGids = appendInts(newGids, pkg.gids);
5777 }
5778 sus.gids = newGids;
5779 }
5780
5781 private int removePackageLP(String name) {
5782 PackageSetting p = mPackages.get(name);
5783 if (p != null) {
5784 mPackages.remove(name);
5785 if (p.sharedUser != null) {
5786 p.sharedUser.packages.remove(p);
5787 if (p.sharedUser.packages.size() == 0) {
5788 mSharedUsers.remove(p.sharedUser.name);
5789 removeUserIdLP(p.sharedUser.userId);
5790 return p.sharedUser.userId;
5791 }
5792 } else {
5793 removeUserIdLP(p.userId);
5794 return p.userId;
5795 }
5796 }
5797 return -1;
5798 }
5799
5800 private boolean addUserIdLP(int uid, Object obj, Object name) {
5801 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
5802 return false;
5803 }
5804
5805 if (uid >= FIRST_APPLICATION_UID) {
5806 int N = mUserIds.size();
5807 final int index = uid - FIRST_APPLICATION_UID;
5808 while (index >= N) {
5809 mUserIds.add(null);
5810 N++;
5811 }
5812 if (mUserIds.get(index) != null) {
5813 reportSettingsProblem(Log.ERROR,
5814 "Adding duplicate shared id: " + uid
5815 + " name=" + name);
5816 return false;
5817 }
5818 mUserIds.set(index, obj);
5819 } else {
5820 if (mOtherUserIds.get(uid) != null) {
5821 reportSettingsProblem(Log.ERROR,
5822 "Adding duplicate shared id: " + uid
5823 + " name=" + name);
5824 return false;
5825 }
5826 mOtherUserIds.put(uid, obj);
5827 }
5828 return true;
5829 }
5830
5831 public Object getUserIdLP(int uid) {
5832 if (uid >= FIRST_APPLICATION_UID) {
5833 int N = mUserIds.size();
5834 final int index = uid - FIRST_APPLICATION_UID;
5835 return index < N ? mUserIds.get(index) : null;
5836 } else {
5837 return mOtherUserIds.get(uid);
5838 }
5839 }
5840
5841 private void removeUserIdLP(int uid) {
5842 if (uid >= FIRST_APPLICATION_UID) {
5843 int N = mUserIds.size();
5844 final int index = uid - FIRST_APPLICATION_UID;
5845 if (index < N) mUserIds.set(index, null);
5846 } else {
5847 mOtherUserIds.remove(uid);
5848 }
5849 }
5850
5851 void writeLP() {
5852 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
5853
5854 // Keep the old settings around until we know the new ones have
5855 // been successfully written.
5856 if (mSettingsFilename.exists()) {
5857 if (mBackupSettingsFilename.exists()) {
5858 mBackupSettingsFilename.delete();
5859 }
5860 mSettingsFilename.renameTo(mBackupSettingsFilename);
5861 }
5862
5863 mPastSignatures.clear();
5864
5865 try {
5866 FileOutputStream str = new FileOutputStream(mSettingsFilename);
5867
5868 //XmlSerializer serializer = XmlUtils.serializerInstance();
5869 XmlSerializer serializer = new FastXmlSerializer();
5870 serializer.setOutput(str, "utf-8");
5871 serializer.startDocument(null, true);
5872 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
5873
5874 serializer.startTag(null, "packages");
5875
5876 serializer.startTag(null, "permission-trees");
5877 for (BasePermission bp : mPermissionTrees.values()) {
5878 writePermission(serializer, bp);
5879 }
5880 serializer.endTag(null, "permission-trees");
5881
5882 serializer.startTag(null, "permissions");
5883 for (BasePermission bp : mPermissions.values()) {
5884 writePermission(serializer, bp);
5885 }
5886 serializer.endTag(null, "permissions");
5887
5888 for (PackageSetting pkg : mPackages.values()) {
5889 writePackage(serializer, pkg);
5890 }
5891
5892 for (PackageSetting pkg : mDisabledSysPackages.values()) {
5893 writeDisabledSysPackage(serializer, pkg);
5894 }
5895
5896 serializer.startTag(null, "preferred-packages");
5897 int N = mPreferredPackages.size();
5898 for (int i=0; i<N; i++) {
5899 PackageSetting pkg = mPreferredPackages.get(i);
5900 serializer.startTag(null, "item");
5901 serializer.attribute(null, "name", pkg.name);
5902 serializer.endTag(null, "item");
5903 }
5904 serializer.endTag(null, "preferred-packages");
5905
5906 serializer.startTag(null, "preferred-activities");
5907 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
5908 serializer.startTag(null, "item");
5909 pa.writeToXml(serializer);
5910 serializer.endTag(null, "item");
5911 }
5912 serializer.endTag(null, "preferred-activities");
5913
5914 for (SharedUserSetting usr : mSharedUsers.values()) {
5915 serializer.startTag(null, "shared-user");
5916 serializer.attribute(null, "name", usr.name);
5917 serializer.attribute(null, "userId",
5918 Integer.toString(usr.userId));
5919 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
5920 serializer.startTag(null, "perms");
5921 for (String name : usr.grantedPermissions) {
5922 serializer.startTag(null, "item");
5923 serializer.attribute(null, "name", name);
5924 serializer.endTag(null, "item");
5925 }
5926 serializer.endTag(null, "perms");
5927 serializer.endTag(null, "shared-user");
5928 }
5929
5930 serializer.endTag(null, "packages");
5931
5932 serializer.endDocument();
5933
5934 str.flush();
5935 str.close();
5936
5937 // New settings successfully written, old ones are no longer
5938 // needed.
5939 mBackupSettingsFilename.delete();
5940 FileUtils.setPermissions(mSettingsFilename.toString(),
5941 FileUtils.S_IRUSR|FileUtils.S_IWUSR
5942 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
5943 |FileUtils.S_IROTH,
5944 -1, -1);
5945
5946 } catch(XmlPullParserException e) {
5947 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
5948
5949 } catch(java.io.IOException e) {
5950 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
5951
5952 }
5953
5954 //Debug.stopMethodTracing();
5955 }
5956
5957 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
5958 throws java.io.IOException {
5959 serializer.startTag(null, "updated-package");
5960 serializer.attribute(null, "name", pkg.name);
5961 serializer.attribute(null, "codePath", pkg.codePathString);
5962 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005963 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005964 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
5965 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
5966 }
5967 if (pkg.sharedUser == null) {
5968 serializer.attribute(null, "userId",
5969 Integer.toString(pkg.userId));
5970 } else {
5971 serializer.attribute(null, "sharedUserId",
5972 Integer.toString(pkg.userId));
5973 }
5974 serializer.startTag(null, "perms");
5975 if (pkg.sharedUser == null) {
5976 // If this is a shared user, the permissions will
5977 // be written there. We still need to write an
5978 // empty permissions list so permissionsFixed will
5979 // be set.
5980 for (final String name : pkg.grantedPermissions) {
5981 BasePermission bp = mPermissions.get(name);
5982 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
5983 // We only need to write signature or system permissions but this wont
5984 // match the semantics of grantedPermissions. So write all permissions.
5985 serializer.startTag(null, "item");
5986 serializer.attribute(null, "name", name);
5987 serializer.endTag(null, "item");
5988 }
5989 }
5990 }
5991 serializer.endTag(null, "perms");
5992 serializer.endTag(null, "updated-package");
5993 }
5994
5995 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
5996 throws java.io.IOException {
5997 serializer.startTag(null, "package");
5998 serializer.attribute(null, "name", pkg.name);
5999 serializer.attribute(null, "codePath", pkg.codePathString);
6000 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6001 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6002 }
6003 serializer.attribute(null, "system",
6004 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6005 ? "true" : "false");
6006 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006007 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 if (pkg.sharedUser == null) {
6009 serializer.attribute(null, "userId",
6010 Integer.toString(pkg.userId));
6011 } else {
6012 serializer.attribute(null, "sharedUserId",
6013 Integer.toString(pkg.userId));
6014 }
6015 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6016 serializer.attribute(null, "enabled",
6017 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6018 ? "true" : "false");
6019 }
6020 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6021 serializer.attribute(null, "installStatus", "false");
6022 }
Jacek Surazskic64322c2009-04-28 15:26:38 +02006023 if (pkg.installerPackageName != null) {
6024 serializer.attribute(null, "installer", pkg.installerPackageName);
6025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6027 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6028 serializer.startTag(null, "perms");
6029 if (pkg.sharedUser == null) {
6030 // If this is a shared user, the permissions will
6031 // be written there. We still need to write an
6032 // empty permissions list so permissionsFixed will
6033 // be set.
6034 for (final String name : pkg.grantedPermissions) {
6035 serializer.startTag(null, "item");
6036 serializer.attribute(null, "name", name);
6037 serializer.endTag(null, "item");
6038 }
6039 }
6040 serializer.endTag(null, "perms");
6041 }
6042 if (pkg.disabledComponents.size() > 0) {
6043 serializer.startTag(null, "disabled-components");
6044 for (final String name : pkg.disabledComponents) {
6045 serializer.startTag(null, "item");
6046 serializer.attribute(null, "name", name);
6047 serializer.endTag(null, "item");
6048 }
6049 serializer.endTag(null, "disabled-components");
6050 }
6051 if (pkg.enabledComponents.size() > 0) {
6052 serializer.startTag(null, "enabled-components");
6053 for (final String name : pkg.enabledComponents) {
6054 serializer.startTag(null, "item");
6055 serializer.attribute(null, "name", name);
6056 serializer.endTag(null, "item");
6057 }
6058 serializer.endTag(null, "enabled-components");
6059 }
Jacek Surazskic64322c2009-04-28 15:26:38 +02006060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 serializer.endTag(null, "package");
6062 }
6063
6064 void writePermission(XmlSerializer serializer, BasePermission bp)
6065 throws XmlPullParserException, java.io.IOException {
6066 if (bp.type != BasePermission.TYPE_BUILTIN
6067 && bp.sourcePackage != null) {
6068 serializer.startTag(null, "item");
6069 serializer.attribute(null, "name", bp.name);
6070 serializer.attribute(null, "package", bp.sourcePackage);
6071 if (DEBUG_SETTINGS) Log.v(TAG,
6072 "Writing perm: name=" + bp.name + " type=" + bp.type);
6073 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6074 PermissionInfo pi = bp.perm != null ? bp.perm.info
6075 : bp.pendingInfo;
6076 if (pi != null) {
6077 serializer.attribute(null, "type", "dynamic");
6078 if (pi.icon != 0) {
6079 serializer.attribute(null, "icon",
6080 Integer.toString(pi.icon));
6081 }
6082 if (pi.nonLocalizedLabel != null) {
6083 serializer.attribute(null, "label",
6084 pi.nonLocalizedLabel.toString());
6085 }
6086 if (pi.protectionLevel !=
6087 PermissionInfo.PROTECTION_NORMAL) {
6088 serializer.attribute(null, "protection",
6089 Integer.toString(pi.protectionLevel));
6090 }
6091 }
6092 }
6093 serializer.endTag(null, "item");
6094 }
6095 }
6096
6097 String getReadMessagesLP() {
6098 return mReadMessages.toString();
6099 }
6100
6101 ArrayList<String> getListOfIncompleteInstallPackages() {
6102 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6103 Iterator<String> its = kList.iterator();
6104 ArrayList<String> ret = new ArrayList<String>();
6105 while(its.hasNext()) {
6106 String key = its.next();
6107 PackageSetting ps = mPackages.get(key);
6108 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
6109 ret.add(key);
6110 }
6111 }
6112 return ret;
6113 }
6114
6115 boolean readLP() {
6116 FileInputStream str = null;
6117 if (mBackupSettingsFilename.exists()) {
6118 try {
6119 str = new FileInputStream(mBackupSettingsFilename);
6120 mReadMessages.append("Reading from backup settings file\n");
6121 Log.i(TAG, "Reading from backup settings file!");
6122 } catch (java.io.IOException e) {
6123 // We'll try for the normal settings file.
6124 }
6125 }
6126
6127 mPastSignatures.clear();
6128
6129 try {
6130 if (str == null) {
6131 if (!mSettingsFilename.exists()) {
6132 mReadMessages.append("No settings file found\n");
6133 Log.i(TAG, "No current settings file!");
6134 return false;
6135 }
6136 str = new FileInputStream(mSettingsFilename);
6137 }
6138 XmlPullParser parser = Xml.newPullParser();
6139 parser.setInput(str, null);
6140
6141 int type;
6142 while ((type=parser.next()) != XmlPullParser.START_TAG
6143 && type != XmlPullParser.END_DOCUMENT) {
6144 ;
6145 }
6146
6147 if (type != XmlPullParser.START_TAG) {
6148 mReadMessages.append("No start tag found in settings file\n");
6149 Log.e(TAG, "No start tag found in package manager settings");
6150 return false;
6151 }
6152
6153 int outerDepth = parser.getDepth();
6154 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6155 && (type != XmlPullParser.END_TAG
6156 || parser.getDepth() > outerDepth)) {
6157 if (type == XmlPullParser.END_TAG
6158 || type == XmlPullParser.TEXT) {
6159 continue;
6160 }
6161
6162 String tagName = parser.getName();
6163 if (tagName.equals("package")) {
6164 readPackageLP(parser);
6165 } else if (tagName.equals("permissions")) {
6166 readPermissionsLP(mPermissions, parser);
6167 } else if (tagName.equals("permission-trees")) {
6168 readPermissionsLP(mPermissionTrees, parser);
6169 } else if (tagName.equals("shared-user")) {
6170 readSharedUserLP(parser);
6171 } else if (tagName.equals("preferred-packages")) {
6172 readPreferredPackagesLP(parser);
6173 } else if (tagName.equals("preferred-activities")) {
6174 readPreferredActivitiesLP(parser);
6175 } else if(tagName.equals("updated-package")) {
6176 readDisabledSysPackageLP(parser);
6177 } else {
6178 Log.w(TAG, "Unknown element under <packages>: "
6179 + parser.getName());
6180 XmlUtils.skipCurrentTag(parser);
6181 }
6182 }
6183
6184 str.close();
6185
6186 } catch(XmlPullParserException e) {
6187 mReadMessages.append("Error reading: " + e.toString());
6188 Log.e(TAG, "Error reading package manager settings", e);
6189
6190 } catch(java.io.IOException e) {
6191 mReadMessages.append("Error reading: " + e.toString());
6192 Log.e(TAG, "Error reading package manager settings", e);
6193
6194 }
6195
6196 int N = mPendingPackages.size();
6197 for (int i=0; i<N; i++) {
6198 final PendingPackage pp = mPendingPackages.get(i);
6199 Object idObj = getUserIdLP(pp.sharedId);
6200 if (idObj != null && idObj instanceof SharedUserSetting) {
6201 PackageSetting p = getPackageLP(pp.name,
6202 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006203 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 if (p == null) {
6205 Log.w(TAG, "Unable to create application package for "
6206 + pp.name);
6207 continue;
6208 }
6209 p.copyFrom(pp);
6210 } else if (idObj != null) {
6211 String msg = "Bad package setting: package " + pp.name
6212 + " has shared uid " + pp.sharedId
6213 + " that is not a shared uid\n";
6214 mReadMessages.append(msg);
6215 Log.e(TAG, msg);
6216 } else {
6217 String msg = "Bad package setting: package " + pp.name
6218 + " has shared uid " + pp.sharedId
6219 + " that is not defined\n";
6220 mReadMessages.append(msg);
6221 Log.e(TAG, msg);
6222 }
6223 }
6224 mPendingPackages.clear();
6225
6226 N = mPendingPreferredPackages.size();
6227 mPreferredPackages.clear();
6228 for (int i=0; i<N; i++) {
6229 final String name = mPendingPreferredPackages.get(i);
6230 final PackageSetting p = mPackages.get(name);
6231 if (p != null) {
6232 mPreferredPackages.add(p);
6233 } else {
6234 Log.w(TAG, "Unknown preferred package: " + name);
6235 }
6236 }
6237 mPendingPreferredPackages.clear();
6238
6239 mReadMessages.append("Read completed successfully: "
6240 + mPackages.size() + " packages, "
6241 + mSharedUsers.size() + " shared uids\n");
6242
6243 return true;
6244 }
6245
6246 private int readInt(XmlPullParser parser, String ns, String name,
6247 int defValue) {
6248 String v = parser.getAttributeValue(ns, name);
6249 try {
6250 if (v == null) {
6251 return defValue;
6252 }
6253 return Integer.parseInt(v);
6254 } catch (NumberFormatException e) {
6255 reportSettingsProblem(Log.WARN,
6256 "Error in package manager settings: attribute " +
6257 name + " has bad integer value " + v + " at "
6258 + parser.getPositionDescription());
6259 }
6260 return defValue;
6261 }
6262
6263 private void readPermissionsLP(HashMap<String, BasePermission> out,
6264 XmlPullParser parser)
6265 throws IOException, XmlPullParserException {
6266 int outerDepth = parser.getDepth();
6267 int type;
6268 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6269 && (type != XmlPullParser.END_TAG
6270 || parser.getDepth() > outerDepth)) {
6271 if (type == XmlPullParser.END_TAG
6272 || type == XmlPullParser.TEXT) {
6273 continue;
6274 }
6275
6276 String tagName = parser.getName();
6277 if (tagName.equals("item")) {
6278 String name = parser.getAttributeValue(null, "name");
6279 String sourcePackage = parser.getAttributeValue(null, "package");
6280 String ptype = parser.getAttributeValue(null, "type");
6281 if (name != null && sourcePackage != null) {
6282 boolean dynamic = "dynamic".equals(ptype);
6283 BasePermission bp = new BasePermission(name, sourcePackage,
6284 dynamic
6285 ? BasePermission.TYPE_DYNAMIC
6286 : BasePermission.TYPE_NORMAL);
6287 if (dynamic) {
6288 PermissionInfo pi = new PermissionInfo();
6289 pi.packageName = sourcePackage.intern();
6290 pi.name = name.intern();
6291 pi.icon = readInt(parser, null, "icon", 0);
6292 pi.nonLocalizedLabel = parser.getAttributeValue(
6293 null, "label");
6294 pi.protectionLevel = readInt(parser, null, "protection",
6295 PermissionInfo.PROTECTION_NORMAL);
6296 bp.pendingInfo = pi;
6297 }
6298 out.put(bp.name, bp);
6299 } else {
6300 reportSettingsProblem(Log.WARN,
6301 "Error in package manager settings: permissions has"
6302 + " no name at " + parser.getPositionDescription());
6303 }
6304 } else {
6305 reportSettingsProblem(Log.WARN,
6306 "Unknown element reading permissions: "
6307 + parser.getName() + " at "
6308 + parser.getPositionDescription());
6309 }
6310 XmlUtils.skipCurrentTag(parser);
6311 }
6312 }
6313
6314 private void readDisabledSysPackageLP(XmlPullParser parser)
6315 throws XmlPullParserException, IOException {
6316 String name = parser.getAttributeValue(null, "name");
6317 String codePathStr = parser.getAttributeValue(null, "codePath");
6318 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6319 if(resourcePathStr == null) {
6320 resourcePathStr = codePathStr;
6321 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006322 String version = parser.getAttributeValue(null, "version");
6323 int versionCode = 0;
6324 if (version != null) {
6325 try {
6326 versionCode = Integer.parseInt(version);
6327 } catch (NumberFormatException e) {
6328 }
6329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330
6331 int pkgFlags = 0;
6332 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6333 PackageSetting ps = new PackageSetting(name,
6334 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006335 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 String timeStampStr = parser.getAttributeValue(null, "ts");
6337 if (timeStampStr != null) {
6338 try {
6339 long timeStamp = Long.parseLong(timeStampStr);
6340 ps.setTimeStamp(timeStamp, timeStampStr);
6341 } catch (NumberFormatException e) {
6342 }
6343 }
6344 String idStr = parser.getAttributeValue(null, "userId");
6345 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
6346 if(ps.userId <= 0) {
6347 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6348 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
6349 }
6350 int outerDepth = parser.getDepth();
6351 int type;
6352 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6353 && (type != XmlPullParser.END_TAG
6354 || parser.getDepth() > outerDepth)) {
6355 if (type == XmlPullParser.END_TAG
6356 || type == XmlPullParser.TEXT) {
6357 continue;
6358 }
6359
6360 String tagName = parser.getName();
6361 if (tagName.equals("perms")) {
6362 readGrantedPermissionsLP(parser,
6363 ps.grantedPermissions);
6364 } else {
6365 reportSettingsProblem(Log.WARN,
6366 "Unknown element under <updated-package>: "
6367 + parser.getName());
6368 XmlUtils.skipCurrentTag(parser);
6369 }
6370 }
6371 mDisabledSysPackages.put(name, ps);
6372 }
6373
6374 private void readPackageLP(XmlPullParser parser)
6375 throws XmlPullParserException, IOException {
6376 String name = null;
6377 String idStr = null;
6378 String sharedIdStr = null;
6379 String codePathStr = null;
6380 String resourcePathStr = null;
6381 String systemStr = null;
Jacek Surazskic64322c2009-04-28 15:26:38 +02006382 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 int pkgFlags = 0;
6384 String timeStampStr;
6385 long timeStamp = 0;
6386 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006387 String version = null;
6388 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 try {
6390 name = parser.getAttributeValue(null, "name");
6391 idStr = parser.getAttributeValue(null, "userId");
6392 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6393 codePathStr = parser.getAttributeValue(null, "codePath");
6394 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006395 version = parser.getAttributeValue(null, "version");
6396 if (version != null) {
6397 try {
6398 versionCode = Integer.parseInt(version);
6399 } catch (NumberFormatException e) {
6400 }
6401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazskic64322c2009-04-28 15:26:38 +02006403 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 if (systemStr != null) {
6405 if ("true".equals(systemStr)) {
6406 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6407 }
6408 } else {
6409 // Old settings that don't specify system... just treat
6410 // them as system, good enough.
6411 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6412 }
6413 timeStampStr = parser.getAttributeValue(null, "ts");
6414 if (timeStampStr != null) {
6415 try {
6416 timeStamp = Long.parseLong(timeStampStr);
6417 } catch (NumberFormatException e) {
6418 }
6419 }
6420 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
6421 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
6422 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
6423 if (resourcePathStr == null) {
6424 resourcePathStr = codePathStr;
6425 }
6426 if (name == null) {
6427 reportSettingsProblem(Log.WARN,
6428 "Error in package manager settings: <package> has no name at "
6429 + parser.getPositionDescription());
6430 } else if (codePathStr == null) {
6431 reportSettingsProblem(Log.WARN,
6432 "Error in package manager settings: <package> has no codePath at "
6433 + parser.getPositionDescription());
6434 } else if (userId > 0) {
6435 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006436 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
6438 + ": userId=" + userId + " pkg=" + packageSetting);
6439 if (packageSetting == null) {
6440 reportSettingsProblem(Log.ERROR,
6441 "Failure adding uid " + userId
6442 + " while parsing settings at "
6443 + parser.getPositionDescription());
6444 } else {
6445 packageSetting.setTimeStamp(timeStamp, timeStampStr);
6446 }
6447 } else if (sharedIdStr != null) {
6448 userId = sharedIdStr != null
6449 ? Integer.parseInt(sharedIdStr) : 0;
6450 if (userId > 0) {
6451 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006452 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 packageSetting.setTimeStamp(timeStamp, timeStampStr);
6454 mPendingPackages.add((PendingPackage) packageSetting);
6455 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
6456 + ": sharedUserId=" + userId + " pkg="
6457 + packageSetting);
6458 } else {
6459 reportSettingsProblem(Log.WARN,
6460 "Error in package manager settings: package "
6461 + name + " has bad sharedId " + sharedIdStr
6462 + " at " + parser.getPositionDescription());
6463 }
6464 } else {
6465 reportSettingsProblem(Log.WARN,
6466 "Error in package manager settings: package "
6467 + name + " has bad userId " + idStr + " at "
6468 + parser.getPositionDescription());
6469 }
6470 } catch (NumberFormatException e) {
6471 reportSettingsProblem(Log.WARN,
6472 "Error in package manager settings: package "
6473 + name + " has bad userId " + idStr + " at "
6474 + parser.getPositionDescription());
6475 }
6476 if (packageSetting != null) {
Jacek Surazskic64322c2009-04-28 15:26:38 +02006477 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 final String enabledStr = parser.getAttributeValue(null, "enabled");
6479 if (enabledStr != null) {
6480 if (enabledStr.equalsIgnoreCase("true")) {
6481 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
6482 } else if (enabledStr.equalsIgnoreCase("false")) {
6483 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
6484 } else if (enabledStr.equalsIgnoreCase("default")) {
6485 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6486 } else {
6487 reportSettingsProblem(Log.WARN,
6488 "Error in package manager settings: package "
6489 + name + " has bad enabled value: " + idStr
6490 + " at " + parser.getPositionDescription());
6491 }
6492 } else {
6493 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6494 }
6495 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
6496 if (installStatusStr != null) {
6497 if (installStatusStr.equalsIgnoreCase("false")) {
6498 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
6499 } else {
6500 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
6501 }
6502 }
6503
6504 int outerDepth = parser.getDepth();
6505 int type;
6506 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6507 && (type != XmlPullParser.END_TAG
6508 || parser.getDepth() > outerDepth)) {
6509 if (type == XmlPullParser.END_TAG
6510 || type == XmlPullParser.TEXT) {
6511 continue;
6512 }
6513
6514 String tagName = parser.getName();
6515 if (tagName.equals("disabled-components")) {
6516 readDisabledComponentsLP(packageSetting, parser);
6517 } else if (tagName.equals("enabled-components")) {
6518 readEnabledComponentsLP(packageSetting, parser);
6519 } else if (tagName.equals("sigs")) {
6520 packageSetting.signatures.readXml(parser, mPastSignatures);
6521 } else if (tagName.equals("perms")) {
6522 readGrantedPermissionsLP(parser,
6523 packageSetting.loadedPermissions);
6524 packageSetting.permissionsFixed = true;
6525 } else {
6526 reportSettingsProblem(Log.WARN,
6527 "Unknown element under <package>: "
6528 + parser.getName());
6529 XmlUtils.skipCurrentTag(parser);
6530 }
6531 }
6532 } else {
6533 XmlUtils.skipCurrentTag(parser);
6534 }
6535 }
6536
6537 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
6538 XmlPullParser parser)
6539 throws IOException, XmlPullParserException {
6540 int outerDepth = parser.getDepth();
6541 int type;
6542 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6543 && (type != XmlPullParser.END_TAG
6544 || parser.getDepth() > outerDepth)) {
6545 if (type == XmlPullParser.END_TAG
6546 || type == XmlPullParser.TEXT) {
6547 continue;
6548 }
6549
6550 String tagName = parser.getName();
6551 if (tagName.equals("item")) {
6552 String name = parser.getAttributeValue(null, "name");
6553 if (name != null) {
6554 packageSetting.disabledComponents.add(name.intern());
6555 } else {
6556 reportSettingsProblem(Log.WARN,
6557 "Error in package manager settings: <disabled-components> has"
6558 + " no name at " + parser.getPositionDescription());
6559 }
6560 } else {
6561 reportSettingsProblem(Log.WARN,
6562 "Unknown element under <disabled-components>: "
6563 + parser.getName());
6564 }
6565 XmlUtils.skipCurrentTag(parser);
6566 }
6567 }
6568
6569 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
6570 XmlPullParser parser)
6571 throws IOException, XmlPullParserException {
6572 int outerDepth = parser.getDepth();
6573 int type;
6574 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6575 && (type != XmlPullParser.END_TAG
6576 || parser.getDepth() > outerDepth)) {
6577 if (type == XmlPullParser.END_TAG
6578 || type == XmlPullParser.TEXT) {
6579 continue;
6580 }
6581
6582 String tagName = parser.getName();
6583 if (tagName.equals("item")) {
6584 String name = parser.getAttributeValue(null, "name");
6585 if (name != null) {
6586 packageSetting.enabledComponents.add(name.intern());
6587 } else {
6588 reportSettingsProblem(Log.WARN,
6589 "Error in package manager settings: <enabled-components> has"
6590 + " no name at " + parser.getPositionDescription());
6591 }
6592 } else {
6593 reportSettingsProblem(Log.WARN,
6594 "Unknown element under <enabled-components>: "
6595 + parser.getName());
6596 }
6597 XmlUtils.skipCurrentTag(parser);
6598 }
6599 }
6600
6601 private void readSharedUserLP(XmlPullParser parser)
6602 throws XmlPullParserException, IOException {
6603 String name = null;
6604 String idStr = null;
6605 int pkgFlags = 0;
6606 SharedUserSetting su = null;
6607 try {
6608 name = parser.getAttributeValue(null, "name");
6609 idStr = parser.getAttributeValue(null, "userId");
6610 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
6611 if ("true".equals(parser.getAttributeValue(null, "system"))) {
6612 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6613 }
6614 if (name == null) {
6615 reportSettingsProblem(Log.WARN,
6616 "Error in package manager settings: <shared-user> has no name at "
6617 + parser.getPositionDescription());
6618 } else if (userId == 0) {
6619 reportSettingsProblem(Log.WARN,
6620 "Error in package manager settings: shared-user "
6621 + name + " has bad userId " + idStr + " at "
6622 + parser.getPositionDescription());
6623 } else {
6624 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
6625 reportSettingsProblem(Log.ERROR,
6626 "Occurred while parsing settings at "
6627 + parser.getPositionDescription());
6628 }
6629 }
6630 } catch (NumberFormatException e) {
6631 reportSettingsProblem(Log.WARN,
6632 "Error in package manager settings: package "
6633 + name + " has bad userId " + idStr + " at "
6634 + parser.getPositionDescription());
6635 };
6636
6637 if (su != null) {
6638 int outerDepth = parser.getDepth();
6639 int type;
6640 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6641 && (type != XmlPullParser.END_TAG
6642 || parser.getDepth() > outerDepth)) {
6643 if (type == XmlPullParser.END_TAG
6644 || type == XmlPullParser.TEXT) {
6645 continue;
6646 }
6647
6648 String tagName = parser.getName();
6649 if (tagName.equals("sigs")) {
6650 su.signatures.readXml(parser, mPastSignatures);
6651 } else if (tagName.equals("perms")) {
6652 readGrantedPermissionsLP(parser, su.loadedPermissions);
6653 } else {
6654 reportSettingsProblem(Log.WARN,
6655 "Unknown element under <shared-user>: "
6656 + parser.getName());
6657 XmlUtils.skipCurrentTag(parser);
6658 }
6659 }
6660
6661 } else {
6662 XmlUtils.skipCurrentTag(parser);
6663 }
6664 }
6665
6666 private void readGrantedPermissionsLP(XmlPullParser parser,
6667 HashSet<String> outPerms) throws IOException, XmlPullParserException {
6668 int outerDepth = parser.getDepth();
6669 int type;
6670 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6671 && (type != XmlPullParser.END_TAG
6672 || parser.getDepth() > outerDepth)) {
6673 if (type == XmlPullParser.END_TAG
6674 || type == XmlPullParser.TEXT) {
6675 continue;
6676 }
6677
6678 String tagName = parser.getName();
6679 if (tagName.equals("item")) {
6680 String name = parser.getAttributeValue(null, "name");
6681 if (name != null) {
6682 outPerms.add(name.intern());
6683 } else {
6684 reportSettingsProblem(Log.WARN,
6685 "Error in package manager settings: <perms> has"
6686 + " no name at " + parser.getPositionDescription());
6687 }
6688 } else {
6689 reportSettingsProblem(Log.WARN,
6690 "Unknown element under <perms>: "
6691 + parser.getName());
6692 }
6693 XmlUtils.skipCurrentTag(parser);
6694 }
6695 }
6696
6697 private void readPreferredPackagesLP(XmlPullParser parser)
6698 throws XmlPullParserException, IOException {
6699 int outerDepth = parser.getDepth();
6700 int type;
6701 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6702 && (type != XmlPullParser.END_TAG
6703 || parser.getDepth() > outerDepth)) {
6704 if (type == XmlPullParser.END_TAG
6705 || type == XmlPullParser.TEXT) {
6706 continue;
6707 }
6708
6709 String tagName = parser.getName();
6710 if (tagName.equals("item")) {
6711 String name = parser.getAttributeValue(null, "name");
6712 if (name != null) {
6713 mPendingPreferredPackages.add(name);
6714 } else {
6715 reportSettingsProblem(Log.WARN,
6716 "Error in package manager settings: <preferred-package> has no name at "
6717 + parser.getPositionDescription());
6718 }
6719 } else {
6720 reportSettingsProblem(Log.WARN,
6721 "Unknown element under <preferred-packages>: "
6722 + parser.getName());
6723 }
6724 XmlUtils.skipCurrentTag(parser);
6725 }
6726 }
6727
6728 private void readPreferredActivitiesLP(XmlPullParser parser)
6729 throws XmlPullParserException, IOException {
6730 int outerDepth = parser.getDepth();
6731 int type;
6732 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6733 && (type != XmlPullParser.END_TAG
6734 || parser.getDepth() > outerDepth)) {
6735 if (type == XmlPullParser.END_TAG
6736 || type == XmlPullParser.TEXT) {
6737 continue;
6738 }
6739
6740 String tagName = parser.getName();
6741 if (tagName.equals("item")) {
6742 PreferredActivity pa = new PreferredActivity(parser);
6743 if (pa.mParseError == null) {
6744 mPreferredActivities.addFilter(pa);
6745 } else {
6746 reportSettingsProblem(Log.WARN,
6747 "Error in package manager settings: <preferred-activity> "
6748 + pa.mParseError + " at "
6749 + parser.getPositionDescription());
6750 }
6751 } else {
6752 reportSettingsProblem(Log.WARN,
6753 "Unknown element under <preferred-activities>: "
6754 + parser.getName());
6755 XmlUtils.skipCurrentTag(parser);
6756 }
6757 }
6758 }
6759
6760 // Returns -1 if we could not find an available UserId to assign
6761 private int newUserIdLP(Object obj) {
6762 // Let's be stupidly inefficient for now...
6763 final int N = mUserIds.size();
6764 for (int i=0; i<N; i++) {
6765 if (mUserIds.get(i) == null) {
6766 mUserIds.set(i, obj);
6767 return FIRST_APPLICATION_UID + i;
6768 }
6769 }
6770
6771 // None left?
6772 if (N >= MAX_APPLICATION_UIDS) {
6773 return -1;
6774 }
6775
6776 mUserIds.add(obj);
6777 return FIRST_APPLICATION_UID + N;
6778 }
6779
6780 public PackageSetting getDisabledSystemPkg(String name) {
6781 synchronized(mPackages) {
6782 PackageSetting ps = mDisabledSysPackages.get(name);
6783 return ps;
6784 }
6785 }
6786
6787 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
6788 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
6789 if (Config.LOGV) {
6790 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
6791 + " componentName = " + componentInfo.name);
6792 Log.v(TAG, "enabledComponents: "
6793 + Arrays.toString(packageSettings.enabledComponents.toArray()));
6794 Log.v(TAG, "disabledComponents: "
6795 + Arrays.toString(packageSettings.disabledComponents.toArray()));
6796 }
6797 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
6798 || ((componentInfo.enabled
6799 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
6800 || (componentInfo.applicationInfo.enabled
6801 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
6802 && !packageSettings.disabledComponents.contains(componentInfo.name))
6803 || packageSettings.enabledComponents.contains(componentInfo.name));
6804 }
6805 }
6806}