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