blob: 14714355512c21e867fe5bf14da69d81876a5797 [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);
Mihai Predac3320db2009-05-18 20:15:32 +02002903
2904 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02002905 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02002906 intentFilters = packageActivities.get(i).intents;
2907 if (intentFilters != null && intentFilters.size() > 0) {
2908 listCut.add(intentFilters);
2909 }
Mihai Predaeae850c2009-05-13 10:13:48 +02002910 }
2911 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
2912 }
2913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 public final void addActivity(PackageParser.Activity a, String type) {
2915 mActivities.put(a.component, a);
2916 if (SHOW_INFO || Config.LOGV) Log.v(
2917 TAG, " " + type + " " +
2918 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
2919 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
2920 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02002921 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
2923 if (SHOW_INFO || Config.LOGV) {
2924 Log.v(TAG, " IntentFilter:");
2925 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2926 }
2927 if (!intent.debugCheck()) {
2928 Log.w(TAG, "==> For Activity " + a.info.name);
2929 }
2930 addFilter(intent);
2931 }
2932 }
2933
2934 public final void removeActivity(PackageParser.Activity a, String type) {
2935 mActivities.remove(a.component);
2936 if (SHOW_INFO || Config.LOGV) Log.v(
2937 TAG, " " + type + " " +
2938 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
2939 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
2940 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02002941 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
2943 if (SHOW_INFO || Config.LOGV) {
2944 Log.v(TAG, " IntentFilter:");
2945 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2946 }
2947 removeFilter(intent);
2948 }
2949 }
2950
2951 @Override
2952 protected boolean allowFilterResult(
2953 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
2954 ActivityInfo filterAi = filter.activity.info;
2955 for (int i=dest.size()-1; i>=0; i--) {
2956 ActivityInfo destAi = dest.get(i).activityInfo;
2957 if (destAi.name == filterAi.name
2958 && destAi.packageName == filterAi.packageName) {
2959 return false;
2960 }
2961 }
2962 return true;
2963 }
2964
2965 @Override
2966 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
2967 int match) {
2968 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
2969 return null;
2970 }
2971 final PackageParser.Activity activity = info.activity;
2972 if (mSafeMode && (activity.info.applicationInfo.flags
2973 &ApplicationInfo.FLAG_SYSTEM) == 0) {
2974 return null;
2975 }
2976 final ResolveInfo res = new ResolveInfo();
2977 res.activityInfo = PackageParser.generateActivityInfo(activity,
2978 mFlags);
2979 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
2980 res.filter = info;
2981 }
2982 res.priority = info.getPriority();
2983 res.preferredOrder = activity.owner.mPreferredOrder;
2984 //System.out.println("Result: " + res.activityInfo.className +
2985 // " = " + res.priority);
2986 res.match = match;
2987 res.isDefault = info.hasDefault;
2988 res.labelRes = info.labelRes;
2989 res.nonLocalizedLabel = info.nonLocalizedLabel;
2990 res.icon = info.icon;
2991 return res;
2992 }
2993
2994 @Override
2995 protected void sortResults(List<ResolveInfo> results) {
2996 Collections.sort(results, mResolvePrioritySorter);
2997 }
2998
2999 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003000 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003002 out.print(prefix); out.print(
3003 Integer.toHexString(System.identityHashCode(filter.activity)));
3004 out.print(' ');
3005 out.println(filter.activity.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 }
3007
3008// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3009// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3010// final List<ResolveInfo> retList = Lists.newArrayList();
3011// while (i.hasNext()) {
3012// final ResolveInfo resolveInfo = i.next();
3013// if (isEnabledLP(resolveInfo.activityInfo)) {
3014// retList.add(resolveInfo);
3015// }
3016// }
3017// return retList;
3018// }
3019
3020 // Keys are String (activity class name), values are Activity.
3021 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3022 = new HashMap<ComponentName, PackageParser.Activity>();
3023 private int mFlags;
3024 }
3025
3026 private final class ServiceIntentResolver
3027 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003028 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003030 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
3032
Mihai Preda074edef2009-05-18 17:13:31 +02003033 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003035 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3037 }
3038
3039 public final void addService(PackageParser.Service s) {
3040 mServices.put(s.component, s);
3041 if (SHOW_INFO || Config.LOGV) Log.v(
3042 TAG, " " + (s.info.nonLocalizedLabel != null
3043 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3044 if (SHOW_INFO || Config.LOGV) Log.v(
3045 TAG, " Class=" + s.info.name);
3046 int NI = s.intents.size();
3047 int j;
3048 for (j=0; j<NI; j++) {
3049 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3050 if (SHOW_INFO || Config.LOGV) {
3051 Log.v(TAG, " IntentFilter:");
3052 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3053 }
3054 if (!intent.debugCheck()) {
3055 Log.w(TAG, "==> For Service " + s.info.name);
3056 }
3057 addFilter(intent);
3058 }
3059 }
3060
3061 public final void removeService(PackageParser.Service s) {
3062 mServices.remove(s.component);
3063 if (SHOW_INFO || Config.LOGV) Log.v(
3064 TAG, " " + (s.info.nonLocalizedLabel != null
3065 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3066 if (SHOW_INFO || Config.LOGV) Log.v(
3067 TAG, " Class=" + s.info.name);
3068 int NI = s.intents.size();
3069 int j;
3070 for (j=0; j<NI; j++) {
3071 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3072 if (SHOW_INFO || Config.LOGV) {
3073 Log.v(TAG, " IntentFilter:");
3074 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3075 }
3076 removeFilter(intent);
3077 }
3078 }
3079
3080 @Override
3081 protected boolean allowFilterResult(
3082 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3083 ServiceInfo filterSi = filter.service.info;
3084 for (int i=dest.size()-1; i>=0; i--) {
3085 ServiceInfo destAi = dest.get(i).serviceInfo;
3086 if (destAi.name == filterSi.name
3087 && destAi.packageName == filterSi.packageName) {
3088 return false;
3089 }
3090 }
3091 return true;
3092 }
3093
3094 @Override
3095 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
3096 int match) {
3097 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
3098 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
3099 return null;
3100 }
3101 final PackageParser.Service service = info.service;
3102 if (mSafeMode && (service.info.applicationInfo.flags
3103 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3104 return null;
3105 }
3106 final ResolveInfo res = new ResolveInfo();
3107 res.serviceInfo = PackageParser.generateServiceInfo(service,
3108 mFlags);
3109 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3110 res.filter = filter;
3111 }
3112 res.priority = info.getPriority();
3113 res.preferredOrder = service.owner.mPreferredOrder;
3114 //System.out.println("Result: " + res.activityInfo.className +
3115 // " = " + res.priority);
3116 res.match = match;
3117 res.isDefault = info.hasDefault;
3118 res.labelRes = info.labelRes;
3119 res.nonLocalizedLabel = info.nonLocalizedLabel;
3120 res.icon = info.icon;
3121 return res;
3122 }
3123
3124 @Override
3125 protected void sortResults(List<ResolveInfo> results) {
3126 Collections.sort(results, mResolvePrioritySorter);
3127 }
3128
3129 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003130 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003132 out.print(prefix); out.print(
3133 Integer.toHexString(System.identityHashCode(filter.service)));
3134 out.print(' ');
3135 out.println(filter.service.componentShortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 }
3137
3138// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3139// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3140// final List<ResolveInfo> retList = Lists.newArrayList();
3141// while (i.hasNext()) {
3142// final ResolveInfo resolveInfo = (ResolveInfo) i;
3143// if (isEnabledLP(resolveInfo.serviceInfo)) {
3144// retList.add(resolveInfo);
3145// }
3146// }
3147// return retList;
3148// }
3149
3150 // Keys are String (activity class name), values are Activity.
3151 private final HashMap<ComponentName, PackageParser.Service> mServices
3152 = new HashMap<ComponentName, PackageParser.Service>();
3153 private int mFlags;
3154 };
3155
3156 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
3157 new Comparator<ResolveInfo>() {
3158 public int compare(ResolveInfo r1, ResolveInfo r2) {
3159 int v1 = r1.priority;
3160 int v2 = r2.priority;
3161 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
3162 if (v1 != v2) {
3163 return (v1 > v2) ? -1 : 1;
3164 }
3165 v1 = r1.preferredOrder;
3166 v2 = r2.preferredOrder;
3167 if (v1 != v2) {
3168 return (v1 > v2) ? -1 : 1;
3169 }
3170 if (r1.isDefault != r2.isDefault) {
3171 return r1.isDefault ? -1 : 1;
3172 }
3173 v1 = r1.match;
3174 v2 = r2.match;
3175 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
3176 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3177 }
3178 };
3179
3180 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
3181 new Comparator<ProviderInfo>() {
3182 public int compare(ProviderInfo p1, ProviderInfo p2) {
3183 final int v1 = p1.initOrder;
3184 final int v2 = p2.initOrder;
3185 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
3186 }
3187 };
3188
3189 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
3190 IActivityManager am = ActivityManagerNative.getDefault();
3191 if (am != null) {
3192 try {
3193 final Intent intent = new Intent(action,
3194 pkg != null ? Uri.fromParts("package", pkg, null) : null);
3195 if (extras != null) {
3196 intent.putExtras(extras);
3197 }
3198 am.broadcastIntent(
3199 null, intent,
3200 null, null, 0, null, null, null, false, false);
3201 } catch (RemoteException ex) {
3202 }
3203 }
3204 }
3205
3206 private final class AppDirObserver extends FileObserver {
3207 public AppDirObserver(String path, int mask, boolean isrom) {
3208 super(path, mask);
3209 mRootDir = path;
3210 mIsRom = isrom;
3211 }
3212
3213 public void onEvent(int event, String path) {
3214 String removedPackage = null;
3215 int removedUid = -1;
3216 String addedPackage = null;
3217 int addedUid = -1;
3218
3219 synchronized (mInstallLock) {
3220 String fullPathStr = null;
3221 File fullPath = null;
3222 if (path != null) {
3223 fullPath = new File(mRootDir, path);
3224 fullPathStr = fullPath.getPath();
3225 }
3226
3227 if (Config.LOGV) Log.v(
3228 TAG, "File " + fullPathStr + " changed: "
3229 + Integer.toHexString(event));
3230
3231 if (!isPackageFilename(path)) {
3232 if (Config.LOGV) Log.v(
3233 TAG, "Ignoring change of non-package file: " + fullPathStr);
3234 return;
3235 }
3236
3237 if ((event&REMOVE_EVENTS) != 0) {
3238 synchronized (mInstallLock) {
3239 PackageParser.Package p = mAppDirs.get(fullPathStr);
3240 if (p != null) {
3241 removePackageLI(p, true);
3242 removedPackage = p.applicationInfo.packageName;
3243 removedUid = p.applicationInfo.uid;
3244 }
3245 }
3246 }
3247
3248 if ((event&ADD_EVENTS) != 0) {
3249 PackageParser.Package p = mAppDirs.get(fullPathStr);
3250 if (p == null) {
3251 p = scanPackageLI(fullPath, fullPath, fullPath,
3252 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
3253 PackageParser.PARSE_CHATTY |
3254 PackageParser.PARSE_MUST_BE_APK,
3255 SCAN_MONITOR);
3256 if (p != null) {
3257 synchronized (mPackages) {
3258 grantPermissionsLP(p, false);
3259 }
3260 addedPackage = p.applicationInfo.packageName;
3261 addedUid = p.applicationInfo.uid;
3262 }
3263 }
3264 }
3265
3266 synchronized (mPackages) {
3267 mSettings.writeLP();
3268 }
3269 }
3270
3271 if (removedPackage != null) {
3272 Bundle extras = new Bundle(1);
3273 extras.putInt(Intent.EXTRA_UID, removedUid);
3274 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
3275 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
3276 }
3277 if (addedPackage != null) {
3278 Bundle extras = new Bundle(1);
3279 extras.putInt(Intent.EXTRA_UID, addedUid);
3280 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
3281 }
3282 }
3283
3284 private final String mRootDir;
3285 private final boolean mIsRom;
3286 }
Jacek Surazskic64322c2009-04-28 15:26:38 +02003287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 /* Called when a downloaded package installation has been confirmed by the user */
3289 public void installPackage(
3290 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazskic64322c2009-04-28 15:26:38 +02003291 installPackage(packageURI, observer, flags, null);
3292 }
3293
3294 /* Called when a downloaded package installation has been confirmed by the user */
3295 public void installPackage(
3296 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
3297 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 mContext.enforceCallingOrSelfPermission(
3299 android.Manifest.permission.INSTALL_PACKAGES, null);
Jacek Surazskic64322c2009-04-28 15:26:38 +02003300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 // Queue up an async operation since the package installation may take a little while.
3302 mHandler.post(new Runnable() {
3303 public void run() {
3304 mHandler.removeCallbacks(this);
3305 PackageInstalledInfo res;
3306 synchronized (mInstallLock) {
Jacek Surazskic64322c2009-04-28 15:26:38 +02003307 res = installPackageLI(packageURI, flags, true, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 }
3309 if (observer != null) {
3310 try {
3311 observer.packageInstalled(res.name, res.returnCode);
3312 } catch (RemoteException e) {
3313 Log.i(TAG, "Observer no longer exists.");
3314 }
3315 }
3316 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
3317 // call appears in the synchronized block above.
3318 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3319 res.removedInfo.sendBroadcast(false, true);
3320 Bundle extras = new Bundle(1);
3321 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003322 final boolean update = res.removedInfo.removedPackage != null;
3323 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 extras.putBoolean(Intent.EXTRA_REPLACING, true);
3325 }
3326 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
3327 res.pkg.applicationInfo.packageName,
3328 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07003329 if (update) {
3330 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
3331 res.pkg.applicationInfo.packageName,
3332 extras);
3333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 }
3335 Runtime.getRuntime().gc();
3336 }
3337 });
3338 }
3339
3340 class PackageInstalledInfo {
3341 String name;
3342 int uid;
3343 PackageParser.Package pkg;
3344 int returnCode;
3345 PackageRemovedInfo removedInfo;
3346 }
3347
3348 /*
3349 * Install a non-existing package.
3350 */
3351 private void installNewPackageLI(String pkgName,
3352 File tmpPackageFile,
3353 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003354 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003355 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 // Remember this for later, in case we need to rollback this install
3357 boolean dataDirExists = (new File(mAppDataDir, pkgName)).exists();
3358 res.name = pkgName;
3359 synchronized(mPackages) {
3360 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(destFilePath)) {
3361 // Don't allow installation over an existing package with the same name.
3362 Log.w(TAG, "Attempt to re-install " + pkgName
3363 + " without first uninstalling.");
3364 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
3365 return;
3366 }
3367 }
3368 if (destPackageFile.exists()) {
3369 // It's safe to do this because we know (from the above check) that the file
3370 // isn't currently used for an installed package.
3371 destPackageFile.delete();
3372 }
3373 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3374 PackageParser.Package newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3375 destResourceFile, pkg, 0,
3376 SCAN_MONITOR | SCAN_FORCE_DEX
3377 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003378 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3379 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 if (newPackage == null) {
3381 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3382 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3383 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3384 }
3385 } else {
3386 updateSettingsLI(pkgName, tmpPackageFile,
3387 destFilePath, destPackageFile,
3388 destResourceFile, pkg,
3389 newPackage,
3390 true,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003391 forwardLocked,
3392 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 res);
3394 // delete the partially installed application. the data directory will have to be
3395 // restored if it was already existing
3396 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3397 // remove package from internal structures. Note that we want deletePackageX to
3398 // delete the package data and cache directories that it created in
3399 // scanPackageLocked, unless those directories existed before we even tried to
3400 // install.
3401 deletePackageLI(
3402 pkgName, true,
3403 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
3404 res.removedInfo);
3405 }
3406 }
3407 }
3408
3409 private void replacePackageLI(String pkgName,
3410 File tmpPackageFile,
3411 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003412 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003413 String installerPackageName, PackageInstalledInfo res) {
3414
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003415 PackageParser.Package oldPackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 // First find the old package info and check signatures
3417 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003418 oldPackage = mPackages.get(pkgName);
3419 if(checkSignaturesLP(pkg, oldPackage) != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3421 return;
3422 }
3423 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003424 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 if(sysPkg) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003426 replaceSystemPackageLI(oldPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003428 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003429 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 } else {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07003431 replaceNonSystemPackageLI(oldPackage, tmpPackageFile, destFilePath,
The Android Open Source Project10592532009-03-18 17:39:46 -07003432 destPackageFile, destResourceFile, pkg, forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003433 newInstall, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 }
3435 }
3436
3437 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
3438 File tmpPackageFile,
3439 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003440 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003441 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 PackageParser.Package newPackage = null;
3443 String pkgName = deletedPackage.packageName;
3444 boolean deletedPkg = true;
3445 boolean updatedSettings = false;
Jacek Surazskic64322c2009-04-28 15:26:38 +02003446
3447 String oldInstallerPackageName = null;
3448 synchronized (mPackages) {
3449 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
3450 }
3451
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003452 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 // First delete the existing package while retaining the data directory
3454 if (!deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA,
3455 res.removedInfo)) {
3456 // If the existing package was'nt successfully deleted
3457 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3458 deletedPkg = false;
3459 } else {
3460 // Successfully deleted the old package. Now proceed with re-installation
3461 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3462 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3463 destResourceFile, pkg, parseFlags,
3464 SCAN_MONITOR | SCAN_FORCE_DEX
3465 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003466 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3467 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468 if (newPackage == null) {
3469 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3470 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3471 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3472 }
3473 } else {
3474 updateSettingsLI(pkgName, tmpPackageFile,
3475 destFilePath, destPackageFile,
3476 destResourceFile, pkg,
3477 newPackage,
3478 true,
3479 forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003480 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 res);
3482 updatedSettings = true;
3483 }
3484 }
3485
3486 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3487 // If we deleted an exisiting package, the old source and resource files that we
3488 // were keeping around in case we needed them (see below) can now be deleted
3489 final ApplicationInfo deletedPackageAppInfo = deletedPackage.applicationInfo;
3490 final ApplicationInfo installedPackageAppInfo =
3491 newPackage.applicationInfo;
3492 if (!deletedPackageAppInfo.sourceDir
3493 .equals(installedPackageAppInfo.sourceDir)) {
3494 new File(deletedPackageAppInfo.sourceDir).delete();
3495 }
3496 if (!deletedPackageAppInfo.publicSourceDir
3497 .equals(installedPackageAppInfo.publicSourceDir)) {
3498 new File(deletedPackageAppInfo.publicSourceDir).delete();
3499 }
3500 //update signature on the new package setting
3501 //this should always succeed, since we checked the
3502 //signature earlier.
3503 synchronized(mPackages) {
3504 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
3505 parseFlags, true);
3506 }
3507 } else {
3508 // remove package from internal structures. Note that we want deletePackageX to
3509 // delete the package data and cache directories that it created in
3510 // scanPackageLocked, unless those directories existed before we even tried to
3511 // install.
3512 if(updatedSettings) {
3513 deletePackageLI(
3514 pkgName, true,
3515 PackageManager.DONT_DELETE_DATA,
3516 res.removedInfo);
3517 }
3518 // Since we failed to install the new package we need to restore the old
3519 // package that we deleted.
3520 if(deletedPkg) {
3521 installPackageLI(
3522 Uri.fromFile(new File(deletedPackage.mPath)),
3523 isForwardLocked(deletedPackage)
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003524 ? PackageManager.INSTALL_FORWARD_LOCK
Jacek Surazskic64322c2009-04-28 15:26:38 +02003525 : 0, false, oldInstallerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 }
3527 }
3528 }
3529
3530 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
3531 File tmpPackageFile,
3532 String destFilePath, File destPackageFile, File destResourceFile,
The Android Open Source Project10592532009-03-18 17:39:46 -07003533 PackageParser.Package pkg, boolean forwardLocked, boolean newInstall,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003534 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 PackageParser.Package newPackage = null;
3536 boolean updatedSettings = false;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003537 int parseFlags = PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 PackageParser.PARSE_IS_SYSTEM;
3539 String packageName = deletedPackage.packageName;
3540 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
3541 if (packageName == null) {
3542 Log.w(TAG, "Attempt to delete null packageName.");
3543 return;
3544 }
3545 PackageParser.Package oldPkg;
3546 PackageSetting oldPkgSetting;
3547 synchronized (mPackages) {
3548 oldPkg = mPackages.get(packageName);
3549 oldPkgSetting = mSettings.mPackages.get(packageName);
3550 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
3551 (oldPkgSetting == null)) {
3552 Log.w(TAG, "Could'nt find package:"+packageName+" information");
3553 return;
3554 }
3555 }
3556 res.removedInfo.uid = oldPkg.applicationInfo.uid;
3557 res.removedInfo.removedPackage = packageName;
3558 // Remove existing system package
3559 removePackageLI(oldPkg, true);
3560 synchronized (mPackages) {
3561 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
3562 }
3563
3564 // Successfully disabled the old package. Now proceed with re-installation
3565 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
3566 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3567 newPackage = scanPackageLI(tmpPackageFile, destPackageFile,
3568 destResourceFile, pkg, parseFlags,
3569 SCAN_MONITOR | SCAN_FORCE_DEX
3570 | SCAN_UPDATE_SIGNATURE
The Android Open Source Project10592532009-03-18 17:39:46 -07003571 | (forwardLocked ? SCAN_FORWARD_LOCKED : 0)
3572 | (newInstall ? SCAN_NEW_INSTALL : 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 if (newPackage == null) {
3574 Log.w(TAG, "Package couldn't be installed in " + destPackageFile);
3575 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
3576 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3577 }
3578 } else {
3579 updateSettingsLI(packageName, tmpPackageFile,
3580 destFilePath, destPackageFile,
3581 destResourceFile, pkg,
3582 newPackage,
3583 true,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003584 forwardLocked,
3585 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 res);
3587 updatedSettings = true;
3588 }
3589
3590 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
3591 //update signature on the new package setting
3592 //this should always succeed, since we checked the
3593 //signature earlier.
3594 synchronized(mPackages) {
3595 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
3596 parseFlags, true);
3597 }
3598 } else {
3599 // Re installation failed. Restore old information
3600 // Remove new pkg information
Dianne Hackborna96cbb42009-05-13 15:06:13 -07003601 if (newPackage != null) {
3602 removePackageLI(newPackage, true);
3603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 // Add back the old system package
3605 scanPackageLI(oldPkgSetting.codePath, oldPkgSetting.codePath,
3606 oldPkgSetting.resourcePath,
3607 oldPkg, parseFlags,
3608 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07003609 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 // Restore the old system information in Settings
3611 synchronized(mPackages) {
3612 if(updatedSettings) {
3613 mSettings.enableSystemPackageLP(packageName);
Jacek Surazskic64322c2009-04-28 15:26:38 +02003614 mSettings.setInstallerPackageName(packageName,
3615 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 }
3617 mSettings.writeLP();
3618 }
3619 }
3620 }
3621
3622 private void updateSettingsLI(String pkgName, File tmpPackageFile,
3623 String destFilePath, File destPackageFile,
3624 File destResourceFile,
3625 PackageParser.Package pkg,
3626 PackageParser.Package newPackage,
3627 boolean replacingExistingPackage,
3628 boolean forwardLocked,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003629 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630 synchronized (mPackages) {
3631 //write settings. the installStatus will be incomplete at this stage.
3632 //note that the new package setting would have already been
3633 //added to mPackages. It hasn't been persisted yet.
3634 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
3635 mSettings.writeLP();
3636 }
3637
3638 int retCode = 0;
3639 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
3640 retCode = mInstaller.movedex(tmpPackageFile.toString(),
3641 destPackageFile.toString());
3642 if (retCode != 0) {
3643 Log.e(TAG, "Couldn't rename dex file: " + destPackageFile);
3644 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3645 return;
3646 }
3647 }
3648 // XXX There are probably some big issues here: upon doing
3649 // the rename, we have reached the point of no return (the
3650 // original .apk is gone!), so we can't fail. Yet... we can.
3651 if (!tmpPackageFile.renameTo(destPackageFile)) {
3652 Log.e(TAG, "Couldn't move package file to: " + destPackageFile);
3653 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3654 } else {
3655 res.returnCode = setPermissionsLI(pkgName, newPackage, destFilePath,
3656 destResourceFile,
3657 forwardLocked);
3658 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3659 return;
3660 } else {
3661 Log.d(TAG, "New package installed in " + destPackageFile);
3662 }
3663 }
3664 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
3665 if (mInstaller != null) {
3666 mInstaller.rmdex(tmpPackageFile.getPath());
3667 }
3668 }
3669
3670 synchronized (mPackages) {
3671 grantPermissionsLP(newPackage, true);
3672 res.name = pkgName;
3673 res.uid = newPackage.applicationInfo.uid;
3674 res.pkg = newPackage;
3675 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazskic64322c2009-04-28 15:26:38 +02003676 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3678 //to update install status
3679 mSettings.writeLP();
3680 }
3681 }
3682
The Android Open Source Project10592532009-03-18 17:39:46 -07003683 private PackageInstalledInfo installPackageLI(Uri pPackageURI,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003684 int pFlags, boolean newInstall, String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 File tmpPackageFile = null;
3686 String pkgName = null;
3687 boolean forwardLocked = false;
3688 boolean replacingExistingPackage = false;
3689 // Result object to be returned
3690 PackageInstalledInfo res = new PackageInstalledInfo();
3691 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
3692 res.uid = -1;
3693 res.pkg = null;
3694 res.removedInfo = new PackageRemovedInfo();
3695
3696 main_flow: try {
3697 tmpPackageFile = createTempPackageFile();
3698 if (tmpPackageFile == null) {
3699 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3700 break main_flow;
3701 }
3702 tmpPackageFile.deleteOnExit(); // paranoia
3703 if (pPackageURI.getScheme().equals("file")) {
3704 final File srcPackageFile = new File(pPackageURI.getPath());
3705 // We copy the source package file to a temp file and then rename it to the
3706 // destination file in order to eliminate a window where the package directory
3707 // scanner notices the new package file but it's not completely copied yet.
3708 if (!FileUtils.copyFile(srcPackageFile, tmpPackageFile)) {
3709 Log.e(TAG, "Couldn't copy package file to temp file.");
3710 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3711 break main_flow;
3712 }
3713 } else if (pPackageURI.getScheme().equals("content")) {
3714 ParcelFileDescriptor fd;
3715 try {
3716 fd = mContext.getContentResolver().openFileDescriptor(pPackageURI, "r");
3717 } catch (FileNotFoundException e) {
3718 Log.e(TAG, "Couldn't open file descriptor from download service.");
3719 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3720 break main_flow;
3721 }
3722 if (fd == null) {
3723 Log.e(TAG, "Couldn't open file descriptor from download service (null).");
3724 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3725 break main_flow;
3726 }
3727 if (Config.LOGV) {
3728 Log.v(TAG, "Opened file descriptor from download service.");
3729 }
3730 ParcelFileDescriptor.AutoCloseInputStream
3731 dlStream = new ParcelFileDescriptor.AutoCloseInputStream(fd);
3732 // We copy the source package file to a temp file and then rename it to the
3733 // destination file in order to eliminate a window where the package directory
3734 // scanner notices the new package file but it's not completely copied yet.
3735 if (!FileUtils.copyToFile(dlStream, tmpPackageFile)) {
3736 Log.e(TAG, "Couldn't copy package stream to temp file.");
3737 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3738 break main_flow;
3739 }
3740 } else {
3741 Log.e(TAG, "Package URI is not 'file:' or 'content:' - " + pPackageURI);
3742 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_URI;
3743 break main_flow;
3744 }
3745 pkgName = PackageParser.parsePackageName(
3746 tmpPackageFile.getAbsolutePath(), 0);
3747 if (pkgName == null) {
3748 Log.e(TAG, "Couldn't find a package name in : " + tmpPackageFile);
3749 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
3750 break main_flow;
3751 }
3752 res.name = pkgName;
3753 //initialize some variables before installing pkg
3754 final String pkgFileName = pkgName + ".apk";
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003755 final File destDir = ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 ? mDrmAppPrivateInstallDir
3757 : mAppInstallDir;
3758 final File destPackageFile = new File(destDir, pkgFileName);
3759 final String destFilePath = destPackageFile.getAbsolutePath();
3760 File destResourceFile;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003761 if ((pFlags&PackageManager.INSTALL_FORWARD_LOCK) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 final String publicZipFileName = pkgName + ".zip";
3763 destResourceFile = new File(mAppInstallDir, publicZipFileName);
3764 forwardLocked = true;
3765 } else {
3766 destResourceFile = destPackageFile;
3767 }
3768 // Retrieve PackageSettings and parse package
3769 int parseFlags = PackageParser.PARSE_CHATTY;
3770 parseFlags |= mDefParseFlags;
3771 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
3772 pp.setSeparateProcesses(mSeparateProcesses);
Dianne Hackborn851a5412009-05-08 12:06:44 -07003773 pp.setSdkVersion(mSdkVersion, mSdkCodename);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003774 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
3775 destPackageFile.getAbsolutePath(), mMetrics, parseFlags);
3776 if (pkg == null) {
3777 res.returnCode = pp.getParseError();
3778 break main_flow;
3779 }
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003780 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
3781 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
3782 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
3783 break main_flow;
3784 }
3785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
3787 res.returnCode = pp.getParseError();
3788 break main_flow;
3789 }
3790
3791 synchronized (mPackages) {
3792 //check if installing already existing package
Dianne Hackbornade3eca2009-05-11 18:54:45 -07003793 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 && mPackages.containsKey(pkgName)) {
3795 replacingExistingPackage = true;
3796 }
3797 }
3798
3799 if(replacingExistingPackage) {
3800 replacePackageLI(pkgName,
3801 tmpPackageFile,
3802 destFilePath, destPackageFile, destResourceFile,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003803 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 res);
3805 } else {
3806 installNewPackageLI(pkgName,
3807 tmpPackageFile,
3808 destFilePath, destPackageFile, destResourceFile,
Jacek Surazskic64322c2009-04-28 15:26:38 +02003809 pkg, forwardLocked, newInstall, installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 res);
3811 }
3812 } finally {
3813 if (tmpPackageFile != null && tmpPackageFile.exists()) {
3814 tmpPackageFile.delete();
3815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003817 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818 }
3819
3820 private int setPermissionsLI(String pkgName,
3821 PackageParser.Package newPackage,
3822 String destFilePath,
3823 File destResourceFile,
3824 boolean forwardLocked) {
3825 int retCode;
3826 if (forwardLocked) {
3827 try {
3828 extractPublicFiles(newPackage, destResourceFile);
3829 } catch (IOException e) {
3830 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
3831 " forward-locked app.");
3832 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3833 } finally {
3834 //TODO clean up the extracted public files
3835 }
3836 if (mInstaller != null) {
3837 retCode = mInstaller.setForwardLockPerm(pkgName,
3838 newPackage.applicationInfo.uid);
3839 } else {
3840 final int filePermissions =
3841 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
3842 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1,
3843 newPackage.applicationInfo.uid);
3844 }
3845 } else {
3846 final int filePermissions =
3847 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
3848 |FileUtils.S_IROTH;
3849 retCode = FileUtils.setPermissions(destFilePath, filePermissions, -1, -1);
3850 }
3851 if (retCode != 0) {
3852 Log.e(TAG, "Couldn't set new package file permissions for " + destFilePath
3853 + ". The return code was: " + retCode);
3854 }
3855 return PackageManager.INSTALL_SUCCEEDED;
3856 }
3857
3858 private boolean isForwardLocked(PackageParser.Package deletedPackage) {
3859 final ApplicationInfo applicationInfo = deletedPackage.applicationInfo;
3860 return applicationInfo.sourceDir.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath());
3861 }
3862
3863 private void extractPublicFiles(PackageParser.Package newPackage,
3864 File publicZipFile) throws IOException {
3865 final ZipOutputStream publicZipOutStream =
3866 new ZipOutputStream(new FileOutputStream(publicZipFile));
3867 final ZipFile privateZip = new ZipFile(newPackage.mPath);
3868
3869 // Copy manifest, resources.arsc and res directory to public zip
3870
3871 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
3872 while (privateZipEntries.hasMoreElements()) {
3873 final ZipEntry zipEntry = privateZipEntries.nextElement();
3874 final String zipEntryName = zipEntry.getName();
3875 if ("AndroidManifest.xml".equals(zipEntryName)
3876 || "resources.arsc".equals(zipEntryName)
3877 || zipEntryName.startsWith("res/")) {
3878 try {
3879 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
3880 } catch (IOException e) {
3881 try {
3882 publicZipOutStream.close();
3883 throw e;
3884 } finally {
3885 publicZipFile.delete();
3886 }
3887 }
3888 }
3889 }
3890
3891 publicZipOutStream.close();
3892 FileUtils.setPermissions(
3893 publicZipFile.getAbsolutePath(),
3894 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
3895 -1, -1);
3896 }
3897
3898 private static void copyZipEntry(ZipEntry zipEntry,
3899 ZipFile inZipFile,
3900 ZipOutputStream outZipStream) throws IOException {
3901 byte[] buffer = new byte[4096];
3902 int num;
3903
3904 ZipEntry newEntry;
3905 if (zipEntry.getMethod() == ZipEntry.STORED) {
3906 // Preserve the STORED method of the input entry.
3907 newEntry = new ZipEntry(zipEntry);
3908 } else {
3909 // Create a new entry so that the compressed len is recomputed.
3910 newEntry = new ZipEntry(zipEntry.getName());
3911 }
3912 outZipStream.putNextEntry(newEntry);
3913
3914 InputStream data = inZipFile.getInputStream(zipEntry);
3915 while ((num = data.read(buffer)) > 0) {
3916 outZipStream.write(buffer, 0, num);
3917 }
3918 outZipStream.flush();
3919 }
3920
3921 private void deleteTempPackageFiles() {
3922 FilenameFilter filter = new FilenameFilter() {
3923 public boolean accept(File dir, String name) {
3924 return name.startsWith("vmdl") && name.endsWith(".tmp");
3925 }
3926 };
3927 String tmpFilesList[] = mAppInstallDir.list(filter);
3928 if(tmpFilesList == null) {
3929 return;
3930 }
3931 for(int i = 0; i < tmpFilesList.length; i++) {
3932 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
3933 tmpFile.delete();
3934 }
3935 }
3936
3937 private File createTempPackageFile() {
3938 File tmpPackageFile;
3939 try {
3940 tmpPackageFile = File.createTempFile("vmdl", ".tmp", mAppInstallDir);
3941 } catch (IOException e) {
3942 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
3943 return null;
3944 }
3945 try {
3946 FileUtils.setPermissions(
3947 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
3948 -1, -1);
3949 } catch (IOException e) {
3950 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
3951 return null;
3952 }
3953 return tmpPackageFile;
3954 }
3955
3956 public void deletePackage(final String packageName,
3957 final IPackageDeleteObserver observer,
3958 final int flags) {
3959 mContext.enforceCallingOrSelfPermission(
3960 android.Manifest.permission.DELETE_PACKAGES, null);
3961 // Queue up an async operation since the package deletion may take a little while.
3962 mHandler.post(new Runnable() {
3963 public void run() {
3964 mHandler.removeCallbacks(this);
3965 final boolean succeded = deletePackageX(packageName, true, true, flags);
3966 if (observer != null) {
3967 try {
3968 observer.packageDeleted(succeded);
3969 } catch (RemoteException e) {
3970 Log.i(TAG, "Observer no longer exists.");
3971 } //end catch
3972 } //end if
3973 } //end run
3974 });
3975 }
3976
3977 /**
3978 * This method is an internal method that could be get invoked either
3979 * to delete an installed package or to clean up a failed installation.
3980 * After deleting an installed package, a broadcast is sent to notify any
3981 * listeners that the package has been installed. For cleaning up a failed
3982 * installation, the broadcast is not necessary since the package's
3983 * installation wouldn't have sent the initial broadcast either
3984 * The key steps in deleting a package are
3985 * deleting the package information in internal structures like mPackages,
3986 * deleting the packages base directories through installd
3987 * updating mSettings to reflect current status
3988 * persisting settings for later use
3989 * sending a broadcast if necessary
3990 */
3991
3992 private boolean deletePackageX(String packageName, boolean sendBroadCast,
3993 boolean deleteCodeAndResources, int flags) {
3994 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07003995 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996
3997 synchronized (mInstallLock) {
3998 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
3999 }
4000
4001 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07004002 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
4003 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
4004
4005 // If the removed package was a system update, the old system packaged
4006 // was re-enabled; we need to broadcast this information
4007 if (systemUpdate) {
4008 Bundle extras = new Bundle(1);
4009 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
4010 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4011
4012 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
4013 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
4014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 }
4016 return res;
4017 }
4018
4019 static class PackageRemovedInfo {
4020 String removedPackage;
4021 int uid = -1;
4022 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07004023 boolean isRemovedPackageSystemUpdate = false;
4024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 void sendBroadcast(boolean fullRemove, boolean replacing) {
4026 Bundle extras = new Bundle(1);
4027 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
4028 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
4029 if (replacing) {
4030 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4031 }
4032 if (removedPackage != null) {
4033 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4034 }
4035 if (removedUid >= 0) {
4036 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
4037 }
4038 }
4039 }
4040
4041 /*
4042 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
4043 * flag is not set, the data directory is removed as well.
4044 * make sure this flag is set for partially installed apps. If not its meaningless to
4045 * delete a partially installed application.
4046 */
4047 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
4048 int flags) {
4049 String packageName = p.packageName;
4050 outInfo.removedPackage = packageName;
4051 removePackageLI(p, true);
4052 // Retrieve object to delete permissions for shared user later on
4053 PackageSetting deletedPs;
4054 synchronized (mPackages) {
4055 deletedPs = mSettings.mPackages.get(packageName);
4056 }
4057 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
4058 if (mInstaller != null) {
4059 int retCode = mInstaller.remove(packageName);
4060 if (retCode < 0) {
4061 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
4062 + packageName + ", retcode=" + retCode);
4063 // we don't consider this to be a failure of the core package deletion
4064 }
4065 } else {
4066 //for emulator
4067 PackageParser.Package pkg = mPackages.get(packageName);
4068 File dataDir = new File(pkg.applicationInfo.dataDir);
4069 dataDir.delete();
4070 }
4071 synchronized (mPackages) {
4072 outInfo.removedUid = mSettings.removePackageLP(packageName);
4073 }
4074 }
4075 synchronized (mPackages) {
4076 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
4077 // remove permissions associated with package
4078 mSettings.updateSharedUserPerms (deletedPs);
4079 }
4080 // Save settings now
4081 mSettings.writeLP ();
4082 }
4083 }
4084
4085 /*
4086 * Tries to delete system package.
4087 */
4088 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004089 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 ApplicationInfo applicationInfo = p.applicationInfo;
4091 //applicable for non-partially installed applications only
4092 if (applicationInfo == null) {
4093 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4094 return false;
4095 }
4096 PackageSetting ps = null;
4097 // Confirm if the system package has been updated
4098 // An updated system app can be deleted. This will also have to restore
4099 // the system pkg from system partition
4100 synchronized (mPackages) {
4101 ps = mSettings.getDisabledSystemPkg(p.packageName);
4102 }
4103 if (ps == null) {
4104 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
4105 return false;
4106 } else {
4107 Log.i(TAG, "Deleting system pkg from data partition");
4108 }
4109 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07004110 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004111 boolean deleteCodeAndResources = false;
4112 if (ps.versionCode < p.mVersionCode) {
4113 // Delete code and resources for downgrades
4114 deleteCodeAndResources = true;
4115 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4116 flags &= ~PackageManager.DONT_DELETE_DATA;
4117 }
4118 } else {
4119 // Preserve data by setting flag
4120 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
4121 flags |= PackageManager.DONT_DELETE_DATA;
4122 }
4123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
4125 if (!ret) {
4126 return false;
4127 }
4128 synchronized (mPackages) {
4129 // Reinstate the old system package
4130 mSettings.enableSystemPackageLP(p.packageName);
4131 }
4132 // Install the system package
4133 PackageParser.Package newPkg = scanPackageLI(ps.codePath, ps.codePath, ps.resourcePath,
4134 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
4135 SCAN_MONITOR);
4136
4137 if (newPkg == null) {
4138 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
4139 return false;
4140 }
4141 synchronized (mPackages) {
4142 mSettings.writeLP();
4143 }
4144 return true;
4145 }
4146
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004147 private void deletePackageResourcesLI(String packageName,
4148 String sourceDir, String publicSourceDir) {
4149 File sourceFile = new File(sourceDir);
4150 if (!sourceFile.exists()) {
4151 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4152 }
4153 // Delete application's code and resources
4154 sourceFile.delete();
4155 final File publicSourceFile = new File(publicSourceDir);
4156 if (publicSourceFile.exists()) {
4157 publicSourceFile.delete();
4158 }
4159 if (mInstaller != null) {
4160 int retCode = mInstaller.rmdex(sourceFile.toString());
4161 if (retCode < 0) {
4162 Log.w(TAG, "Couldn't remove dex file for package: "
4163 + packageName + " at location " + sourceFile.toString() + ", retcode=" + retCode);
4164 // we don't consider this to be a failure of the core package deletion
4165 }
4166 }
4167 }
4168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 private boolean deleteInstalledPackageLI(PackageParser.Package p,
4170 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4171 ApplicationInfo applicationInfo = p.applicationInfo;
4172 if (applicationInfo == null) {
4173 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4174 return false;
4175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 outInfo.uid = applicationInfo.uid;
4177
4178 // Delete package data from internal structures and also remove data if flag is set
4179 removePackageDataLI(p, outInfo, flags);
4180
4181 // Delete application code and resources
4182 if (deleteCodeAndResources) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004183 deletePackageResourcesLI(applicationInfo.packageName,
4184 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 }
4186 return true;
4187 }
4188
4189 /*
4190 * This method handles package deletion in general
4191 */
4192 private boolean deletePackageLI(String packageName,
4193 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
4194 if (packageName == null) {
4195 Log.w(TAG, "Attempt to delete null packageName.");
4196 return false;
4197 }
4198 PackageParser.Package p;
4199 boolean dataOnly = false;
4200 synchronized (mPackages) {
4201 p = mPackages.get(packageName);
4202 if (p == null) {
4203 //this retrieves partially installed apps
4204 dataOnly = true;
4205 PackageSetting ps = mSettings.mPackages.get(packageName);
4206 if (ps == null) {
4207 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4208 return false;
4209 }
4210 p = ps.pkg;
4211 }
4212 }
4213 if (p == null) {
4214 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4215 return false;
4216 }
4217
4218 if (dataOnly) {
4219 // Delete application data first
4220 removePackageDataLI(p, outInfo, flags);
4221 return true;
4222 }
4223 // At this point the package should have ApplicationInfo associated with it
4224 if (p.applicationInfo == null) {
4225 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
4226 return false;
4227 }
4228 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4229 Log.i(TAG, "Removing system package:"+p.packageName);
4230 // When an updated system application is deleted we delete the existing resources as well and
4231 // fall back to existing code in system partition
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004232 return deleteSystemPackageLI(p, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 }
4234 Log.i(TAG, "Removing non-system package:"+p.packageName);
4235 return deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
4236 }
4237
4238 public void clearApplicationUserData(final String packageName,
4239 final IPackageDataObserver observer) {
4240 mContext.enforceCallingOrSelfPermission(
4241 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
4242 // Queue up an async operation since the package deletion may take a little while.
4243 mHandler.post(new Runnable() {
4244 public void run() {
4245 mHandler.removeCallbacks(this);
4246 final boolean succeeded;
4247 synchronized (mInstallLock) {
4248 succeeded = clearApplicationUserDataLI(packageName);
4249 }
4250 if (succeeded) {
4251 // invoke DeviceStorageMonitor's update method to clear any notifications
4252 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
4253 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
4254 if (dsm != null) {
4255 dsm.updateMemory();
4256 }
4257 }
4258 if(observer != null) {
4259 try {
4260 observer.onRemoveCompleted(packageName, succeeded);
4261 } catch (RemoteException e) {
4262 Log.i(TAG, "Observer no longer exists.");
4263 }
4264 } //end if observer
4265 } //end run
4266 });
4267 }
4268
4269 private boolean clearApplicationUserDataLI(String packageName) {
4270 if (packageName == null) {
4271 Log.w(TAG, "Attempt to delete null packageName.");
4272 return false;
4273 }
4274 PackageParser.Package p;
4275 boolean dataOnly = false;
4276 synchronized (mPackages) {
4277 p = mPackages.get(packageName);
4278 if(p == null) {
4279 dataOnly = true;
4280 PackageSetting ps = mSettings.mPackages.get(packageName);
4281 if((ps == null) || (ps.pkg == null)) {
4282 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4283 return false;
4284 }
4285 p = ps.pkg;
4286 }
4287 }
4288 if(!dataOnly) {
4289 //need to check this only for fully installed applications
4290 if (p == null) {
4291 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4292 return false;
4293 }
4294 final ApplicationInfo applicationInfo = p.applicationInfo;
4295 if (applicationInfo == null) {
4296 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4297 return false;
4298 }
4299 }
4300 if (mInstaller != null) {
4301 int retCode = mInstaller.clearUserData(packageName);
4302 if (retCode < 0) {
4303 Log.w(TAG, "Couldn't remove cache files for package: "
4304 + packageName);
4305 return false;
4306 }
4307 }
4308 return true;
4309 }
4310
4311 public void deleteApplicationCacheFiles(final String packageName,
4312 final IPackageDataObserver observer) {
4313 mContext.enforceCallingOrSelfPermission(
4314 android.Manifest.permission.DELETE_CACHE_FILES, null);
4315 // Queue up an async operation since the package deletion may take a little while.
4316 mHandler.post(new Runnable() {
4317 public void run() {
4318 mHandler.removeCallbacks(this);
4319 final boolean succeded;
4320 synchronized (mInstallLock) {
4321 succeded = deleteApplicationCacheFilesLI(packageName);
4322 }
4323 if(observer != null) {
4324 try {
4325 observer.onRemoveCompleted(packageName, succeded);
4326 } catch (RemoteException e) {
4327 Log.i(TAG, "Observer no longer exists.");
4328 }
4329 } //end if observer
4330 } //end run
4331 });
4332 }
4333
4334 private boolean deleteApplicationCacheFilesLI(String packageName) {
4335 if (packageName == null) {
4336 Log.w(TAG, "Attempt to delete null packageName.");
4337 return false;
4338 }
4339 PackageParser.Package p;
4340 synchronized (mPackages) {
4341 p = mPackages.get(packageName);
4342 }
4343 if (p == null) {
4344 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4345 return false;
4346 }
4347 final ApplicationInfo applicationInfo = p.applicationInfo;
4348 if (applicationInfo == null) {
4349 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4350 return false;
4351 }
4352 if (mInstaller != null) {
4353 int retCode = mInstaller.deleteCacheFiles(packageName);
4354 if (retCode < 0) {
4355 Log.w(TAG, "Couldn't remove cache files for package: "
4356 + packageName);
4357 return false;
4358 }
4359 }
4360 return true;
4361 }
4362
4363 public void getPackageSizeInfo(final String packageName,
4364 final IPackageStatsObserver observer) {
4365 mContext.enforceCallingOrSelfPermission(
4366 android.Manifest.permission.GET_PACKAGE_SIZE, null);
4367 // Queue up an async operation since the package deletion may take a little while.
4368 mHandler.post(new Runnable() {
4369 public void run() {
4370 mHandler.removeCallbacks(this);
4371 PackageStats lStats = new PackageStats(packageName);
4372 final boolean succeded;
4373 synchronized (mInstallLock) {
4374 succeded = getPackageSizeInfoLI(packageName, lStats);
4375 }
4376 if(observer != null) {
4377 try {
4378 observer.onGetStatsCompleted(lStats, succeded);
4379 } catch (RemoteException e) {
4380 Log.i(TAG, "Observer no longer exists.");
4381 }
4382 } //end if observer
4383 } //end run
4384 });
4385 }
4386
4387 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
4388 if (packageName == null) {
4389 Log.w(TAG, "Attempt to get size of null packageName.");
4390 return false;
4391 }
4392 PackageParser.Package p;
4393 boolean dataOnly = false;
4394 synchronized (mPackages) {
4395 p = mPackages.get(packageName);
4396 if(p == null) {
4397 dataOnly = true;
4398 PackageSetting ps = mSettings.mPackages.get(packageName);
4399 if((ps == null) || (ps.pkg == null)) {
4400 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
4401 return false;
4402 }
4403 p = ps.pkg;
4404 }
4405 }
4406 String publicSrcDir = null;
4407 if(!dataOnly) {
4408 final ApplicationInfo applicationInfo = p.applicationInfo;
4409 if (applicationInfo == null) {
4410 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
4411 return false;
4412 }
4413 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
4414 }
4415 if (mInstaller != null) {
4416 int res = mInstaller.getSizeInfo(packageName, p.mPath,
4417 publicSrcDir, pStats);
4418 if (res < 0) {
4419 return false;
4420 } else {
4421 return true;
4422 }
4423 }
4424 return true;
4425 }
4426
4427
4428 public void addPackageToPreferred(String packageName) {
4429 mContext.enforceCallingOrSelfPermission(
4430 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4431
4432 synchronized (mPackages) {
4433 PackageParser.Package p = mPackages.get(packageName);
4434 if (p == null) {
4435 return;
4436 }
4437 PackageSetting ps = (PackageSetting)p.mExtras;
4438 if (ps != null) {
4439 mSettings.mPreferredPackages.remove(ps);
4440 mSettings.mPreferredPackages.add(0, ps);
4441 updatePreferredIndicesLP();
4442 mSettings.writeLP();
4443 }
4444 }
4445 }
4446
4447 public void removePackageFromPreferred(String packageName) {
4448 mContext.enforceCallingOrSelfPermission(
4449 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4450
4451 synchronized (mPackages) {
4452 PackageParser.Package p = mPackages.get(packageName);
4453 if (p == null) {
4454 return;
4455 }
4456 if (p.mPreferredOrder > 0) {
4457 PackageSetting ps = (PackageSetting)p.mExtras;
4458 if (ps != null) {
4459 mSettings.mPreferredPackages.remove(ps);
4460 p.mPreferredOrder = 0;
4461 updatePreferredIndicesLP();
4462 mSettings.writeLP();
4463 }
4464 }
4465 }
4466 }
4467
4468 private void updatePreferredIndicesLP() {
4469 final ArrayList<PackageSetting> pkgs
4470 = mSettings.mPreferredPackages;
4471 final int N = pkgs.size();
4472 for (int i=0; i<N; i++) {
4473 pkgs.get(i).pkg.mPreferredOrder = N - i;
4474 }
4475 }
4476
4477 public List<PackageInfo> getPreferredPackages(int flags) {
4478 synchronized (mPackages) {
4479 final ArrayList<PackageInfo> res = new ArrayList<PackageInfo>();
4480 final ArrayList<PackageSetting> pref = mSettings.mPreferredPackages;
4481 final int N = pref.size();
4482 for (int i=0; i<N; i++) {
4483 res.add(generatePackageInfo(pref.get(i).pkg, flags));
4484 }
4485 return res;
4486 }
4487 }
4488
4489 public void addPreferredActivity(IntentFilter filter, int match,
4490 ComponentName[] set, ComponentName activity) {
4491 mContext.enforceCallingOrSelfPermission(
4492 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4493
4494 synchronized (mPackages) {
4495 Log.i(TAG, "Adding preferred activity " + activity + ":");
4496 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
4497 mSettings.mPreferredActivities.addFilter(
4498 new PreferredActivity(filter, match, set, activity));
4499 mSettings.writeLP();
4500 }
4501 }
4502
4503 public void clearPackagePreferredActivities(String packageName) {
4504 mContext.enforceCallingOrSelfPermission(
4505 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
4506
4507 synchronized (mPackages) {
4508 if (clearPackagePreferredActivitiesLP(packageName)) {
4509 mSettings.writeLP();
4510 }
4511 }
4512 }
4513
4514 boolean clearPackagePreferredActivitiesLP(String packageName) {
4515 boolean changed = false;
4516 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4517 while (it.hasNext()) {
4518 PreferredActivity pa = it.next();
4519 if (pa.mActivity.getPackageName().equals(packageName)) {
4520 it.remove();
4521 changed = true;
4522 }
4523 }
4524 return changed;
4525 }
4526
4527 public int getPreferredActivities(List<IntentFilter> outFilters,
4528 List<ComponentName> outActivities, String packageName) {
4529
4530 int num = 0;
4531 synchronized (mPackages) {
4532 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
4533 while (it.hasNext()) {
4534 PreferredActivity pa = it.next();
4535 if (packageName == null
4536 || pa.mActivity.getPackageName().equals(packageName)) {
4537 if (outFilters != null) {
4538 outFilters.add(new IntentFilter(pa));
4539 }
4540 if (outActivities != null) {
4541 outActivities.add(pa.mActivity);
4542 }
4543 }
4544 }
4545 }
4546
4547 return num;
4548 }
4549
4550 public void setApplicationEnabledSetting(String appPackageName,
4551 int newState, int flags) {
4552 setEnabledSetting(appPackageName, null, newState, flags);
4553 }
4554
4555 public void setComponentEnabledSetting(ComponentName componentName,
4556 int newState, int flags) {
4557 setEnabledSetting(componentName.getPackageName(),
4558 componentName.getClassName(), newState, flags);
4559 }
4560
4561 private void setEnabledSetting(
4562 final String packageNameStr, String classNameStr, int newState, final int flags) {
4563 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
4564 || newState == COMPONENT_ENABLED_STATE_ENABLED
4565 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
4566 throw new IllegalArgumentException("Invalid new component state: "
4567 + newState);
4568 }
4569 PackageSetting pkgSetting;
4570 final int uid = Binder.getCallingUid();
4571 final int permission = mContext.checkCallingPermission(
4572 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
4573 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4574 int packageUid = -1;
4575 synchronized (mPackages) {
4576 pkgSetting = mSettings.mPackages.get(packageNameStr);
4577 if (pkgSetting == null) {
4578 if (classNameStr == null) {
4579 throw new IllegalArgumentException(
4580 "Unknown package: " + packageNameStr);
4581 }
4582 throw new IllegalArgumentException(
4583 "Unknown component: " + packageNameStr
4584 + "/" + classNameStr);
4585 }
4586 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4587 throw new SecurityException(
4588 "Permission Denial: attempt to change component state from pid="
4589 + Binder.getCallingPid()
4590 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
4591 }
4592 packageUid = pkgSetting.userId;
4593 if (classNameStr == null) {
4594 // We're dealing with an application/package level state change
4595 pkgSetting.enabled = newState;
4596 } else {
4597 // We're dealing with a component level state change
4598 switch (newState) {
4599 case COMPONENT_ENABLED_STATE_ENABLED:
4600 pkgSetting.enableComponentLP(classNameStr);
4601 break;
4602 case COMPONENT_ENABLED_STATE_DISABLED:
4603 pkgSetting.disableComponentLP(classNameStr);
4604 break;
4605 case COMPONENT_ENABLED_STATE_DEFAULT:
4606 pkgSetting.restoreComponentLP(classNameStr);
4607 break;
4608 default:
4609 Log.e(TAG, "Invalid new component state: " + newState);
4610 }
4611 }
4612 mSettings.writeLP();
4613 }
4614
4615 long callingId = Binder.clearCallingIdentity();
4616 try {
4617 Bundle extras = new Bundle(2);
4618 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP,
4619 (flags&PackageManager.DONT_KILL_APP) != 0);
4620 extras.putInt(Intent.EXTRA_UID, packageUid);
4621 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageNameStr, extras);
4622 } finally {
4623 Binder.restoreCallingIdentity(callingId);
4624 }
4625 }
4626
Jacek Surazskic64322c2009-04-28 15:26:38 +02004627 public String getInstallerPackageName(String packageName) {
4628 synchronized (mPackages) {
4629 PackageSetting pkg = mSettings.mPackages.get(packageName);
4630 if (pkg == null) {
4631 throw new IllegalArgumentException("Unknown package: " + packageName);
4632 }
4633 return pkg.installerPackageName;
4634 }
4635 }
4636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 public int getApplicationEnabledSetting(String appPackageName) {
4638 synchronized (mPackages) {
4639 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
4640 if (pkg == null) {
4641 throw new IllegalArgumentException("Unknown package: " + appPackageName);
4642 }
4643 return pkg.enabled;
4644 }
4645 }
4646
4647 public int getComponentEnabledSetting(ComponentName componentName) {
4648 synchronized (mPackages) {
4649 final String packageNameStr = componentName.getPackageName();
4650 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
4651 if (pkg == null) {
4652 throw new IllegalArgumentException("Unknown component: " + componentName);
4653 }
4654 final String classNameStr = componentName.getClassName();
4655 return pkg.currentEnabledStateLP(classNameStr);
4656 }
4657 }
4658
4659 public void enterSafeMode() {
4660 if (!mSystemReady) {
4661 mSafeMode = true;
4662 }
4663 }
4664
4665 public void systemReady() {
4666 mSystemReady = true;
4667 }
4668
4669 public boolean isSafeMode() {
4670 return mSafeMode;
4671 }
4672
4673 public boolean hasSystemUidErrors() {
4674 return mHasSystemUidErrors;
4675 }
4676
4677 static String arrayToString(int[] array) {
4678 StringBuffer buf = new StringBuffer(128);
4679 buf.append('[');
4680 if (array != null) {
4681 for (int i=0; i<array.length; i++) {
4682 if (i > 0) buf.append(", ");
4683 buf.append(array[i]);
4684 }
4685 }
4686 buf.append(']');
4687 return buf.toString();
4688 }
4689
4690 @Override
4691 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
4692 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4693 != PackageManager.PERMISSION_GRANTED) {
4694 pw.println("Permission Denial: can't dump ActivityManager from from pid="
4695 + Binder.getCallingPid()
4696 + ", uid=" + Binder.getCallingUid()
4697 + " without permission "
4698 + android.Manifest.permission.DUMP);
4699 return;
4700 }
4701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 synchronized (mPackages) {
4703 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004704 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 pw.println(" ");
4706 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004707 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004708 pw.println(" ");
4709 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004710 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711 pw.println(" ");
4712 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004713 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004714 pw.println(" ");
4715 pw.println("Preferred Packages:");
4716 {
4717 for (PackageSetting ps : mSettings.mPreferredPackages) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004718 pw.print(" "); pw.println(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 }
4720 }
4721 pw.println(" ");
4722 pw.println("Permissions:");
4723 {
4724 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004725 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
4726 pw.print(Integer.toHexString(System.identityHashCode(p)));
4727 pw.println("):");
4728 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
4729 pw.print(" uid="); pw.print(p.uid);
4730 pw.print(" gids="); pw.print(arrayToString(p.gids));
4731 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004732 }
4733 }
4734 pw.println(" ");
4735 pw.println("Packages:");
4736 {
4737 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004738 pw.print(" Package ["); pw.print(ps.name); pw.print("] (");
4739 pw.print(Integer.toHexString(System.identityHashCode(ps)));
4740 pw.println("):");
4741 pw.print(" userId="); pw.print(ps.userId);
4742 pw.print(" gids="); pw.println(arrayToString(ps.gids));
4743 pw.print(" sharedUser="); pw.println(ps.sharedUser);
4744 pw.print(" pkg="); pw.println(ps.pkg);
4745 pw.print(" codePath="); pw.println(ps.codePathString);
4746 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004747 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004748 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004749 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004750 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
4751 pw.print(" signatures="); pw.println(ps.signatures);
4752 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
4753 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
4754 pw.print(" installStatus="); pw.print(ps.installStatus);
4755 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004756 if (ps.disabledComponents.size() > 0) {
4757 pw.println(" disabledComponents:");
4758 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004759 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 }
4761 }
4762 if (ps.enabledComponents.size() > 0) {
4763 pw.println(" enabledComponents:");
4764 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004765 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 }
4767 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004768 if (ps.grantedPermissions.size() > 0) {
4769 pw.println(" grantedPermissions:");
4770 for (String s : ps.grantedPermissions) {
4771 pw.print(" "); pw.println(s);
4772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004773 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004774 if (ps.loadedPermissions.size() > 0) {
4775 pw.println(" loadedPermissions:");
4776 for (String s : ps.loadedPermissions) {
4777 pw.print(" "); pw.println(s);
4778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004779 }
4780 }
4781 }
4782 pw.println(" ");
4783 pw.println("Shared Users:");
4784 {
4785 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004786 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
4787 pw.print(Integer.toHexString(System.identityHashCode(su)));
4788 pw.println("):");
4789 pw.print(" userId="); pw.print(su.userId);
4790 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004791 pw.println(" grantedPermissions:");
4792 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004793 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004794 }
4795 pw.println(" loadedPermissions:");
4796 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004797 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004798 }
4799 }
4800 }
4801 pw.println(" ");
4802 pw.println("Settings parse messages:");
4803 pw.println(mSettings.mReadMessages.toString());
4804 }
4805 }
4806
4807 static final class BasePermission {
4808 final static int TYPE_NORMAL = 0;
4809 final static int TYPE_BUILTIN = 1;
4810 final static int TYPE_DYNAMIC = 2;
4811
4812 final String name;
4813 final String sourcePackage;
4814 final int type;
4815 PackageParser.Permission perm;
4816 PermissionInfo pendingInfo;
4817 int uid;
4818 int[] gids;
4819
4820 BasePermission(String _name, String _sourcePackage, int _type) {
4821 name = _name;
4822 sourcePackage = _sourcePackage;
4823 type = _type;
4824 }
4825 }
4826
4827 static class PackageSignatures {
4828 private Signature[] mSignatures;
4829
4830 PackageSignatures(Signature[] sigs) {
4831 assignSignatures(sigs);
4832 }
4833
4834 PackageSignatures() {
4835 }
4836
4837 void writeXml(XmlSerializer serializer, String tagName,
4838 ArrayList<Signature> pastSignatures) throws IOException {
4839 if (mSignatures == null) {
4840 return;
4841 }
4842 serializer.startTag(null, tagName);
4843 serializer.attribute(null, "count",
4844 Integer.toString(mSignatures.length));
4845 for (int i=0; i<mSignatures.length; i++) {
4846 serializer.startTag(null, "cert");
4847 final Signature sig = mSignatures[i];
4848 final int sigHash = sig.hashCode();
4849 final int numPast = pastSignatures.size();
4850 int j;
4851 for (j=0; j<numPast; j++) {
4852 Signature pastSig = pastSignatures.get(j);
4853 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
4854 serializer.attribute(null, "index", Integer.toString(j));
4855 break;
4856 }
4857 }
4858 if (j >= numPast) {
4859 pastSignatures.add(sig);
4860 serializer.attribute(null, "index", Integer.toString(numPast));
4861 serializer.attribute(null, "key", sig.toCharsString());
4862 }
4863 serializer.endTag(null, "cert");
4864 }
4865 serializer.endTag(null, tagName);
4866 }
4867
4868 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
4869 throws IOException, XmlPullParserException {
4870 String countStr = parser.getAttributeValue(null, "count");
4871 if (countStr == null) {
4872 reportSettingsProblem(Log.WARN,
4873 "Error in package manager settings: <signatures> has"
4874 + " no count at " + parser.getPositionDescription());
4875 XmlUtils.skipCurrentTag(parser);
4876 }
4877 final int count = Integer.parseInt(countStr);
4878 mSignatures = new Signature[count];
4879 int pos = 0;
4880
4881 int outerDepth = parser.getDepth();
4882 int type;
4883 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
4884 && (type != XmlPullParser.END_TAG
4885 || parser.getDepth() > outerDepth)) {
4886 if (type == XmlPullParser.END_TAG
4887 || type == XmlPullParser.TEXT) {
4888 continue;
4889 }
4890
4891 String tagName = parser.getName();
4892 if (tagName.equals("cert")) {
4893 if (pos < count) {
4894 String index = parser.getAttributeValue(null, "index");
4895 if (index != null) {
4896 try {
4897 int idx = Integer.parseInt(index);
4898 String key = parser.getAttributeValue(null, "key");
4899 if (key == null) {
4900 if (idx >= 0 && idx < pastSignatures.size()) {
4901 Signature sig = pastSignatures.get(idx);
4902 if (sig != null) {
4903 mSignatures[pos] = pastSignatures.get(idx);
4904 pos++;
4905 } else {
4906 reportSettingsProblem(Log.WARN,
4907 "Error in package manager settings: <cert> "
4908 + "index " + index + " is not defined at "
4909 + parser.getPositionDescription());
4910 }
4911 } else {
4912 reportSettingsProblem(Log.WARN,
4913 "Error in package manager settings: <cert> "
4914 + "index " + index + " is out of bounds at "
4915 + parser.getPositionDescription());
4916 }
4917 } else {
4918 while (pastSignatures.size() <= idx) {
4919 pastSignatures.add(null);
4920 }
4921 Signature sig = new Signature(key);
4922 pastSignatures.set(idx, sig);
4923 mSignatures[pos] = sig;
4924 pos++;
4925 }
4926 } catch (NumberFormatException e) {
4927 reportSettingsProblem(Log.WARN,
4928 "Error in package manager settings: <cert> "
4929 + "index " + index + " is not a number at "
4930 + parser.getPositionDescription());
4931 }
4932 } else {
4933 reportSettingsProblem(Log.WARN,
4934 "Error in package manager settings: <cert> has"
4935 + " no index at " + parser.getPositionDescription());
4936 }
4937 } else {
4938 reportSettingsProblem(Log.WARN,
4939 "Error in package manager settings: too "
4940 + "many <cert> tags, expected " + count
4941 + " at " + parser.getPositionDescription());
4942 }
4943 } else {
4944 reportSettingsProblem(Log.WARN,
4945 "Unknown element under <cert>: "
4946 + parser.getName());
4947 }
4948 XmlUtils.skipCurrentTag(parser);
4949 }
4950
4951 if (pos < count) {
4952 // Should never happen -- there is an error in the written
4953 // settings -- but if it does we don't want to generate
4954 // a bad array.
4955 Signature[] newSigs = new Signature[pos];
4956 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
4957 mSignatures = newSigs;
4958 }
4959 }
4960
4961 /**
4962 * If any of the given 'sigs' is contained in the existing signatures,
4963 * then completely replace the current signatures with the ones in
4964 * 'sigs'. This is used for updating an existing package to a newly
4965 * installed version.
4966 */
4967 boolean updateSignatures(Signature[] sigs, boolean update) {
4968 if (mSignatures == null) {
4969 if (update) {
4970 assignSignatures(sigs);
4971 }
4972 return true;
4973 }
4974 if (sigs == null) {
4975 return false;
4976 }
4977
4978 for (int i=0; i<sigs.length; i++) {
4979 Signature sig = sigs[i];
4980 for (int j=0; j<mSignatures.length; j++) {
4981 if (mSignatures[j].equals(sig)) {
4982 if (update) {
4983 assignSignatures(sigs);
4984 }
4985 return true;
4986 }
4987 }
4988 }
4989 return false;
4990 }
4991
4992 /**
4993 * If any of the given 'sigs' is contained in the existing signatures,
4994 * then add in any new signatures found in 'sigs'. This is used for
4995 * including a new package into an existing shared user id.
4996 */
4997 boolean mergeSignatures(Signature[] sigs, boolean update) {
4998 if (mSignatures == null) {
4999 if (update) {
5000 assignSignatures(sigs);
5001 }
5002 return true;
5003 }
5004 if (sigs == null) {
5005 return false;
5006 }
5007
5008 Signature[] added = null;
5009 int addedCount = 0;
5010 boolean haveMatch = false;
5011 for (int i=0; i<sigs.length; i++) {
5012 Signature sig = sigs[i];
5013 boolean found = false;
5014 for (int j=0; j<mSignatures.length; j++) {
5015 if (mSignatures[j].equals(sig)) {
5016 found = true;
5017 haveMatch = true;
5018 break;
5019 }
5020 }
5021
5022 if (!found) {
5023 if (added == null) {
5024 added = new Signature[sigs.length];
5025 }
5026 added[i] = sig;
5027 addedCount++;
5028 }
5029 }
5030
5031 if (!haveMatch) {
5032 // Nothing matched -- reject the new signatures.
5033 return false;
5034 }
5035 if (added == null) {
5036 // Completely matched -- nothing else to do.
5037 return true;
5038 }
5039
5040 // Add additional signatures in.
5041 if (update) {
5042 Signature[] total = new Signature[addedCount+mSignatures.length];
5043 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
5044 int j = mSignatures.length;
5045 for (int i=0; i<added.length; i++) {
5046 if (added[i] != null) {
5047 total[j] = added[i];
5048 j++;
5049 }
5050 }
5051 mSignatures = total;
5052 }
5053 return true;
5054 }
5055
5056 private void assignSignatures(Signature[] sigs) {
5057 if (sigs == null) {
5058 mSignatures = null;
5059 return;
5060 }
5061 mSignatures = new Signature[sigs.length];
5062 for (int i=0; i<sigs.length; i++) {
5063 mSignatures[i] = sigs[i];
5064 }
5065 }
5066
5067 @Override
5068 public String toString() {
5069 StringBuffer buf = new StringBuffer(128);
5070 buf.append("PackageSignatures{");
5071 buf.append(Integer.toHexString(System.identityHashCode(this)));
5072 buf.append(" [");
5073 if (mSignatures != null) {
5074 for (int i=0; i<mSignatures.length; i++) {
5075 if (i > 0) buf.append(", ");
5076 buf.append(Integer.toHexString(
5077 System.identityHashCode(mSignatures[i])));
5078 }
5079 }
5080 buf.append("]}");
5081 return buf.toString();
5082 }
5083 }
5084
5085 static class PreferredActivity extends IntentFilter {
5086 final int mMatch;
5087 final String[] mSetPackages;
5088 final String[] mSetClasses;
5089 final String[] mSetComponents;
5090 final ComponentName mActivity;
5091 final String mShortActivity;
5092 String mParseError;
5093
5094 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
5095 ComponentName activity) {
5096 super(filter);
5097 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
5098 mActivity = activity;
5099 mShortActivity = activity.flattenToShortString();
5100 mParseError = null;
5101 if (set != null) {
5102 final int N = set.length;
5103 String[] myPackages = new String[N];
5104 String[] myClasses = new String[N];
5105 String[] myComponents = new String[N];
5106 for (int i=0; i<N; i++) {
5107 ComponentName cn = set[i];
5108 if (cn == null) {
5109 mSetPackages = null;
5110 mSetClasses = null;
5111 mSetComponents = null;
5112 return;
5113 }
5114 myPackages[i] = cn.getPackageName().intern();
5115 myClasses[i] = cn.getClassName().intern();
5116 myComponents[i] = cn.flattenToShortString().intern();
5117 }
5118 mSetPackages = myPackages;
5119 mSetClasses = myClasses;
5120 mSetComponents = myComponents;
5121 } else {
5122 mSetPackages = null;
5123 mSetClasses = null;
5124 mSetComponents = null;
5125 }
5126 }
5127
5128 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
5129 IOException {
5130 mShortActivity = parser.getAttributeValue(null, "name");
5131 mActivity = ComponentName.unflattenFromString(mShortActivity);
5132 if (mActivity == null) {
5133 mParseError = "Bad activity name " + mShortActivity;
5134 }
5135 String matchStr = parser.getAttributeValue(null, "match");
5136 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
5137 String setCountStr = parser.getAttributeValue(null, "set");
5138 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
5139
5140 String[] myPackages = setCount > 0 ? new String[setCount] : null;
5141 String[] myClasses = setCount > 0 ? new String[setCount] : null;
5142 String[] myComponents = setCount > 0 ? new String[setCount] : null;
5143
5144 int setPos = 0;
5145
5146 int outerDepth = parser.getDepth();
5147 int type;
5148 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
5149 && (type != XmlPullParser.END_TAG
5150 || parser.getDepth() > outerDepth)) {
5151 if (type == XmlPullParser.END_TAG
5152 || type == XmlPullParser.TEXT) {
5153 continue;
5154 }
5155
5156 String tagName = parser.getName();
5157 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
5158 // + parser.getDepth() + " tag=" + tagName);
5159 if (tagName.equals("set")) {
5160 String name = parser.getAttributeValue(null, "name");
5161 if (name == null) {
5162 if (mParseError == null) {
5163 mParseError = "No name in set tag in preferred activity "
5164 + mShortActivity;
5165 }
5166 } else if (setPos >= setCount) {
5167 if (mParseError == null) {
5168 mParseError = "Too many set tags in preferred activity "
5169 + mShortActivity;
5170 }
5171 } else {
5172 ComponentName cn = ComponentName.unflattenFromString(name);
5173 if (cn == null) {
5174 if (mParseError == null) {
5175 mParseError = "Bad set name " + name + " in preferred activity "
5176 + mShortActivity;
5177 }
5178 } else {
5179 myPackages[setPos] = cn.getPackageName();
5180 myClasses[setPos] = cn.getClassName();
5181 myComponents[setPos] = name;
5182 setPos++;
5183 }
5184 }
5185 XmlUtils.skipCurrentTag(parser);
5186 } else if (tagName.equals("filter")) {
5187 //Log.i(TAG, "Starting to parse filter...");
5188 readFromXml(parser);
5189 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
5190 // + parser.getDepth() + " tag=" + parser.getName());
5191 } else {
5192 reportSettingsProblem(Log.WARN,
5193 "Unknown element under <preferred-activities>: "
5194 + parser.getName());
5195 XmlUtils.skipCurrentTag(parser);
5196 }
5197 }
5198
5199 if (setPos != setCount) {
5200 if (mParseError == null) {
5201 mParseError = "Not enough set tags (expected " + setCount
5202 + " but found " + setPos + ") in " + mShortActivity;
5203 }
5204 }
5205
5206 mSetPackages = myPackages;
5207 mSetClasses = myClasses;
5208 mSetComponents = myComponents;
5209 }
5210
5211 public void writeToXml(XmlSerializer serializer) throws IOException {
5212 final int NS = mSetClasses != null ? mSetClasses.length : 0;
5213 serializer.attribute(null, "name", mShortActivity);
5214 serializer.attribute(null, "match", Integer.toHexString(mMatch));
5215 serializer.attribute(null, "set", Integer.toString(NS));
5216 for (int s=0; s<NS; s++) {
5217 serializer.startTag(null, "set");
5218 serializer.attribute(null, "name", mSetComponents[s]);
5219 serializer.endTag(null, "set");
5220 }
5221 serializer.startTag(null, "filter");
5222 super.writeToXml(serializer);
5223 serializer.endTag(null, "filter");
5224 }
5225
5226 boolean sameSet(List<ResolveInfo> query, int priority) {
5227 if (mSetPackages == null) return false;
5228 final int NQ = query.size();
5229 final int NS = mSetPackages.length;
5230 int numMatch = 0;
5231 for (int i=0; i<NQ; i++) {
5232 ResolveInfo ri = query.get(i);
5233 if (ri.priority != priority) continue;
5234 ActivityInfo ai = ri.activityInfo;
5235 boolean good = false;
5236 for (int j=0; j<NS; j++) {
5237 if (mSetPackages[j].equals(ai.packageName)
5238 && mSetClasses[j].equals(ai.name)) {
5239 numMatch++;
5240 good = true;
5241 break;
5242 }
5243 }
5244 if (!good) return false;
5245 }
5246 return numMatch == NS;
5247 }
5248 }
5249
5250 static class GrantedPermissions {
5251 final int pkgFlags;
5252
5253 HashSet<String> grantedPermissions = new HashSet<String>();
5254 int[] gids;
5255
5256 HashSet<String> loadedPermissions = new HashSet<String>();
5257
5258 GrantedPermissions(int pkgFlags) {
5259 this.pkgFlags = pkgFlags & ApplicationInfo.FLAG_SYSTEM;
5260 }
5261 }
5262
5263 /**
5264 * Settings base class for pending and resolved classes.
5265 */
5266 static class PackageSettingBase extends GrantedPermissions {
5267 final String name;
5268 final File codePath;
5269 final String codePathString;
5270 final File resourcePath;
5271 final String resourcePathString;
5272 private long timeStamp;
5273 private String timeStampString = "0";
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005274 final int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005275
5276 PackageSignatures signatures = new PackageSignatures();
5277
5278 boolean permissionsFixed;
5279
5280 /* Explicitly disabled components */
5281 HashSet<String> disabledComponents = new HashSet<String>(0);
5282 /* Explicitly enabled components */
5283 HashSet<String> enabledComponents = new HashSet<String>(0);
5284 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
5285 int installStatus = PKG_INSTALL_COMPLETE;
Jacek Surazskic64322c2009-04-28 15:26:38 +02005286
5287 /* package name of the app that installed this package */
5288 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289
5290 PackageSettingBase(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005291 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005292 super(pkgFlags);
5293 this.name = name;
5294 this.codePath = codePath;
5295 this.codePathString = codePath.toString();
5296 this.resourcePath = resourcePath;
5297 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005298 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005299 }
5300
Jacek Surazskic64322c2009-04-28 15:26:38 +02005301 public void setInstallerPackageName(String packageName) {
5302 installerPackageName = packageName;
5303 }
5304
5305 String getInstallerPackageName() {
5306 return installerPackageName;
5307 }
5308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005309 public void setInstallStatus(int newStatus) {
5310 installStatus = newStatus;
5311 }
5312
5313 public int getInstallStatus() {
5314 return installStatus;
5315 }
5316
5317 public void setTimeStamp(long newStamp) {
5318 if (newStamp != timeStamp) {
5319 timeStamp = newStamp;
5320 timeStampString = Long.toString(newStamp);
5321 }
5322 }
5323
5324 public void setTimeStamp(long newStamp, String newStampStr) {
5325 timeStamp = newStamp;
5326 timeStampString = newStampStr;
5327 }
5328
5329 public long getTimeStamp() {
5330 return timeStamp;
5331 }
5332
5333 public String getTimeStampStr() {
5334 return timeStampString;
5335 }
5336
5337 public void copyFrom(PackageSettingBase base) {
5338 grantedPermissions = base.grantedPermissions;
5339 gids = base.gids;
5340 loadedPermissions = base.loadedPermissions;
5341
5342 timeStamp = base.timeStamp;
5343 timeStampString = base.timeStampString;
5344 signatures = base.signatures;
5345 permissionsFixed = base.permissionsFixed;
5346 disabledComponents = base.disabledComponents;
5347 enabledComponents = base.enabledComponents;
5348 enabled = base.enabled;
5349 installStatus = base.installStatus;
5350 }
5351
5352 void enableComponentLP(String componentClassName) {
5353 disabledComponents.remove(componentClassName);
5354 enabledComponents.add(componentClassName);
5355 }
5356
5357 void disableComponentLP(String componentClassName) {
5358 enabledComponents.remove(componentClassName);
5359 disabledComponents.add(componentClassName);
5360 }
5361
5362 void restoreComponentLP(String componentClassName) {
5363 enabledComponents.remove(componentClassName);
5364 disabledComponents.remove(componentClassName);
5365 }
5366
5367 int currentEnabledStateLP(String componentName) {
5368 if (enabledComponents.contains(componentName)) {
5369 return COMPONENT_ENABLED_STATE_ENABLED;
5370 } else if (disabledComponents.contains(componentName)) {
5371 return COMPONENT_ENABLED_STATE_DISABLED;
5372 } else {
5373 return COMPONENT_ENABLED_STATE_DEFAULT;
5374 }
5375 }
5376 }
5377
5378 /**
5379 * Settings data for a particular package we know about.
5380 */
5381 static final class PackageSetting extends PackageSettingBase {
5382 int userId;
5383 PackageParser.Package pkg;
5384 SharedUserSetting sharedUser;
5385
5386 PackageSetting(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005387 int pVersionCode, int pkgFlags) {
5388 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 }
5390
5391 @Override
5392 public String toString() {
5393 return "PackageSetting{"
5394 + Integer.toHexString(System.identityHashCode(this))
5395 + " " + name + "/" + userId + "}";
5396 }
5397 }
5398
5399 /**
5400 * Settings data for a particular shared user ID we know about.
5401 */
5402 static final class SharedUserSetting extends GrantedPermissions {
5403 final String name;
5404 int userId;
5405 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
5406 final PackageSignatures signatures = new PackageSignatures();
5407
5408 SharedUserSetting(String _name, int _pkgFlags) {
5409 super(_pkgFlags);
5410 name = _name;
5411 }
5412
5413 @Override
5414 public String toString() {
5415 return "SharedUserSetting{"
5416 + Integer.toHexString(System.identityHashCode(this))
5417 + " " + name + "/" + userId + "}";
5418 }
5419 }
5420
5421 /**
5422 * Holds information about dynamic settings.
5423 */
5424 private static final class Settings {
5425 private final File mSettingsFilename;
5426 private final File mBackupSettingsFilename;
5427 private final HashMap<String, PackageSetting> mPackages =
5428 new HashMap<String, PackageSetting>();
5429 // The user's preferred packages/applications, in order of preference.
5430 // First is the most preferred.
5431 private final ArrayList<PackageSetting> mPreferredPackages =
5432 new ArrayList<PackageSetting>();
5433 // List of replaced system applications
5434 final HashMap<String, PackageSetting> mDisabledSysPackages =
5435 new HashMap<String, PackageSetting>();
5436
5437 // The user's preferred activities associated with particular intent
5438 // filters.
5439 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
5440 new IntentResolver<PreferredActivity, PreferredActivity>() {
5441 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005442 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005444 out.print(prefix); out.print(
5445 Integer.toHexString(System.identityHashCode(filter)));
5446 out.print(' ');
5447 out.print(filter.mActivity.flattenToShortString());
5448 out.print(" match=0x");
5449 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005451 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07005453 out.print(prefix); out.print(" ");
5454 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 }
5456 }
5457 }
5458 };
5459 private final HashMap<String, SharedUserSetting> mSharedUsers =
5460 new HashMap<String, SharedUserSetting>();
5461 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
5462 private final SparseArray<Object> mOtherUserIds =
5463 new SparseArray<Object>();
5464
5465 // For reading/writing settings file.
5466 private final ArrayList<Signature> mPastSignatures =
5467 new ArrayList<Signature>();
5468
5469 // Mapping from permission names to info about them.
5470 final HashMap<String, BasePermission> mPermissions =
5471 new HashMap<String, BasePermission>();
5472
5473 // Mapping from permission tree names to info about them.
5474 final HashMap<String, BasePermission> mPermissionTrees =
5475 new HashMap<String, BasePermission>();
5476
5477 private final ArrayList<String> mPendingPreferredPackages
5478 = new ArrayList<String>();
5479
5480 private final StringBuilder mReadMessages = new StringBuilder();
5481
5482 private static final class PendingPackage extends PackageSettingBase {
5483 final int sharedId;
5484
5485 PendingPackage(String name, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005486 int sharedId, int pVersionCode, int pkgFlags) {
5487 super(name, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 this.sharedId = sharedId;
5489 }
5490 }
5491 private final ArrayList<PendingPackage> mPendingPackages
5492 = new ArrayList<PendingPackage>();
5493
5494 Settings() {
5495 File dataDir = Environment.getDataDirectory();
5496 File systemDir = new File(dataDir, "system");
5497 systemDir.mkdirs();
5498 FileUtils.setPermissions(systemDir.toString(),
5499 FileUtils.S_IRWXU|FileUtils.S_IRWXG
5500 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
5501 -1, -1);
5502 mSettingsFilename = new File(systemDir, "packages.xml");
5503 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
5504 }
5505
5506 PackageSetting getPackageLP(PackageParser.Package pkg,
5507 SharedUserSetting sharedUser, File codePath, File resourcePath,
5508 int pkgFlags, boolean create, boolean add) {
5509 final String name = pkg.packageName;
5510 PackageSetting p = getPackageLP(name, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005511 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512
5513 if (p != null) {
5514 p.pkg = pkg;
5515 }
5516 return p;
5517 }
5518
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005519 PackageSetting peekPackageLP(String name) {
5520 return mPackages.get(name);
5521 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 PackageSetting p = mPackages.get(name);
5523 if (p != null && p.codePath.getPath().equals(codePath)) {
5524 return p;
5525 }
5526 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005527 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 }
5529
5530 void setInstallStatus(String pkgName, int status) {
5531 PackageSetting p = mPackages.get(pkgName);
5532 if(p != null) {
5533 if(p.getInstallStatus() != status) {
5534 p.setInstallStatus(status);
5535 }
5536 }
5537 }
5538
Jacek Surazskic64322c2009-04-28 15:26:38 +02005539 void setInstallerPackageName(String pkgName,
5540 String installerPkgName) {
5541 PackageSetting p = mPackages.get(pkgName);
5542 if(p != null) {
5543 p.setInstallerPackageName(installerPkgName);
5544 }
5545 }
5546
5547 String getInstallerPackageName(String pkgName) {
5548 PackageSetting p = mPackages.get(pkgName);
5549 return (p == null) ? null : p.getInstallerPackageName();
5550 }
5551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 int getInstallStatus(String pkgName) {
5553 PackageSetting p = mPackages.get(pkgName);
5554 if(p != null) {
5555 return p.getInstallStatus();
5556 }
5557 return -1;
5558 }
5559
5560 SharedUserSetting getSharedUserLP(String name,
5561 int pkgFlags, boolean create) {
5562 SharedUserSetting s = mSharedUsers.get(name);
5563 if (s == null) {
5564 if (!create) {
5565 return null;
5566 }
5567 s = new SharedUserSetting(name, pkgFlags);
5568 if (MULTIPLE_APPLICATION_UIDS) {
5569 s.userId = newUserIdLP(s);
5570 } else {
5571 s.userId = FIRST_APPLICATION_UID;
5572 }
5573 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
5574 // < 0 means we couldn't assign a userid; fall out and return
5575 // s, which is currently null
5576 if (s.userId >= 0) {
5577 mSharedUsers.put(name, s);
5578 }
5579 }
5580
5581 return s;
5582 }
5583
5584 int disableSystemPackageLP(String name) {
5585 PackageSetting p = mPackages.get(name);
5586 if(p == null) {
5587 Log.w(TAG, "Package:"+name+" is not an installed package");
5588 return -1;
5589 }
5590 PackageSetting dp = mDisabledSysPackages.get(name);
5591 // always make sure the system package code and resource paths dont change
5592 if(dp == null) {
5593 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
5594 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5595 }
5596 mDisabledSysPackages.put(name, p);
5597 }
5598 return removePackageLP(name);
5599 }
5600
5601 PackageSetting enableSystemPackageLP(String name) {
5602 PackageSetting p = mDisabledSysPackages.get(name);
5603 if(p == null) {
5604 Log.w(TAG, "Package:"+name+" is not disabled");
5605 return null;
5606 }
5607 // Reset flag in ApplicationInfo object
5608 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
5609 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5610 }
5611 PackageSetting ret = addPackageLP(name, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005612 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 mDisabledSysPackages.remove(name);
5614 return ret;
5615 }
5616
5617 PackageSetting addPackageLP(String name, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005618 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 PackageSetting p = mPackages.get(name);
5620 if (p != null) {
5621 if (p.userId == uid) {
5622 return p;
5623 }
5624 reportSettingsProblem(Log.ERROR,
5625 "Adding duplicate package, keeping first: " + name);
5626 return null;
5627 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005628 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005629 p.userId = uid;
5630 if (addUserIdLP(uid, p, name)) {
5631 mPackages.put(name, p);
5632 return p;
5633 }
5634 return null;
5635 }
5636
5637 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
5638 SharedUserSetting s = mSharedUsers.get(name);
5639 if (s != null) {
5640 if (s.userId == uid) {
5641 return s;
5642 }
5643 reportSettingsProblem(Log.ERROR,
5644 "Adding duplicate shared user, keeping first: " + name);
5645 return null;
5646 }
5647 s = new SharedUserSetting(name, pkgFlags);
5648 s.userId = uid;
5649 if (addUserIdLP(uid, s, name)) {
5650 mSharedUsers.put(name, s);
5651 return s;
5652 }
5653 return null;
5654 }
5655
5656 private PackageSetting getPackageLP(String name,
5657 SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005658 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 PackageSetting p = mPackages.get(name);
5660 if (p != null) {
5661 if (!p.codePath.equals(codePath)) {
5662 // Check to see if its a disabled system app
5663 PackageSetting ps = mDisabledSysPackages.get(name);
5664 if((ps != null) && ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5665 // Could be a replaced system package
5666 // Note that if the user replaced a system app, the user has to physically
5667 // delete the new one in order to revert to the system app. So even
5668 // if the user updated the system app via an update, the user still
5669 // has to delete the one installed in the data partition in order to pick up the
5670 // new system package.
5671 return p;
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07005672 } else if ((p.pkg != null) && (p.pkg.applicationInfo != null) &&
5673 ((p.pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)) {
5674 // Check for non-system apps
5675 reportSettingsProblem(Log.WARN,
5676 "Package " + name + " codePath changed from " + p.codePath
5677 + " to " + codePath + "; Retaining data and using new code");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 } else {
5679 reportSettingsProblem(Log.WARN,
5680 "Package " + name + " codePath changed from " + p.codePath
5681 + " to " + codePath + "; replacing with new");
5682 p = null;
5683 }
5684 } else if (p.sharedUser != sharedUser) {
5685 reportSettingsProblem(Log.WARN,
5686 "Package " + name + " shared user changed from "
5687 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
5688 + " to "
5689 + (sharedUser != null ? sharedUser.name : "<nothing>")
5690 + "; replacing with new");
5691 p = null;
5692 }
5693 }
5694 if (p == null) {
5695 // Create a new PackageSettings entry. this can end up here because
5696 // of code path mismatch or user id mismatch of an updated system partition
5697 if (!create) {
5698 return null;
5699 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005700 p = new PackageSetting(name, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 p.setTimeStamp(codePath.lastModified());
Dianne Hackborn5d6d7732009-05-13 18:09:56 -07005702 p.sharedUser = sharedUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 if (sharedUser != null) {
5704 p.userId = sharedUser.userId;
5705 } else if (MULTIPLE_APPLICATION_UIDS) {
5706 p.userId = newUserIdLP(p);
5707 } else {
5708 p.userId = FIRST_APPLICATION_UID;
5709 }
5710 if (p.userId < 0) {
5711 reportSettingsProblem(Log.WARN,
5712 "Package " + name + " could not be assigned a valid uid");
5713 return null;
5714 }
5715 if (add) {
5716 // Finish adding new package by adding it and updating shared
5717 // user preferences
5718 insertPackageSettingLP(p, name, sharedUser);
5719 }
5720 }
5721 return p;
5722 }
5723
5724 // Utility method that adds a PackageSetting to mPackages and
5725 // completes updating the shared user attributes
5726 private void insertPackageSettingLP(PackageSetting p, String name,
5727 SharedUserSetting sharedUser) {
5728 mPackages.put(name, p);
5729 if (sharedUser != null) {
5730 if (p.sharedUser != null && p.sharedUser != sharedUser) {
5731 reportSettingsProblem(Log.ERROR,
5732 "Package " + p.name + " was user "
5733 + p.sharedUser + " but is now " + sharedUser
5734 + "; I am not changing its files so it will probably fail!");
5735 p.sharedUser.packages.remove(p);
5736 } else if (p.userId != sharedUser.userId) {
5737 reportSettingsProblem(Log.ERROR,
5738 "Package " + p.name + " was user id " + p.userId
5739 + " but is now user " + sharedUser
5740 + " with id " + sharedUser.userId
5741 + "; I am not changing its files so it will probably fail!");
5742 }
5743
5744 sharedUser.packages.add(p);
5745 p.sharedUser = sharedUser;
5746 p.userId = sharedUser.userId;
5747 }
5748 }
5749
5750 private void updateSharedUserPerms (PackageSetting deletedPs) {
5751 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
5752 Log.i(TAG, "Trying to update info for null package. Just ignoring");
5753 return;
5754 }
5755 // No sharedUserId
5756 if (deletedPs.sharedUser == null) {
5757 return;
5758 }
5759 SharedUserSetting sus = deletedPs.sharedUser;
5760 // Update permissions
5761 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
5762 boolean used = false;
5763 if (!sus.grantedPermissions.contains (eachPerm)) {
5764 continue;
5765 }
5766 for (PackageSetting pkg:sus.packages) {
5767 if (pkg.grantedPermissions.contains (eachPerm)) {
5768 used = true;
5769 break;
5770 }
5771 }
5772 if (!used) {
5773 // can safely delete this permission from list
5774 sus.grantedPermissions.remove(eachPerm);
5775 sus.loadedPermissions.remove(eachPerm);
5776 }
5777 }
5778 // Update gids
5779 int newGids[] = null;
5780 for (PackageSetting pkg:sus.packages) {
5781 newGids = appendInts(newGids, pkg.gids);
5782 }
5783 sus.gids = newGids;
5784 }
5785
5786 private int removePackageLP(String name) {
5787 PackageSetting p = mPackages.get(name);
5788 if (p != null) {
5789 mPackages.remove(name);
5790 if (p.sharedUser != null) {
5791 p.sharedUser.packages.remove(p);
5792 if (p.sharedUser.packages.size() == 0) {
5793 mSharedUsers.remove(p.sharedUser.name);
5794 removeUserIdLP(p.sharedUser.userId);
5795 return p.sharedUser.userId;
5796 }
5797 } else {
5798 removeUserIdLP(p.userId);
5799 return p.userId;
5800 }
5801 }
5802 return -1;
5803 }
5804
5805 private boolean addUserIdLP(int uid, Object obj, Object name) {
5806 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
5807 return false;
5808 }
5809
5810 if (uid >= FIRST_APPLICATION_UID) {
5811 int N = mUserIds.size();
5812 final int index = uid - FIRST_APPLICATION_UID;
5813 while (index >= N) {
5814 mUserIds.add(null);
5815 N++;
5816 }
5817 if (mUserIds.get(index) != null) {
5818 reportSettingsProblem(Log.ERROR,
5819 "Adding duplicate shared id: " + uid
5820 + " name=" + name);
5821 return false;
5822 }
5823 mUserIds.set(index, obj);
5824 } else {
5825 if (mOtherUserIds.get(uid) != null) {
5826 reportSettingsProblem(Log.ERROR,
5827 "Adding duplicate shared id: " + uid
5828 + " name=" + name);
5829 return false;
5830 }
5831 mOtherUserIds.put(uid, obj);
5832 }
5833 return true;
5834 }
5835
5836 public Object getUserIdLP(int uid) {
5837 if (uid >= FIRST_APPLICATION_UID) {
5838 int N = mUserIds.size();
5839 final int index = uid - FIRST_APPLICATION_UID;
5840 return index < N ? mUserIds.get(index) : null;
5841 } else {
5842 return mOtherUserIds.get(uid);
5843 }
5844 }
5845
5846 private void removeUserIdLP(int uid) {
5847 if (uid >= FIRST_APPLICATION_UID) {
5848 int N = mUserIds.size();
5849 final int index = uid - FIRST_APPLICATION_UID;
5850 if (index < N) mUserIds.set(index, null);
5851 } else {
5852 mOtherUserIds.remove(uid);
5853 }
5854 }
5855
5856 void writeLP() {
5857 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
5858
5859 // Keep the old settings around until we know the new ones have
5860 // been successfully written.
5861 if (mSettingsFilename.exists()) {
5862 if (mBackupSettingsFilename.exists()) {
5863 mBackupSettingsFilename.delete();
5864 }
5865 mSettingsFilename.renameTo(mBackupSettingsFilename);
5866 }
5867
5868 mPastSignatures.clear();
5869
5870 try {
5871 FileOutputStream str = new FileOutputStream(mSettingsFilename);
5872
5873 //XmlSerializer serializer = XmlUtils.serializerInstance();
5874 XmlSerializer serializer = new FastXmlSerializer();
5875 serializer.setOutput(str, "utf-8");
5876 serializer.startDocument(null, true);
5877 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
5878
5879 serializer.startTag(null, "packages");
5880
5881 serializer.startTag(null, "permission-trees");
5882 for (BasePermission bp : mPermissionTrees.values()) {
5883 writePermission(serializer, bp);
5884 }
5885 serializer.endTag(null, "permission-trees");
5886
5887 serializer.startTag(null, "permissions");
5888 for (BasePermission bp : mPermissions.values()) {
5889 writePermission(serializer, bp);
5890 }
5891 serializer.endTag(null, "permissions");
5892
5893 for (PackageSetting pkg : mPackages.values()) {
5894 writePackage(serializer, pkg);
5895 }
5896
5897 for (PackageSetting pkg : mDisabledSysPackages.values()) {
5898 writeDisabledSysPackage(serializer, pkg);
5899 }
5900
5901 serializer.startTag(null, "preferred-packages");
5902 int N = mPreferredPackages.size();
5903 for (int i=0; i<N; i++) {
5904 PackageSetting pkg = mPreferredPackages.get(i);
5905 serializer.startTag(null, "item");
5906 serializer.attribute(null, "name", pkg.name);
5907 serializer.endTag(null, "item");
5908 }
5909 serializer.endTag(null, "preferred-packages");
5910
5911 serializer.startTag(null, "preferred-activities");
5912 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
5913 serializer.startTag(null, "item");
5914 pa.writeToXml(serializer);
5915 serializer.endTag(null, "item");
5916 }
5917 serializer.endTag(null, "preferred-activities");
5918
5919 for (SharedUserSetting usr : mSharedUsers.values()) {
5920 serializer.startTag(null, "shared-user");
5921 serializer.attribute(null, "name", usr.name);
5922 serializer.attribute(null, "userId",
5923 Integer.toString(usr.userId));
5924 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
5925 serializer.startTag(null, "perms");
5926 for (String name : usr.grantedPermissions) {
5927 serializer.startTag(null, "item");
5928 serializer.attribute(null, "name", name);
5929 serializer.endTag(null, "item");
5930 }
5931 serializer.endTag(null, "perms");
5932 serializer.endTag(null, "shared-user");
5933 }
5934
5935 serializer.endTag(null, "packages");
5936
5937 serializer.endDocument();
5938
5939 str.flush();
5940 str.close();
5941
5942 // New settings successfully written, old ones are no longer
5943 // needed.
5944 mBackupSettingsFilename.delete();
5945 FileUtils.setPermissions(mSettingsFilename.toString(),
5946 FileUtils.S_IRUSR|FileUtils.S_IWUSR
5947 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
5948 |FileUtils.S_IROTH,
5949 -1, -1);
5950
5951 } catch(XmlPullParserException e) {
5952 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
5953
5954 } catch(java.io.IOException e) {
5955 Log.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
5956
5957 }
5958
5959 //Debug.stopMethodTracing();
5960 }
5961
5962 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
5963 throws java.io.IOException {
5964 serializer.startTag(null, "updated-package");
5965 serializer.attribute(null, "name", pkg.name);
5966 serializer.attribute(null, "codePath", pkg.codePathString);
5967 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005968 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
5970 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
5971 }
5972 if (pkg.sharedUser == null) {
5973 serializer.attribute(null, "userId",
5974 Integer.toString(pkg.userId));
5975 } else {
5976 serializer.attribute(null, "sharedUserId",
5977 Integer.toString(pkg.userId));
5978 }
5979 serializer.startTag(null, "perms");
5980 if (pkg.sharedUser == null) {
5981 // If this is a shared user, the permissions will
5982 // be written there. We still need to write an
5983 // empty permissions list so permissionsFixed will
5984 // be set.
5985 for (final String name : pkg.grantedPermissions) {
5986 BasePermission bp = mPermissions.get(name);
5987 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
5988 // We only need to write signature or system permissions but this wont
5989 // match the semantics of grantedPermissions. So write all permissions.
5990 serializer.startTag(null, "item");
5991 serializer.attribute(null, "name", name);
5992 serializer.endTag(null, "item");
5993 }
5994 }
5995 }
5996 serializer.endTag(null, "perms");
5997 serializer.endTag(null, "updated-package");
5998 }
5999
6000 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
6001 throws java.io.IOException {
6002 serializer.startTag(null, "package");
6003 serializer.attribute(null, "name", pkg.name);
6004 serializer.attribute(null, "codePath", pkg.codePathString);
6005 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
6006 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
6007 }
6008 serializer.attribute(null, "system",
6009 (pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
6010 ? "true" : "false");
6011 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006012 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 if (pkg.sharedUser == null) {
6014 serializer.attribute(null, "userId",
6015 Integer.toString(pkg.userId));
6016 } else {
6017 serializer.attribute(null, "sharedUserId",
6018 Integer.toString(pkg.userId));
6019 }
6020 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
6021 serializer.attribute(null, "enabled",
6022 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
6023 ? "true" : "false");
6024 }
6025 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
6026 serializer.attribute(null, "installStatus", "false");
6027 }
Jacek Surazskic64322c2009-04-28 15:26:38 +02006028 if (pkg.installerPackageName != null) {
6029 serializer.attribute(null, "installer", pkg.installerPackageName);
6030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
6032 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6033 serializer.startTag(null, "perms");
6034 if (pkg.sharedUser == null) {
6035 // If this is a shared user, the permissions will
6036 // be written there. We still need to write an
6037 // empty permissions list so permissionsFixed will
6038 // be set.
6039 for (final String name : pkg.grantedPermissions) {
6040 serializer.startTag(null, "item");
6041 serializer.attribute(null, "name", name);
6042 serializer.endTag(null, "item");
6043 }
6044 }
6045 serializer.endTag(null, "perms");
6046 }
6047 if (pkg.disabledComponents.size() > 0) {
6048 serializer.startTag(null, "disabled-components");
6049 for (final String name : pkg.disabledComponents) {
6050 serializer.startTag(null, "item");
6051 serializer.attribute(null, "name", name);
6052 serializer.endTag(null, "item");
6053 }
6054 serializer.endTag(null, "disabled-components");
6055 }
6056 if (pkg.enabledComponents.size() > 0) {
6057 serializer.startTag(null, "enabled-components");
6058 for (final String name : pkg.enabledComponents) {
6059 serializer.startTag(null, "item");
6060 serializer.attribute(null, "name", name);
6061 serializer.endTag(null, "item");
6062 }
6063 serializer.endTag(null, "enabled-components");
6064 }
Jacek Surazskic64322c2009-04-28 15:26:38 +02006065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 serializer.endTag(null, "package");
6067 }
6068
6069 void writePermission(XmlSerializer serializer, BasePermission bp)
6070 throws XmlPullParserException, java.io.IOException {
6071 if (bp.type != BasePermission.TYPE_BUILTIN
6072 && bp.sourcePackage != null) {
6073 serializer.startTag(null, "item");
6074 serializer.attribute(null, "name", bp.name);
6075 serializer.attribute(null, "package", bp.sourcePackage);
6076 if (DEBUG_SETTINGS) Log.v(TAG,
6077 "Writing perm: name=" + bp.name + " type=" + bp.type);
6078 if (bp.type == BasePermission.TYPE_DYNAMIC) {
6079 PermissionInfo pi = bp.perm != null ? bp.perm.info
6080 : bp.pendingInfo;
6081 if (pi != null) {
6082 serializer.attribute(null, "type", "dynamic");
6083 if (pi.icon != 0) {
6084 serializer.attribute(null, "icon",
6085 Integer.toString(pi.icon));
6086 }
6087 if (pi.nonLocalizedLabel != null) {
6088 serializer.attribute(null, "label",
6089 pi.nonLocalizedLabel.toString());
6090 }
6091 if (pi.protectionLevel !=
6092 PermissionInfo.PROTECTION_NORMAL) {
6093 serializer.attribute(null, "protection",
6094 Integer.toString(pi.protectionLevel));
6095 }
6096 }
6097 }
6098 serializer.endTag(null, "item");
6099 }
6100 }
6101
6102 String getReadMessagesLP() {
6103 return mReadMessages.toString();
6104 }
6105
6106 ArrayList<String> getListOfIncompleteInstallPackages() {
6107 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
6108 Iterator<String> its = kList.iterator();
6109 ArrayList<String> ret = new ArrayList<String>();
6110 while(its.hasNext()) {
6111 String key = its.next();
6112 PackageSetting ps = mPackages.get(key);
6113 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
6114 ret.add(key);
6115 }
6116 }
6117 return ret;
6118 }
6119
6120 boolean readLP() {
6121 FileInputStream str = null;
6122 if (mBackupSettingsFilename.exists()) {
6123 try {
6124 str = new FileInputStream(mBackupSettingsFilename);
6125 mReadMessages.append("Reading from backup settings file\n");
6126 Log.i(TAG, "Reading from backup settings file!");
6127 } catch (java.io.IOException e) {
6128 // We'll try for the normal settings file.
6129 }
6130 }
6131
6132 mPastSignatures.clear();
6133
6134 try {
6135 if (str == null) {
6136 if (!mSettingsFilename.exists()) {
6137 mReadMessages.append("No settings file found\n");
6138 Log.i(TAG, "No current settings file!");
6139 return false;
6140 }
6141 str = new FileInputStream(mSettingsFilename);
6142 }
6143 XmlPullParser parser = Xml.newPullParser();
6144 parser.setInput(str, null);
6145
6146 int type;
6147 while ((type=parser.next()) != XmlPullParser.START_TAG
6148 && type != XmlPullParser.END_DOCUMENT) {
6149 ;
6150 }
6151
6152 if (type != XmlPullParser.START_TAG) {
6153 mReadMessages.append("No start tag found in settings file\n");
6154 Log.e(TAG, "No start tag found in package manager settings");
6155 return false;
6156 }
6157
6158 int outerDepth = parser.getDepth();
6159 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6160 && (type != XmlPullParser.END_TAG
6161 || parser.getDepth() > outerDepth)) {
6162 if (type == XmlPullParser.END_TAG
6163 || type == XmlPullParser.TEXT) {
6164 continue;
6165 }
6166
6167 String tagName = parser.getName();
6168 if (tagName.equals("package")) {
6169 readPackageLP(parser);
6170 } else if (tagName.equals("permissions")) {
6171 readPermissionsLP(mPermissions, parser);
6172 } else if (tagName.equals("permission-trees")) {
6173 readPermissionsLP(mPermissionTrees, parser);
6174 } else if (tagName.equals("shared-user")) {
6175 readSharedUserLP(parser);
6176 } else if (tagName.equals("preferred-packages")) {
6177 readPreferredPackagesLP(parser);
6178 } else if (tagName.equals("preferred-activities")) {
6179 readPreferredActivitiesLP(parser);
6180 } else if(tagName.equals("updated-package")) {
6181 readDisabledSysPackageLP(parser);
6182 } else {
6183 Log.w(TAG, "Unknown element under <packages>: "
6184 + parser.getName());
6185 XmlUtils.skipCurrentTag(parser);
6186 }
6187 }
6188
6189 str.close();
6190
6191 } catch(XmlPullParserException e) {
6192 mReadMessages.append("Error reading: " + e.toString());
6193 Log.e(TAG, "Error reading package manager settings", e);
6194
6195 } catch(java.io.IOException e) {
6196 mReadMessages.append("Error reading: " + e.toString());
6197 Log.e(TAG, "Error reading package manager settings", e);
6198
6199 }
6200
6201 int N = mPendingPackages.size();
6202 for (int i=0; i<N; i++) {
6203 final PendingPackage pp = mPendingPackages.get(i);
6204 Object idObj = getUserIdLP(pp.sharedId);
6205 if (idObj != null && idObj instanceof SharedUserSetting) {
6206 PackageSetting p = getPackageLP(pp.name,
6207 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006208 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 if (p == null) {
6210 Log.w(TAG, "Unable to create application package for "
6211 + pp.name);
6212 continue;
6213 }
6214 p.copyFrom(pp);
6215 } else if (idObj != null) {
6216 String msg = "Bad package setting: package " + pp.name
6217 + " has shared uid " + pp.sharedId
6218 + " that is not a shared uid\n";
6219 mReadMessages.append(msg);
6220 Log.e(TAG, msg);
6221 } else {
6222 String msg = "Bad package setting: package " + pp.name
6223 + " has shared uid " + pp.sharedId
6224 + " that is not defined\n";
6225 mReadMessages.append(msg);
6226 Log.e(TAG, msg);
6227 }
6228 }
6229 mPendingPackages.clear();
6230
6231 N = mPendingPreferredPackages.size();
6232 mPreferredPackages.clear();
6233 for (int i=0; i<N; i++) {
6234 final String name = mPendingPreferredPackages.get(i);
6235 final PackageSetting p = mPackages.get(name);
6236 if (p != null) {
6237 mPreferredPackages.add(p);
6238 } else {
6239 Log.w(TAG, "Unknown preferred package: " + name);
6240 }
6241 }
6242 mPendingPreferredPackages.clear();
6243
6244 mReadMessages.append("Read completed successfully: "
6245 + mPackages.size() + " packages, "
6246 + mSharedUsers.size() + " shared uids\n");
6247
6248 return true;
6249 }
6250
6251 private int readInt(XmlPullParser parser, String ns, String name,
6252 int defValue) {
6253 String v = parser.getAttributeValue(ns, name);
6254 try {
6255 if (v == null) {
6256 return defValue;
6257 }
6258 return Integer.parseInt(v);
6259 } catch (NumberFormatException e) {
6260 reportSettingsProblem(Log.WARN,
6261 "Error in package manager settings: attribute " +
6262 name + " has bad integer value " + v + " at "
6263 + parser.getPositionDescription());
6264 }
6265 return defValue;
6266 }
6267
6268 private void readPermissionsLP(HashMap<String, BasePermission> out,
6269 XmlPullParser parser)
6270 throws IOException, XmlPullParserException {
6271 int outerDepth = parser.getDepth();
6272 int type;
6273 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6274 && (type != XmlPullParser.END_TAG
6275 || parser.getDepth() > outerDepth)) {
6276 if (type == XmlPullParser.END_TAG
6277 || type == XmlPullParser.TEXT) {
6278 continue;
6279 }
6280
6281 String tagName = parser.getName();
6282 if (tagName.equals("item")) {
6283 String name = parser.getAttributeValue(null, "name");
6284 String sourcePackage = parser.getAttributeValue(null, "package");
6285 String ptype = parser.getAttributeValue(null, "type");
6286 if (name != null && sourcePackage != null) {
6287 boolean dynamic = "dynamic".equals(ptype);
6288 BasePermission bp = new BasePermission(name, sourcePackage,
6289 dynamic
6290 ? BasePermission.TYPE_DYNAMIC
6291 : BasePermission.TYPE_NORMAL);
6292 if (dynamic) {
6293 PermissionInfo pi = new PermissionInfo();
6294 pi.packageName = sourcePackage.intern();
6295 pi.name = name.intern();
6296 pi.icon = readInt(parser, null, "icon", 0);
6297 pi.nonLocalizedLabel = parser.getAttributeValue(
6298 null, "label");
6299 pi.protectionLevel = readInt(parser, null, "protection",
6300 PermissionInfo.PROTECTION_NORMAL);
6301 bp.pendingInfo = pi;
6302 }
6303 out.put(bp.name, bp);
6304 } else {
6305 reportSettingsProblem(Log.WARN,
6306 "Error in package manager settings: permissions has"
6307 + " no name at " + parser.getPositionDescription());
6308 }
6309 } else {
6310 reportSettingsProblem(Log.WARN,
6311 "Unknown element reading permissions: "
6312 + parser.getName() + " at "
6313 + parser.getPositionDescription());
6314 }
6315 XmlUtils.skipCurrentTag(parser);
6316 }
6317 }
6318
6319 private void readDisabledSysPackageLP(XmlPullParser parser)
6320 throws XmlPullParserException, IOException {
6321 String name = parser.getAttributeValue(null, "name");
6322 String codePathStr = parser.getAttributeValue(null, "codePath");
6323 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
6324 if(resourcePathStr == null) {
6325 resourcePathStr = codePathStr;
6326 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006327 String version = parser.getAttributeValue(null, "version");
6328 int versionCode = 0;
6329 if (version != null) {
6330 try {
6331 versionCode = Integer.parseInt(version);
6332 } catch (NumberFormatException e) {
6333 }
6334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335
6336 int pkgFlags = 0;
6337 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6338 PackageSetting ps = new PackageSetting(name,
6339 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006340 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 String timeStampStr = parser.getAttributeValue(null, "ts");
6342 if (timeStampStr != null) {
6343 try {
6344 long timeStamp = Long.parseLong(timeStampStr);
6345 ps.setTimeStamp(timeStamp, timeStampStr);
6346 } catch (NumberFormatException e) {
6347 }
6348 }
6349 String idStr = parser.getAttributeValue(null, "userId");
6350 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
6351 if(ps.userId <= 0) {
6352 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6353 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
6354 }
6355 int outerDepth = parser.getDepth();
6356 int type;
6357 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6358 && (type != XmlPullParser.END_TAG
6359 || parser.getDepth() > outerDepth)) {
6360 if (type == XmlPullParser.END_TAG
6361 || type == XmlPullParser.TEXT) {
6362 continue;
6363 }
6364
6365 String tagName = parser.getName();
6366 if (tagName.equals("perms")) {
6367 readGrantedPermissionsLP(parser,
6368 ps.grantedPermissions);
6369 } else {
6370 reportSettingsProblem(Log.WARN,
6371 "Unknown element under <updated-package>: "
6372 + parser.getName());
6373 XmlUtils.skipCurrentTag(parser);
6374 }
6375 }
6376 mDisabledSysPackages.put(name, ps);
6377 }
6378
6379 private void readPackageLP(XmlPullParser parser)
6380 throws XmlPullParserException, IOException {
6381 String name = null;
6382 String idStr = null;
6383 String sharedIdStr = null;
6384 String codePathStr = null;
6385 String resourcePathStr = null;
6386 String systemStr = null;
Jacek Surazskic64322c2009-04-28 15:26:38 +02006387 String installerPackageName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 int pkgFlags = 0;
6389 String timeStampStr;
6390 long timeStamp = 0;
6391 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006392 String version = null;
6393 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 try {
6395 name = parser.getAttributeValue(null, "name");
6396 idStr = parser.getAttributeValue(null, "userId");
6397 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
6398 codePathStr = parser.getAttributeValue(null, "codePath");
6399 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006400 version = parser.getAttributeValue(null, "version");
6401 if (version != null) {
6402 try {
6403 versionCode = Integer.parseInt(version);
6404 } catch (NumberFormatException e) {
6405 }
6406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 systemStr = parser.getAttributeValue(null, "system");
Jacek Surazskic64322c2009-04-28 15:26:38 +02006408 installerPackageName = parser.getAttributeValue(null, "installer");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 if (systemStr != null) {
6410 if ("true".equals(systemStr)) {
6411 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6412 }
6413 } else {
6414 // Old settings that don't specify system... just treat
6415 // them as system, good enough.
6416 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6417 }
6418 timeStampStr = parser.getAttributeValue(null, "ts");
6419 if (timeStampStr != null) {
6420 try {
6421 timeStamp = Long.parseLong(timeStampStr);
6422 } catch (NumberFormatException e) {
6423 }
6424 }
6425 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
6426 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
6427 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
6428 if (resourcePathStr == null) {
6429 resourcePathStr = codePathStr;
6430 }
6431 if (name == null) {
6432 reportSettingsProblem(Log.WARN,
6433 "Error in package manager settings: <package> has no name at "
6434 + parser.getPositionDescription());
6435 } else if (codePathStr == null) {
6436 reportSettingsProblem(Log.WARN,
6437 "Error in package manager settings: <package> has no codePath at "
6438 + parser.getPositionDescription());
6439 } else if (userId > 0) {
6440 packageSetting = addPackageLP(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006441 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
6443 + ": userId=" + userId + " pkg=" + packageSetting);
6444 if (packageSetting == null) {
6445 reportSettingsProblem(Log.ERROR,
6446 "Failure adding uid " + userId
6447 + " while parsing settings at "
6448 + parser.getPositionDescription());
6449 } else {
6450 packageSetting.setTimeStamp(timeStamp, timeStampStr);
6451 }
6452 } else if (sharedIdStr != null) {
6453 userId = sharedIdStr != null
6454 ? Integer.parseInt(sharedIdStr) : 0;
6455 if (userId > 0) {
6456 packageSetting = new PendingPackage(name.intern(), new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006457 new File(resourcePathStr), userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 packageSetting.setTimeStamp(timeStamp, timeStampStr);
6459 mPendingPackages.add((PendingPackage) packageSetting);
6460 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
6461 + ": sharedUserId=" + userId + " pkg="
6462 + packageSetting);
6463 } else {
6464 reportSettingsProblem(Log.WARN,
6465 "Error in package manager settings: package "
6466 + name + " has bad sharedId " + sharedIdStr
6467 + " at " + parser.getPositionDescription());
6468 }
6469 } else {
6470 reportSettingsProblem(Log.WARN,
6471 "Error in package manager settings: package "
6472 + name + " has bad userId " + idStr + " at "
6473 + parser.getPositionDescription());
6474 }
6475 } catch (NumberFormatException e) {
6476 reportSettingsProblem(Log.WARN,
6477 "Error in package manager settings: package "
6478 + name + " has bad userId " + idStr + " at "
6479 + parser.getPositionDescription());
6480 }
6481 if (packageSetting != null) {
Jacek Surazskic64322c2009-04-28 15:26:38 +02006482 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 final String enabledStr = parser.getAttributeValue(null, "enabled");
6484 if (enabledStr != null) {
6485 if (enabledStr.equalsIgnoreCase("true")) {
6486 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
6487 } else if (enabledStr.equalsIgnoreCase("false")) {
6488 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
6489 } else if (enabledStr.equalsIgnoreCase("default")) {
6490 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6491 } else {
6492 reportSettingsProblem(Log.WARN,
6493 "Error in package manager settings: package "
6494 + name + " has bad enabled value: " + idStr
6495 + " at " + parser.getPositionDescription());
6496 }
6497 } else {
6498 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6499 }
6500 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
6501 if (installStatusStr != null) {
6502 if (installStatusStr.equalsIgnoreCase("false")) {
6503 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
6504 } else {
6505 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
6506 }
6507 }
6508
6509 int outerDepth = parser.getDepth();
6510 int type;
6511 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6512 && (type != XmlPullParser.END_TAG
6513 || parser.getDepth() > outerDepth)) {
6514 if (type == XmlPullParser.END_TAG
6515 || type == XmlPullParser.TEXT) {
6516 continue;
6517 }
6518
6519 String tagName = parser.getName();
6520 if (tagName.equals("disabled-components")) {
6521 readDisabledComponentsLP(packageSetting, parser);
6522 } else if (tagName.equals("enabled-components")) {
6523 readEnabledComponentsLP(packageSetting, parser);
6524 } else if (tagName.equals("sigs")) {
6525 packageSetting.signatures.readXml(parser, mPastSignatures);
6526 } else if (tagName.equals("perms")) {
6527 readGrantedPermissionsLP(parser,
6528 packageSetting.loadedPermissions);
6529 packageSetting.permissionsFixed = true;
6530 } else {
6531 reportSettingsProblem(Log.WARN,
6532 "Unknown element under <package>: "
6533 + parser.getName());
6534 XmlUtils.skipCurrentTag(parser);
6535 }
6536 }
6537 } else {
6538 XmlUtils.skipCurrentTag(parser);
6539 }
6540 }
6541
6542 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
6543 XmlPullParser parser)
6544 throws IOException, XmlPullParserException {
6545 int outerDepth = parser.getDepth();
6546 int type;
6547 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6548 && (type != XmlPullParser.END_TAG
6549 || parser.getDepth() > outerDepth)) {
6550 if (type == XmlPullParser.END_TAG
6551 || type == XmlPullParser.TEXT) {
6552 continue;
6553 }
6554
6555 String tagName = parser.getName();
6556 if (tagName.equals("item")) {
6557 String name = parser.getAttributeValue(null, "name");
6558 if (name != null) {
6559 packageSetting.disabledComponents.add(name.intern());
6560 } else {
6561 reportSettingsProblem(Log.WARN,
6562 "Error in package manager settings: <disabled-components> has"
6563 + " no name at " + parser.getPositionDescription());
6564 }
6565 } else {
6566 reportSettingsProblem(Log.WARN,
6567 "Unknown element under <disabled-components>: "
6568 + parser.getName());
6569 }
6570 XmlUtils.skipCurrentTag(parser);
6571 }
6572 }
6573
6574 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
6575 XmlPullParser parser)
6576 throws IOException, XmlPullParserException {
6577 int outerDepth = parser.getDepth();
6578 int type;
6579 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6580 && (type != XmlPullParser.END_TAG
6581 || parser.getDepth() > outerDepth)) {
6582 if (type == XmlPullParser.END_TAG
6583 || type == XmlPullParser.TEXT) {
6584 continue;
6585 }
6586
6587 String tagName = parser.getName();
6588 if (tagName.equals("item")) {
6589 String name = parser.getAttributeValue(null, "name");
6590 if (name != null) {
6591 packageSetting.enabledComponents.add(name.intern());
6592 } else {
6593 reportSettingsProblem(Log.WARN,
6594 "Error in package manager settings: <enabled-components> has"
6595 + " no name at " + parser.getPositionDescription());
6596 }
6597 } else {
6598 reportSettingsProblem(Log.WARN,
6599 "Unknown element under <enabled-components>: "
6600 + parser.getName());
6601 }
6602 XmlUtils.skipCurrentTag(parser);
6603 }
6604 }
6605
6606 private void readSharedUserLP(XmlPullParser parser)
6607 throws XmlPullParserException, IOException {
6608 String name = null;
6609 String idStr = null;
6610 int pkgFlags = 0;
6611 SharedUserSetting su = null;
6612 try {
6613 name = parser.getAttributeValue(null, "name");
6614 idStr = parser.getAttributeValue(null, "userId");
6615 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
6616 if ("true".equals(parser.getAttributeValue(null, "system"))) {
6617 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
6618 }
6619 if (name == null) {
6620 reportSettingsProblem(Log.WARN,
6621 "Error in package manager settings: <shared-user> has no name at "
6622 + parser.getPositionDescription());
6623 } else if (userId == 0) {
6624 reportSettingsProblem(Log.WARN,
6625 "Error in package manager settings: shared-user "
6626 + name + " has bad userId " + idStr + " at "
6627 + parser.getPositionDescription());
6628 } else {
6629 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
6630 reportSettingsProblem(Log.ERROR,
6631 "Occurred while parsing settings at "
6632 + parser.getPositionDescription());
6633 }
6634 }
6635 } catch (NumberFormatException e) {
6636 reportSettingsProblem(Log.WARN,
6637 "Error in package manager settings: package "
6638 + name + " has bad userId " + idStr + " at "
6639 + parser.getPositionDescription());
6640 };
6641
6642 if (su != null) {
6643 int outerDepth = parser.getDepth();
6644 int type;
6645 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6646 && (type != XmlPullParser.END_TAG
6647 || parser.getDepth() > outerDepth)) {
6648 if (type == XmlPullParser.END_TAG
6649 || type == XmlPullParser.TEXT) {
6650 continue;
6651 }
6652
6653 String tagName = parser.getName();
6654 if (tagName.equals("sigs")) {
6655 su.signatures.readXml(parser, mPastSignatures);
6656 } else if (tagName.equals("perms")) {
6657 readGrantedPermissionsLP(parser, su.loadedPermissions);
6658 } else {
6659 reportSettingsProblem(Log.WARN,
6660 "Unknown element under <shared-user>: "
6661 + parser.getName());
6662 XmlUtils.skipCurrentTag(parser);
6663 }
6664 }
6665
6666 } else {
6667 XmlUtils.skipCurrentTag(parser);
6668 }
6669 }
6670
6671 private void readGrantedPermissionsLP(XmlPullParser parser,
6672 HashSet<String> outPerms) throws IOException, XmlPullParserException {
6673 int outerDepth = parser.getDepth();
6674 int type;
6675 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6676 && (type != XmlPullParser.END_TAG
6677 || parser.getDepth() > outerDepth)) {
6678 if (type == XmlPullParser.END_TAG
6679 || type == XmlPullParser.TEXT) {
6680 continue;
6681 }
6682
6683 String tagName = parser.getName();
6684 if (tagName.equals("item")) {
6685 String name = parser.getAttributeValue(null, "name");
6686 if (name != null) {
6687 outPerms.add(name.intern());
6688 } else {
6689 reportSettingsProblem(Log.WARN,
6690 "Error in package manager settings: <perms> has"
6691 + " no name at " + parser.getPositionDescription());
6692 }
6693 } else {
6694 reportSettingsProblem(Log.WARN,
6695 "Unknown element under <perms>: "
6696 + parser.getName());
6697 }
6698 XmlUtils.skipCurrentTag(parser);
6699 }
6700 }
6701
6702 private void readPreferredPackagesLP(XmlPullParser parser)
6703 throws XmlPullParserException, IOException {
6704 int outerDepth = parser.getDepth();
6705 int type;
6706 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6707 && (type != XmlPullParser.END_TAG
6708 || parser.getDepth() > outerDepth)) {
6709 if (type == XmlPullParser.END_TAG
6710 || type == XmlPullParser.TEXT) {
6711 continue;
6712 }
6713
6714 String tagName = parser.getName();
6715 if (tagName.equals("item")) {
6716 String name = parser.getAttributeValue(null, "name");
6717 if (name != null) {
6718 mPendingPreferredPackages.add(name);
6719 } else {
6720 reportSettingsProblem(Log.WARN,
6721 "Error in package manager settings: <preferred-package> has no name at "
6722 + parser.getPositionDescription());
6723 }
6724 } else {
6725 reportSettingsProblem(Log.WARN,
6726 "Unknown element under <preferred-packages>: "
6727 + parser.getName());
6728 }
6729 XmlUtils.skipCurrentTag(parser);
6730 }
6731 }
6732
6733 private void readPreferredActivitiesLP(XmlPullParser parser)
6734 throws XmlPullParserException, IOException {
6735 int outerDepth = parser.getDepth();
6736 int type;
6737 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6738 && (type != XmlPullParser.END_TAG
6739 || parser.getDepth() > outerDepth)) {
6740 if (type == XmlPullParser.END_TAG
6741 || type == XmlPullParser.TEXT) {
6742 continue;
6743 }
6744
6745 String tagName = parser.getName();
6746 if (tagName.equals("item")) {
6747 PreferredActivity pa = new PreferredActivity(parser);
6748 if (pa.mParseError == null) {
6749 mPreferredActivities.addFilter(pa);
6750 } else {
6751 reportSettingsProblem(Log.WARN,
6752 "Error in package manager settings: <preferred-activity> "
6753 + pa.mParseError + " at "
6754 + parser.getPositionDescription());
6755 }
6756 } else {
6757 reportSettingsProblem(Log.WARN,
6758 "Unknown element under <preferred-activities>: "
6759 + parser.getName());
6760 XmlUtils.skipCurrentTag(parser);
6761 }
6762 }
6763 }
6764
6765 // Returns -1 if we could not find an available UserId to assign
6766 private int newUserIdLP(Object obj) {
6767 // Let's be stupidly inefficient for now...
6768 final int N = mUserIds.size();
6769 for (int i=0; i<N; i++) {
6770 if (mUserIds.get(i) == null) {
6771 mUserIds.set(i, obj);
6772 return FIRST_APPLICATION_UID + i;
6773 }
6774 }
6775
6776 // None left?
6777 if (N >= MAX_APPLICATION_UIDS) {
6778 return -1;
6779 }
6780
6781 mUserIds.add(obj);
6782 return FIRST_APPLICATION_UID + N;
6783 }
6784
6785 public PackageSetting getDisabledSystemPkg(String name) {
6786 synchronized(mPackages) {
6787 PackageSetting ps = mDisabledSysPackages.get(name);
6788 return ps;
6789 }
6790 }
6791
6792 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
6793 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
6794 if (Config.LOGV) {
6795 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
6796 + " componentName = " + componentInfo.name);
6797 Log.v(TAG, "enabledComponents: "
6798 + Arrays.toString(packageSettings.enabledComponents.toArray()));
6799 Log.v(TAG, "disabledComponents: "
6800 + Arrays.toString(packageSettings.disabledComponents.toArray()));
6801 }
6802 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
6803 || ((componentInfo.enabled
6804 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
6805 || (componentInfo.applicationInfo.enabled
6806 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
6807 && !packageSettings.disabledComponents.contains(componentInfo.name))
6808 || packageSettings.enabledComponents.contains(componentInfo.name));
6809 }
6810 }
6811}