PackageManagerService.java revision 706e8ba26bf0de19ad5f736516dae40c4c88c2d7
1/* 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.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 25import static com.android.internal.util.ArrayUtils.appendInt; 26import static com.android.internal.util.ArrayUtils.removeInt; 27import static libcore.io.OsConstants.S_ISLNK; 28 29import com.android.internal.app.IMediaContainerService; 30import com.android.internal.app.ResolverActivity; 31import com.android.internal.content.NativeLibraryHelper; 32import com.android.internal.content.PackageHelper; 33import com.android.internal.util.FastXmlSerializer; 34import com.android.internal.util.XmlUtils; 35import com.android.server.DeviceStorageMonitorService; 36import com.android.server.EventLogTags; 37import com.android.server.IntentResolver; 38 39import org.xmlpull.v1.XmlPullParser; 40import org.xmlpull.v1.XmlPullParserException; 41import org.xmlpull.v1.XmlSerializer; 42 43import android.app.ActivityManagerNative; 44import android.app.IActivityManager; 45import android.app.admin.IDevicePolicyManager; 46import android.app.backup.IBackupManager; 47import android.content.BroadcastReceiver; 48import android.content.ComponentName; 49import android.content.Context; 50import android.content.IIntentReceiver; 51import android.content.Intent; 52import android.content.IntentFilter; 53import android.content.IntentSender; 54import android.content.ServiceConnection; 55import android.content.IntentSender.SendIntentException; 56import android.content.pm.ActivityInfo; 57import android.content.pm.ApplicationInfo; 58import android.content.pm.ContainerEncryptionParams; 59import android.content.pm.FeatureInfo; 60import android.content.pm.IPackageDataObserver; 61import android.content.pm.IPackageDeleteObserver; 62import android.content.pm.IPackageInstallObserver; 63import android.content.pm.IPackageManager; 64import android.content.pm.IPackageMoveObserver; 65import android.content.pm.IPackageStatsObserver; 66import android.content.pm.InstrumentationInfo; 67import android.content.pm.PackageInfo; 68import android.content.pm.PackageInfoLite; 69import android.content.pm.PackageManager; 70import android.content.pm.PackageParser; 71import android.content.pm.UserInfo; 72import android.content.pm.PackageParser.ActivityIntentInfo; 73import android.content.pm.PackageStats; 74import android.content.pm.ParceledListSlice; 75import android.content.pm.PermissionGroupInfo; 76import android.content.pm.PermissionInfo; 77import android.content.pm.ProviderInfo; 78import android.content.pm.ResolveInfo; 79import android.content.pm.ServiceInfo; 80import android.content.pm.Signature; 81import android.content.pm.ManifestDigest; 82import android.content.pm.VerificationParams; 83import android.content.pm.VerifierDeviceIdentity; 84import android.content.pm.VerifierInfo; 85import android.net.Uri; 86import android.os.Binder; 87import android.os.Build; 88import android.os.Bundle; 89import android.os.Environment; 90import android.os.FileObserver; 91import android.os.FileUtils; 92import android.os.Handler; 93import android.os.HandlerThread; 94import android.os.IBinder; 95import android.os.Looper; 96import android.os.Message; 97import android.os.Parcel; 98import android.os.ParcelFileDescriptor; 99import android.os.Process; 100import android.os.RemoteException; 101import android.os.SELinux; 102import android.os.ServiceManager; 103import android.os.SystemClock; 104import android.os.SystemProperties; 105import android.os.UserHandle; 106import android.os.UserManager; 107import android.provider.Settings.Secure; 108import android.security.SystemKeyStore; 109import android.util.DisplayMetrics; 110import android.util.EventLog; 111import android.util.Log; 112import android.util.LogPrinter; 113import android.util.Slog; 114import android.util.SparseArray; 115import android.util.Xml; 116import android.view.Display; 117import android.view.WindowManager; 118 119import java.io.BufferedOutputStream; 120import java.io.File; 121import java.io.FileDescriptor; 122import java.io.FileInputStream; 123import java.io.FileNotFoundException; 124import java.io.FileOutputStream; 125import java.io.FileReader; 126import java.io.FilenameFilter; 127import java.io.IOException; 128import java.io.PrintWriter; 129import java.security.NoSuchAlgorithmException; 130import java.security.PublicKey; 131import java.security.cert.CertificateException; 132import java.text.SimpleDateFormat; 133import java.util.ArrayList; 134import java.util.Arrays; 135import java.util.Collection; 136import java.util.Collections; 137import java.util.Comparator; 138import java.util.Date; 139import java.util.HashMap; 140import java.util.HashSet; 141import java.util.Iterator; 142import java.util.List; 143import java.util.Map; 144import java.util.Map.Entry; 145import java.util.Set; 146 147import libcore.io.ErrnoException; 148import libcore.io.IoUtils; 149import libcore.io.Libcore; 150import libcore.io.StructStat; 151 152/** 153 * Keep track of all those .apks everywhere. 154 * 155 * This is very central to the platform's security; please run the unit 156 * tests whenever making modifications here: 157 * 158mmm frameworks/base/tests/AndroidTests 159adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 160adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 161 * 162 * {@hide} 163 */ 164public class PackageManagerService extends IPackageManager.Stub { 165 static final String TAG = "PackageManager"; 166 static final boolean DEBUG_SETTINGS = false; 167 private static final boolean DEBUG_PREFERRED = false; 168 static final boolean DEBUG_UPGRADE = false; 169 private static final boolean DEBUG_INSTALL = false; 170 private static final boolean DEBUG_REMOVE = false; 171 private static final boolean DEBUG_SHOW_INFO = false; 172 private static final boolean DEBUG_PACKAGE_INFO = false; 173 private static final boolean DEBUG_INTENT_MATCHING = false; 174 private static final boolean DEBUG_PACKAGE_SCANNING = false; 175 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 176 private static final boolean DEBUG_VERIFY = false; 177 178 private static final int RADIO_UID = Process.PHONE_UID; 179 private static final int LOG_UID = Process.LOG_UID; 180 private static final int NFC_UID = Process.NFC_UID; 181 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 182 183 private static final boolean GET_CERTIFICATES = true; 184 185 private static final int REMOVE_EVENTS = 186 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 187 private static final int ADD_EVENTS = 188 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 189 190 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 191 // Suffix used during package installation when copying/moving 192 // package apks to install directory. 193 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 194 195 static final int SCAN_MONITOR = 1<<0; 196 static final int SCAN_NO_DEX = 1<<1; 197 static final int SCAN_FORCE_DEX = 1<<2; 198 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 199 static final int SCAN_NEW_INSTALL = 1<<4; 200 static final int SCAN_NO_PATHS = 1<<5; 201 static final int SCAN_UPDATE_TIME = 1<<6; 202 static final int SCAN_DEFER_DEX = 1<<7; 203 static final int SCAN_BOOTING = 1<<8; 204 205 static final int REMOVE_CHATTY = 1<<16; 206 207 /** 208 * Whether verification is enabled by default. 209 */ 210 // STOPSHIP: change this to true 211 private static final boolean DEFAULT_VERIFY_ENABLE = false; 212 213 /** 214 * The default maximum time to wait for the verification agent to return in 215 * milliseconds. 216 */ 217 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 218 219 /** 220 * The default response for package verification timeout. 221 * 222 * This can be either PackageManager.VERIFICATION_ALLOW or 223 * PackageManager.VERIFICATION_REJECT. 224 */ 225 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 226 227 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 228 229 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 230 DEFAULT_CONTAINER_PACKAGE, 231 "com.android.defcontainer.DefaultContainerService"); 232 233 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 234 235 private static final String LIB_DIR_NAME = "lib"; 236 237 static final String mTempContainerPrefix = "smdl2tmp"; 238 239 final HandlerThread mHandlerThread = new HandlerThread("PackageManager", 240 Process.THREAD_PRIORITY_BACKGROUND); 241 final PackageHandler mHandler; 242 243 final int mSdkVersion = Build.VERSION.SDK_INT; 244 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME) 245 ? null : Build.VERSION.CODENAME; 246 247 final Context mContext; 248 final boolean mFactoryTest; 249 final boolean mOnlyCore; 250 final boolean mNoDexOpt; 251 final DisplayMetrics mMetrics; 252 final int mDefParseFlags; 253 final String[] mSeparateProcesses; 254 255 // This is where all application persistent data goes. 256 final File mAppDataDir; 257 258 // This is where all application persistent data goes for secondary users. 259 final File mUserAppDataDir; 260 261 /** The location for ASEC container files on internal storage. */ 262 final String mAsecInternalPath; 263 264 // This is the object monitoring the framework dir. 265 final FileObserver mFrameworkInstallObserver; 266 267 // This is the object monitoring the system app dir. 268 final FileObserver mSystemInstallObserver; 269 270 // This is the object monitoring the system app dir. 271 final FileObserver mVendorInstallObserver; 272 273 // This is the object monitoring mAppInstallDir. 274 final FileObserver mAppInstallObserver; 275 276 // This is the object monitoring mDrmAppPrivateInstallDir. 277 final FileObserver mDrmAppInstallObserver; 278 279 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages 280 // LOCK HELD. Can be called with mInstallLock held. 281 final Installer mInstaller; 282 283 final File mFrameworkDir; 284 final File mSystemAppDir; 285 final File mVendorAppDir; 286 final File mAppInstallDir; 287 final File mDalvikCacheDir; 288 289 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 290 // apps. 291 final File mDrmAppPrivateInstallDir; 292 293 // ---------------------------------------------------------------- 294 295 // Lock for state used when installing and doing other long running 296 // operations. Methods that must be called with this lock held have 297 // the prefix "LI". 298 final Object mInstallLock = new Object(); 299 300 // These are the directories in the 3rd party applications installed dir 301 // that we have currently loaded packages from. Keys are the application's 302 // installed zip file (absolute codePath), and values are Package. 303 final HashMap<String, PackageParser.Package> mAppDirs = 304 new HashMap<String, PackageParser.Package>(); 305 306 // Information for the parser to write more useful error messages. 307 File mScanningPath; 308 int mLastScanError; 309 310 // ---------------------------------------------------------------- 311 312 // Keys are String (package name), values are Package. This also serves 313 // as the lock for the global state. Methods that must be called with 314 // this lock held have the prefix "LP". 315 final HashMap<String, PackageParser.Package> mPackages = 316 new HashMap<String, PackageParser.Package>(); 317 318 final Settings mSettings; 319 boolean mRestoredSettings; 320 321 // Group-ids that are given to all packages as read from etc/permissions/*.xml. 322 int[] mGlobalGids; 323 324 // These are the built-in uid -> permission mappings that were read from the 325 // etc/permissions.xml file. 326 final SparseArray<HashSet<String>> mSystemPermissions = 327 new SparseArray<HashSet<String>>(); 328 329 // These are the built-in shared libraries that were read from the 330 // etc/permissions.xml file. 331 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>(); 332 333 // Temporary for building the final shared libraries for an .apk. 334 String[] mTmpSharedLibraries = null; 335 336 // These are the features this devices supports that were read from the 337 // etc/permissions.xml file. 338 final HashMap<String, FeatureInfo> mAvailableFeatures = 339 new HashMap<String, FeatureInfo>(); 340 341 // All available activities, for your resolving pleasure. 342 final ActivityIntentResolver mActivities = 343 new ActivityIntentResolver(); 344 345 // All available receivers, for your resolving pleasure. 346 final ActivityIntentResolver mReceivers = 347 new ActivityIntentResolver(); 348 349 // All available services, for your resolving pleasure. 350 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 351 352 // Keys are String (provider class name), values are Provider. 353 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent = 354 new HashMap<ComponentName, PackageParser.Provider>(); 355 356 // Mapping from provider base names (first directory in content URI codePath) 357 // to the provider information. 358 final HashMap<String, PackageParser.Provider> mProviders = 359 new HashMap<String, PackageParser.Provider>(); 360 361 // Mapping from instrumentation class names to info about them. 362 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 363 new HashMap<ComponentName, PackageParser.Instrumentation>(); 364 365 // Mapping from permission names to info about them. 366 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 367 new HashMap<String, PackageParser.PermissionGroup>(); 368 369 // Packages whose data we have transfered into another package, thus 370 // should no longer exist. 371 final HashSet<String> mTransferedPackages = new HashSet<String>(); 372 373 // Broadcast actions that are only available to the system. 374 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 375 376 /** List of packages waiting for verification. */ 377 final SparseArray<PackageVerificationState> mPendingVerification 378 = new SparseArray<PackageVerificationState>(); 379 380 final ArrayList<PackageParser.Package> mDeferredDexOpt = 381 new ArrayList<PackageParser.Package>(); 382 383 /** Token for keys in mPendingVerification. */ 384 private int mPendingVerificationToken = 0; 385 386 boolean mSystemReady; 387 boolean mSafeMode; 388 boolean mHasSystemUidErrors; 389 390 ApplicationInfo mAndroidApplication; 391 final ActivityInfo mResolveActivity = new ActivityInfo(); 392 final ResolveInfo mResolveInfo = new ResolveInfo(); 393 ComponentName mResolveComponentName; 394 PackageParser.Package mPlatformPackage; 395 396 // Set of pending broadcasts for aggregating enable/disable of components. 397 final HashMap<String, ArrayList<String>> mPendingBroadcasts 398 = new HashMap<String, ArrayList<String>>(); 399 // Service Connection to remote media container service to copy 400 // package uri's from external media onto secure containers 401 // or internal storage. 402 private IMediaContainerService mContainerService = null; 403 404 static final int SEND_PENDING_BROADCAST = 1; 405 static final int MCS_BOUND = 3; 406 static final int END_COPY = 4; 407 static final int INIT_COPY = 5; 408 static final int MCS_UNBIND = 6; 409 static final int START_CLEANING_PACKAGE = 7; 410 static final int FIND_INSTALL_LOC = 8; 411 static final int POST_INSTALL = 9; 412 static final int MCS_RECONNECT = 10; 413 static final int MCS_GIVE_UP = 11; 414 static final int UPDATED_MEDIA_STATUS = 12; 415 static final int WRITE_SETTINGS = 13; 416 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 417 static final int PACKAGE_VERIFIED = 15; 418 static final int CHECK_PENDING_VERIFICATION = 16; 419 420 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 421 422 // Delay time in millisecs 423 static final int BROADCAST_DELAY = 10 * 1000; 424 425 static UserManagerService sUserManager; 426 427 // Stores a list of users whose package restrictions file needs to be updated 428 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 429 430 final private DefaultContainerConnection mDefContainerConn = 431 new DefaultContainerConnection(); 432 class DefaultContainerConnection implements ServiceConnection { 433 public void onServiceConnected(ComponentName name, IBinder service) { 434 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 435 IMediaContainerService imcs = 436 IMediaContainerService.Stub.asInterface(service); 437 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 438 } 439 440 public void onServiceDisconnected(ComponentName name) { 441 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 442 } 443 }; 444 445 // Recordkeeping of restore-after-install operations that are currently in flight 446 // between the Package Manager and the Backup Manager 447 class PostInstallData { 448 public InstallArgs args; 449 public PackageInstalledInfo res; 450 451 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 452 args = _a; 453 res = _r; 454 } 455 }; 456 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 457 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 458 459 private final String mRequiredVerifierPackage; 460 461 class PackageHandler extends Handler { 462 private boolean mBound = false; 463 final ArrayList<HandlerParams> mPendingInstalls = 464 new ArrayList<HandlerParams>(); 465 466 private boolean connectToService() { 467 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 468 " DefaultContainerService"); 469 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 470 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 471 if (mContext.bindService(service, mDefContainerConn, 472 Context.BIND_AUTO_CREATE)) { 473 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 474 mBound = true; 475 return true; 476 } 477 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 478 return false; 479 } 480 481 private void disconnectService() { 482 mContainerService = null; 483 mBound = false; 484 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 485 mContext.unbindService(mDefContainerConn); 486 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 487 } 488 489 PackageHandler(Looper looper) { 490 super(looper); 491 } 492 493 public void handleMessage(Message msg) { 494 try { 495 doHandleMessage(msg); 496 } finally { 497 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 498 } 499 } 500 501 void doHandleMessage(Message msg) { 502 switch (msg.what) { 503 case INIT_COPY: { 504 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy"); 505 HandlerParams params = (HandlerParams) msg.obj; 506 int idx = mPendingInstalls.size(); 507 if (DEBUG_INSTALL) Slog.i(TAG, "idx=" + idx); 508 // If a bind was already initiated we dont really 509 // need to do anything. The pending install 510 // will be processed later on. 511 if (!mBound) { 512 // If this is the only one pending we might 513 // have to bind to the service again. 514 if (!connectToService()) { 515 Slog.e(TAG, "Failed to bind to media container service"); 516 params.serviceError(); 517 return; 518 } else { 519 // Once we bind to the service, the first 520 // pending request will be processed. 521 mPendingInstalls.add(idx, params); 522 } 523 } else { 524 mPendingInstalls.add(idx, params); 525 // Already bound to the service. Just make 526 // sure we trigger off processing the first request. 527 if (idx == 0) { 528 mHandler.sendEmptyMessage(MCS_BOUND); 529 } 530 } 531 break; 532 } 533 case MCS_BOUND: { 534 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 535 if (msg.obj != null) { 536 mContainerService = (IMediaContainerService) msg.obj; 537 } 538 if (mContainerService == null) { 539 // Something seriously wrong. Bail out 540 Slog.e(TAG, "Cannot bind to media container service"); 541 for (HandlerParams params : mPendingInstalls) { 542 // Indicate service bind error 543 params.serviceError(); 544 } 545 mPendingInstalls.clear(); 546 } else if (mPendingInstalls.size() > 0) { 547 HandlerParams params = mPendingInstalls.get(0); 548 if (params != null) { 549 if (params.startCopy()) { 550 // We are done... look for more work or to 551 // go idle. 552 if (DEBUG_SD_INSTALL) Log.i(TAG, 553 "Checking for more work or unbind..."); 554 // Delete pending install 555 if (mPendingInstalls.size() > 0) { 556 mPendingInstalls.remove(0); 557 } 558 if (mPendingInstalls.size() == 0) { 559 if (mBound) { 560 if (DEBUG_SD_INSTALL) Log.i(TAG, 561 "Posting delayed MCS_UNBIND"); 562 removeMessages(MCS_UNBIND); 563 Message ubmsg = obtainMessage(MCS_UNBIND); 564 // Unbind after a little delay, to avoid 565 // continual thrashing. 566 sendMessageDelayed(ubmsg, 10000); 567 } 568 } else { 569 // There are more pending requests in queue. 570 // Just post MCS_BOUND message to trigger processing 571 // of next pending install. 572 if (DEBUG_SD_INSTALL) Log.i(TAG, 573 "Posting MCS_BOUND for next woek"); 574 mHandler.sendEmptyMessage(MCS_BOUND); 575 } 576 } 577 } 578 } else { 579 // Should never happen ideally. 580 Slog.w(TAG, "Empty queue"); 581 } 582 break; 583 } 584 case MCS_RECONNECT: { 585 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 586 if (mPendingInstalls.size() > 0) { 587 if (mBound) { 588 disconnectService(); 589 } 590 if (!connectToService()) { 591 Slog.e(TAG, "Failed to bind to media container service"); 592 for (HandlerParams params : mPendingInstalls) { 593 // Indicate service bind error 594 params.serviceError(); 595 } 596 mPendingInstalls.clear(); 597 } 598 } 599 break; 600 } 601 case MCS_UNBIND: { 602 // If there is no actual work left, then time to unbind. 603 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 604 605 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 606 if (mBound) { 607 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 608 609 disconnectService(); 610 } 611 } else if (mPendingInstalls.size() > 0) { 612 // There are more pending requests in queue. 613 // Just post MCS_BOUND message to trigger processing 614 // of next pending install. 615 mHandler.sendEmptyMessage(MCS_BOUND); 616 } 617 618 break; 619 } 620 case MCS_GIVE_UP: { 621 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 622 mPendingInstalls.remove(0); 623 break; 624 } 625 case SEND_PENDING_BROADCAST: { 626 String packages[]; 627 ArrayList<String> components[]; 628 int size = 0; 629 int uids[]; 630 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 631 synchronized (mPackages) { 632 if (mPendingBroadcasts == null) { 633 return; 634 } 635 size = mPendingBroadcasts.size(); 636 if (size <= 0) { 637 // Nothing to be done. Just return 638 return; 639 } 640 packages = new String[size]; 641 components = new ArrayList[size]; 642 uids = new int[size]; 643 Iterator<Map.Entry<String, ArrayList<String>>> 644 it = mPendingBroadcasts.entrySet().iterator(); 645 int i = 0; 646 while (it.hasNext() && i < size) { 647 Map.Entry<String, ArrayList<String>> ent = it.next(); 648 packages[i] = ent.getKey(); 649 components[i] = ent.getValue(); 650 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 651 uids[i] = (ps != null) ? ps.appId : -1; 652 i++; 653 } 654 size = i; 655 mPendingBroadcasts.clear(); 656 } 657 // Send broadcasts 658 for (int i = 0; i < size; i++) { 659 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 660 } 661 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 662 break; 663 } 664 case START_CLEANING_PACKAGE: { 665 String packageName = (String)msg.obj; 666 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 667 synchronized (mPackages) { 668 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) { 669 mSettings.mPackagesToBeCleaned.add(packageName); 670 } 671 } 672 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 673 startCleaningPackages(); 674 } break; 675 case POST_INSTALL: { 676 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 677 PostInstallData data = mRunningInstalls.get(msg.arg1); 678 mRunningInstalls.delete(msg.arg1); 679 boolean deleteOld = false; 680 681 if (data != null) { 682 InstallArgs args = data.args; 683 PackageInstalledInfo res = data.res; 684 685 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 686 res.removedInfo.sendBroadcast(false, true); 687 Bundle extras = new Bundle(1); 688 extras.putInt(Intent.EXTRA_UID, res.uid); 689 final boolean update = res.removedInfo.removedPackage != null; 690 if (update) { 691 extras.putBoolean(Intent.EXTRA_REPLACING, true); 692 } 693 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 694 res.pkg.applicationInfo.packageName, 695 extras, null, null, UserHandle.USER_ALL); 696 if (update) { 697 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 698 res.pkg.applicationInfo.packageName, 699 extras, null, null, UserHandle.USER_ALL); 700 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 701 null, null, 702 res.pkg.applicationInfo.packageName, null, 703 UserHandle.USER_ALL); 704 } 705 if (res.removedInfo.args != null) { 706 // Remove the replaced package's older resources safely now 707 deleteOld = true; 708 } 709 710 // Log current value of "unknown sources" setting 711 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 712 getUnknownSourcesSettings()); 713 } 714 // Force a gc to clear up things 715 Runtime.getRuntime().gc(); 716 // We delete after a gc for applications on sdcard. 717 if (deleteOld) { 718 synchronized (mInstallLock) { 719 res.removedInfo.args.doPostDeleteLI(true); 720 } 721 } 722 if (args.observer != null) { 723 try { 724 args.observer.packageInstalled(res.name, res.returnCode); 725 } catch (RemoteException e) { 726 Slog.i(TAG, "Observer no longer exists."); 727 } 728 } 729 } else { 730 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 731 } 732 } break; 733 case UPDATED_MEDIA_STATUS: { 734 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 735 boolean reportStatus = msg.arg1 == 1; 736 boolean doGc = msg.arg2 == 1; 737 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 738 if (doGc) { 739 // Force a gc to clear up stale containers. 740 Runtime.getRuntime().gc(); 741 } 742 if (msg.obj != null) { 743 @SuppressWarnings("unchecked") 744 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 745 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 746 // Unload containers 747 unloadAllContainers(args); 748 } 749 if (reportStatus) { 750 try { 751 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 752 PackageHelper.getMountService().finishMediaUpdate(); 753 } catch (RemoteException e) { 754 Log.e(TAG, "MountService not running?"); 755 } 756 } 757 } break; 758 case WRITE_SETTINGS: { 759 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 760 synchronized (mPackages) { 761 removeMessages(WRITE_SETTINGS); 762 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 763 mSettings.writeLPr(); 764 mDirtyUsers.clear(); 765 } 766 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 767 } break; 768 case WRITE_PACKAGE_RESTRICTIONS: { 769 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 770 synchronized (mPackages) { 771 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 772 for (int userId : mDirtyUsers) { 773 mSettings.writePackageRestrictionsLPr(userId); 774 } 775 mDirtyUsers.clear(); 776 } 777 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 778 } break; 779 case CHECK_PENDING_VERIFICATION: { 780 final int verificationId = msg.arg1; 781 final PackageVerificationState state = mPendingVerification.get(verificationId); 782 783 if (state != null) { 784 final InstallArgs args = state.getInstallArgs(); 785 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 786 mPendingVerification.remove(verificationId); 787 788 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 789 790 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 791 Slog.i(TAG, "Continuing with installation of " + args.packageURI.toString()); 792 state.setVerifierResponse(Binder.getCallingUid(), PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 793 try { 794 ret = args.copyApk(mContainerService, true); 795 } catch (RemoteException e) { 796 Slog.e(TAG, "Could not contact the ContainerService"); 797 } 798 } 799 800 processPendingInstall(args, ret); 801 802 mHandler.sendEmptyMessage(MCS_UNBIND); 803 } 804 805 break; 806 } 807 case PACKAGE_VERIFIED: { 808 final int verificationId = msg.arg1; 809 810 final PackageVerificationState state = mPendingVerification.get(verificationId); 811 if (state == null) { 812 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 813 break; 814 } 815 816 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 817 818 state.setVerifierResponse(response.callerUid, response.code); 819 820 if (state.isVerificationComplete()) { 821 mPendingVerification.remove(verificationId); 822 823 final InstallArgs args = state.getInstallArgs(); 824 825 int ret; 826 if (state.isInstallAllowed()) { 827 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 828 try { 829 ret = args.copyApk(mContainerService, true); 830 } catch (RemoteException e) { 831 Slog.e(TAG, "Could not contact the ContainerService"); 832 } 833 } else { 834 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 835 } 836 837 processPendingInstall(args, ret); 838 839 mHandler.sendEmptyMessage(MCS_UNBIND); 840 } 841 842 break; 843 } 844 } 845 } 846 } 847 848 void scheduleWriteSettingsLocked() { 849 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 850 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 851 } 852 } 853 854 void scheduleWritePackageRestrictionsLocked(int userId) { 855 if (!sUserManager.exists(userId)) return; 856 mDirtyUsers.add(userId); 857 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 858 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 859 } 860 } 861 862 public static final IPackageManager main(Context context, boolean factoryTest, 863 boolean onlyCore) { 864 PackageManagerService m = new PackageManagerService(context, factoryTest, onlyCore); 865 ServiceManager.addService("package", m); 866 return m; 867 } 868 869 static String[] splitString(String str, char sep) { 870 int count = 1; 871 int i = 0; 872 while ((i=str.indexOf(sep, i)) >= 0) { 873 count++; 874 i++; 875 } 876 877 String[] res = new String[count]; 878 i=0; 879 count = 0; 880 int lastI=0; 881 while ((i=str.indexOf(sep, i)) >= 0) { 882 res[count] = str.substring(lastI, i); 883 count++; 884 i++; 885 lastI = i; 886 } 887 res[count] = str.substring(lastI, str.length()); 888 return res; 889 } 890 891 public PackageManagerService(Context context, boolean factoryTest, boolean onlyCore) { 892 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 893 SystemClock.uptimeMillis()); 894 895 if (mSdkVersion <= 0) { 896 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 897 } 898 899 mContext = context; 900 mFactoryTest = factoryTest; 901 mOnlyCore = onlyCore; 902 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 903 mMetrics = new DisplayMetrics(); 904 mSettings = new Settings(context); 905 mSettings.addSharedUserLPw("android.uid.system", 906 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM); 907 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, ApplicationInfo.FLAG_SYSTEM); 908 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, ApplicationInfo.FLAG_SYSTEM); 909 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, ApplicationInfo.FLAG_SYSTEM); 910 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, ApplicationInfo.FLAG_SYSTEM); 911 912 String separateProcesses = SystemProperties.get("debug.separate_processes"); 913 if (separateProcesses != null && separateProcesses.length() > 0) { 914 if ("*".equals(separateProcesses)) { 915 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 916 mSeparateProcesses = null; 917 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 918 } else { 919 mDefParseFlags = 0; 920 mSeparateProcesses = separateProcesses.split(","); 921 Slog.w(TAG, "Running with debug.separate_processes: " 922 + separateProcesses); 923 } 924 } else { 925 mDefParseFlags = 0; 926 mSeparateProcesses = null; 927 } 928 929 mInstaller = new Installer(); 930 931 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); 932 Display d = wm.getDefaultDisplay(); 933 d.getMetrics(mMetrics); 934 935 synchronized (mInstallLock) { 936 // writer 937 synchronized (mPackages) { 938 mHandlerThread.start(); 939 mHandler = new PackageHandler(mHandlerThread.getLooper()); 940 941 File dataDir = Environment.getDataDirectory(); 942 mAppDataDir = new File(dataDir, "data"); 943 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 944 mUserAppDataDir = new File(dataDir, "user"); 945 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 946 947 sUserManager = UserManagerService.getInstance(context); 948 sUserManager.setInstaller(this, mInstaller); 949 950 readPermissions(); 951 952 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers()); 953 long startTime = SystemClock.uptimeMillis(); 954 955 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 956 startTime); 957 958 // Set flag to monitor and not change apk file paths when 959 // scanning install directories. 960 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 961 if (mNoDexOpt) { 962 Slog.w(TAG, "Running ENG build: no pre-dexopt!"); 963 scanMode |= SCAN_NO_DEX; 964 } 965 966 final HashSet<String> libFiles = new HashSet<String>(); 967 968 mFrameworkDir = new File(Environment.getRootDirectory(), "framework"); 969 mDalvikCacheDir = new File(dataDir, "dalvik-cache"); 970 971 boolean didDexOpt = false; 972 973 /** 974 * Out of paranoia, ensure that everything in the boot class 975 * path has been dexed. 976 */ 977 String bootClassPath = System.getProperty("java.boot.class.path"); 978 if (bootClassPath != null) { 979 String[] paths = splitString(bootClassPath, ':'); 980 for (int i=0; i<paths.length; i++) { 981 try { 982 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) { 983 libFiles.add(paths[i]); 984 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true); 985 didDexOpt = true; 986 } 987 } catch (FileNotFoundException e) { 988 Slog.w(TAG, "Boot class path not found: " + paths[i]); 989 } catch (IOException e) { 990 Slog.w(TAG, "Cannot dexopt " + paths[i] + "; is it an APK or JAR? " 991 + e.getMessage()); 992 } 993 } 994 } else { 995 Slog.w(TAG, "No BOOTCLASSPATH found!"); 996 } 997 998 /** 999 * Also ensure all external libraries have had dexopt run on them. 1000 */ 1001 if (mSharedLibraries.size() > 0) { 1002 Iterator<String> libs = mSharedLibraries.values().iterator(); 1003 while (libs.hasNext()) { 1004 String lib = libs.next(); 1005 try { 1006 if (dalvik.system.DexFile.isDexOptNeeded(lib)) { 1007 libFiles.add(lib); 1008 mInstaller.dexopt(lib, Process.SYSTEM_UID, true); 1009 didDexOpt = true; 1010 } 1011 } catch (FileNotFoundException e) { 1012 Slog.w(TAG, "Library not found: " + lib); 1013 } catch (IOException e) { 1014 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1015 + e.getMessage()); 1016 } 1017 } 1018 } 1019 1020 // Gross hack for now: we know this file doesn't contain any 1021 // code, so don't dexopt it to avoid the resulting log spew. 1022 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk"); 1023 1024 /** 1025 * And there are a number of commands implemented in Java, which 1026 * we currently need to do the dexopt on so that they can be 1027 * run from a non-root shell. 1028 */ 1029 String[] frameworkFiles = mFrameworkDir.list(); 1030 if (frameworkFiles != null) { 1031 for (int i=0; i<frameworkFiles.length; i++) { 1032 File libPath = new File(mFrameworkDir, frameworkFiles[i]); 1033 String path = libPath.getPath(); 1034 // Skip the file if we alrady did it. 1035 if (libFiles.contains(path)) { 1036 continue; 1037 } 1038 // Skip the file if it is not a type we want to dexopt. 1039 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1040 continue; 1041 } 1042 try { 1043 if (dalvik.system.DexFile.isDexOptNeeded(path)) { 1044 mInstaller.dexopt(path, Process.SYSTEM_UID, true); 1045 didDexOpt = true; 1046 } 1047 } catch (FileNotFoundException e) { 1048 Slog.w(TAG, "Jar not found: " + path); 1049 } catch (IOException e) { 1050 Slog.w(TAG, "Exception reading jar: " + path, e); 1051 } 1052 } 1053 } 1054 1055 if (didDexOpt) { 1056 // If we had to do a dexopt of one of the previous 1057 // things, then something on the system has changed. 1058 // Consider this significant, and wipe away all other 1059 // existing dexopt files to ensure we don't leave any 1060 // dangling around. 1061 String[] files = mDalvikCacheDir.list(); 1062 if (files != null) { 1063 for (int i=0; i<files.length; i++) { 1064 String fn = files[i]; 1065 if (fn.startsWith("data@app@") 1066 || fn.startsWith("data@app-private@")) { 1067 Slog.i(TAG, "Pruning dalvik file: " + fn); 1068 (new File(mDalvikCacheDir, fn)).delete(); 1069 } 1070 } 1071 } 1072 } 1073 1074 // Find base frameworks (resource packages without code). 1075 mFrameworkInstallObserver = new AppDirObserver( 1076 mFrameworkDir.getPath(), OBSERVER_EVENTS, true); 1077 mFrameworkInstallObserver.startWatching(); 1078 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM 1079 | PackageParser.PARSE_IS_SYSTEM_DIR, 1080 scanMode | SCAN_NO_DEX, 0); 1081 1082 // Collect all system packages. 1083 mSystemAppDir = new File(Environment.getRootDirectory(), "app"); 1084 mSystemInstallObserver = new AppDirObserver( 1085 mSystemAppDir.getPath(), OBSERVER_EVENTS, true); 1086 mSystemInstallObserver.startWatching(); 1087 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM 1088 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1089 1090 // Collect all vendor packages. 1091 mVendorAppDir = new File("/vendor/app"); 1092 mVendorInstallObserver = new AppDirObserver( 1093 mVendorAppDir.getPath(), OBSERVER_EVENTS, true); 1094 mVendorInstallObserver.startWatching(); 1095 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM 1096 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1097 1098 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1099 mInstaller.moveFiles(); 1100 1101 // Prune any system packages that no longer exist. 1102 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1103 if (!mOnlyCore) { 1104 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1105 while (psit.hasNext()) { 1106 PackageSetting ps = psit.next(); 1107 1108 /* 1109 * If this is not a system app, it can't be a 1110 * disable system app. 1111 */ 1112 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1113 continue; 1114 } 1115 1116 /* 1117 * If the package is scanned, it's not erased. 1118 */ 1119 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1120 if (scannedPkg != null) { 1121 /* 1122 * If the system app is both scanned and in the 1123 * disabled packages list, then it must have been 1124 * added via OTA. Remove it from the currently 1125 * scanned package so the previously user-installed 1126 * application can be scanned. 1127 */ 1128 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1129 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1130 + "; removing system app"); 1131 removePackageLI(scannedPkg, true); 1132 } 1133 1134 continue; 1135 } 1136 1137 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1138 psit.remove(); 1139 String msg = "System package " + ps.name 1140 + " no longer exists; wiping its data"; 1141 reportSettingsProblem(Log.WARN, msg); 1142 mInstaller.remove(ps.name, 0); 1143 sUserManager.removePackageForAllUsers(ps.name); 1144 } else { 1145 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1146 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1147 possiblyDeletedUpdatedSystemApps.add(ps.name); 1148 } 1149 } 1150 } 1151 } 1152 1153 mAppInstallDir = new File(dataDir, "app"); 1154 //look for any incomplete package installations 1155 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1156 //clean up list 1157 for(int i = 0; i < deletePkgsList.size(); i++) { 1158 //clean up here 1159 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1160 } 1161 //delete tmp files 1162 deleteTempPackageFiles(); 1163 1164 if (!mOnlyCore) { 1165 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1166 SystemClock.uptimeMillis()); 1167 mAppInstallObserver = new AppDirObserver( 1168 mAppInstallDir.getPath(), OBSERVER_EVENTS, false); 1169 mAppInstallObserver.startWatching(); 1170 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1171 1172 mDrmAppInstallObserver = new AppDirObserver( 1173 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false); 1174 mDrmAppInstallObserver.startWatching(); 1175 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1176 scanMode, 0); 1177 1178 /** 1179 * Remove disable package settings for any updated system 1180 * apps that were removed via an OTA. If they're not a 1181 * previously-updated app, remove them completely. 1182 * Otherwise, just revoke their system-level permissions. 1183 */ 1184 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1185 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1186 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1187 1188 String msg; 1189 if (deletedPkg == null) { 1190 msg = "Updated system package " + deletedAppName 1191 + " no longer exists; wiping its data"; 1192 1193 mInstaller.remove(deletedAppName, 0); 1194 sUserManager.removePackageForAllUsers(deletedAppName); 1195 } else { 1196 msg = "Updated system app + " + deletedAppName 1197 + " no longer present; removing system privileges for " 1198 + deletedAppName; 1199 1200 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1201 1202 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1203 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1204 } 1205 reportSettingsProblem(Log.WARN, msg); 1206 } 1207 } else { 1208 mAppInstallObserver = null; 1209 mDrmAppInstallObserver = null; 1210 } 1211 1212 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1213 SystemClock.uptimeMillis()); 1214 Slog.i(TAG, "Time to scan packages: " 1215 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1216 + " seconds"); 1217 1218 // If the platform SDK has changed since the last time we booted, 1219 // we need to re-grant app permission to catch any new ones that 1220 // appear. This is really a hack, and means that apps can in some 1221 // cases get permissions that the user didn't initially explicitly 1222 // allow... it would be nice to have some better way to handle 1223 // this situation. 1224 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1225 != mSdkVersion; 1226 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1227 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1228 + "; regranting permissions for internal storage"); 1229 mSettings.mInternalSdkPlatform = mSdkVersion; 1230 1231 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1232 | (regrantPermissions 1233 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1234 : 0)); 1235 1236 // Verify that all of the preferred activity components actually 1237 // exist. It is possible for applications to be updated and at 1238 // that point remove a previously declared activity component that 1239 // had been set as a preferred activity. We try to clean this up 1240 // the next time we encounter that preferred activity, but it is 1241 // possible for the user flow to never be able to return to that 1242 // situation so here we do a sanity check to make sure we haven't 1243 // left any junk around. 1244 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 1245 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) { 1246 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 1247 removed.add(pa); 1248 } 1249 } 1250 for (int i=0; i<removed.size(); i++) { 1251 PreferredActivity pa = removed.get(i); 1252 Slog.w(TAG, "Removing dangling preferred activity: " 1253 + pa.mPref.mComponent); 1254 mSettings.mPreferredActivities.removeFilter(pa); 1255 } 1256 1257 // can downgrade to reader 1258 mSettings.writeLPr(); 1259 1260 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1261 SystemClock.uptimeMillis()); 1262 1263 // Now after opening every single application zip, make sure they 1264 // are all flushed. Not really needed, but keeps things nice and 1265 // tidy. 1266 Runtime.getRuntime().gc(); 1267 1268 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1269 } // synchronized (mPackages) 1270 } // synchronized (mInstallLock) 1271 } 1272 1273 public boolean isFirstBoot() { 1274 return !mRestoredSettings; 1275 } 1276 1277 private String getRequiredVerifierLPr() { 1278 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1279 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1280 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1281 1282 String requiredVerifier = null; 1283 1284 final int N = receivers.size(); 1285 for (int i = 0; i < N; i++) { 1286 final ResolveInfo info = receivers.get(i); 1287 1288 if (info.activityInfo == null) { 1289 continue; 1290 } 1291 1292 final String packageName = info.activityInfo.packageName; 1293 1294 final PackageSetting ps = mSettings.mPackages.get(packageName); 1295 if (ps == null) { 1296 continue; 1297 } 1298 1299 if (!ps.grantedPermissions 1300 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1301 continue; 1302 } 1303 1304 if (requiredVerifier != null) { 1305 throw new RuntimeException("There can be only one required verifier"); 1306 } 1307 1308 requiredVerifier = packageName; 1309 } 1310 1311 return requiredVerifier; 1312 } 1313 1314 @Override 1315 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1316 throws RemoteException { 1317 try { 1318 return super.onTransact(code, data, reply, flags); 1319 } catch (RuntimeException e) { 1320 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1321 Slog.e(TAG, "Package Manager Crash", e); 1322 } 1323 throw e; 1324 } 1325 } 1326 1327 void cleanupInstallFailedPackage(PackageSetting ps) { 1328 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1329 int retCode = mInstaller.remove(ps.name, 0); 1330 if (retCode < 0) { 1331 Slog.w(TAG, "Couldn't remove app data directory for package: " 1332 + ps.name + ", retcode=" + retCode); 1333 } else { 1334 sUserManager.removePackageForAllUsers(ps.name); 1335 } 1336 if (ps.codePath != null) { 1337 if (!ps.codePath.delete()) { 1338 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1339 } 1340 } 1341 if (ps.resourcePath != null) { 1342 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1343 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1344 } 1345 } 1346 mSettings.removePackageLPw(ps.name); 1347 } 1348 1349 void readPermissions() { 1350 // Read permissions from .../etc/permission directory. 1351 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions"); 1352 if (!libraryDir.exists() || !libraryDir.isDirectory()) { 1353 Slog.w(TAG, "No directory " + libraryDir + ", skipping"); 1354 return; 1355 } 1356 if (!libraryDir.canRead()) { 1357 Slog.w(TAG, "Directory " + libraryDir + " cannot be read"); 1358 return; 1359 } 1360 1361 // Iterate over the files in the directory and scan .xml files 1362 for (File f : libraryDir.listFiles()) { 1363 // We'll read platform.xml last 1364 if (f.getPath().endsWith("etc/permissions/platform.xml")) { 1365 continue; 1366 } 1367 1368 if (!f.getPath().endsWith(".xml")) { 1369 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring"); 1370 continue; 1371 } 1372 if (!f.canRead()) { 1373 Slog.w(TAG, "Permissions library file " + f + " cannot be read"); 1374 continue; 1375 } 1376 1377 readPermissionsFromXml(f); 1378 } 1379 1380 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence 1381 final File permFile = new File(Environment.getRootDirectory(), 1382 "etc/permissions/platform.xml"); 1383 readPermissionsFromXml(permFile); 1384 } 1385 1386 private void readPermissionsFromXml(File permFile) { 1387 FileReader permReader = null; 1388 try { 1389 permReader = new FileReader(permFile); 1390 } catch (FileNotFoundException e) { 1391 Slog.w(TAG, "Couldn't find or open permissions file " + permFile); 1392 return; 1393 } 1394 1395 try { 1396 XmlPullParser parser = Xml.newPullParser(); 1397 parser.setInput(permReader); 1398 1399 XmlUtils.beginDocument(parser, "permissions"); 1400 1401 while (true) { 1402 XmlUtils.nextElement(parser); 1403 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) { 1404 break; 1405 } 1406 1407 String name = parser.getName(); 1408 if ("group".equals(name)) { 1409 String gidStr = parser.getAttributeValue(null, "gid"); 1410 if (gidStr != null) { 1411 int gid = Integer.parseInt(gidStr); 1412 mGlobalGids = appendInt(mGlobalGids, gid); 1413 } else { 1414 Slog.w(TAG, "<group> without gid at " 1415 + parser.getPositionDescription()); 1416 } 1417 1418 XmlUtils.skipCurrentTag(parser); 1419 continue; 1420 } else if ("permission".equals(name)) { 1421 String perm = parser.getAttributeValue(null, "name"); 1422 if (perm == null) { 1423 Slog.w(TAG, "<permission> without name at " 1424 + parser.getPositionDescription()); 1425 XmlUtils.skipCurrentTag(parser); 1426 continue; 1427 } 1428 perm = perm.intern(); 1429 readPermission(parser, perm); 1430 1431 } else if ("assign-permission".equals(name)) { 1432 String perm = parser.getAttributeValue(null, "name"); 1433 if (perm == null) { 1434 Slog.w(TAG, "<assign-permission> without name at " 1435 + parser.getPositionDescription()); 1436 XmlUtils.skipCurrentTag(parser); 1437 continue; 1438 } 1439 String uidStr = parser.getAttributeValue(null, "uid"); 1440 if (uidStr == null) { 1441 Slog.w(TAG, "<assign-permission> without uid at " 1442 + parser.getPositionDescription()); 1443 XmlUtils.skipCurrentTag(parser); 1444 continue; 1445 } 1446 int uid = Process.getUidForName(uidStr); 1447 if (uid < 0) { 1448 Slog.w(TAG, "<assign-permission> with unknown uid \"" 1449 + uidStr + "\" at " 1450 + parser.getPositionDescription()); 1451 XmlUtils.skipCurrentTag(parser); 1452 continue; 1453 } 1454 perm = perm.intern(); 1455 HashSet<String> perms = mSystemPermissions.get(uid); 1456 if (perms == null) { 1457 perms = new HashSet<String>(); 1458 mSystemPermissions.put(uid, perms); 1459 } 1460 perms.add(perm); 1461 XmlUtils.skipCurrentTag(parser); 1462 1463 } else if ("library".equals(name)) { 1464 String lname = parser.getAttributeValue(null, "name"); 1465 String lfile = parser.getAttributeValue(null, "file"); 1466 if (lname == null) { 1467 Slog.w(TAG, "<library> without name at " 1468 + parser.getPositionDescription()); 1469 } else if (lfile == null) { 1470 Slog.w(TAG, "<library> without file at " 1471 + parser.getPositionDescription()); 1472 } else { 1473 //Log.i(TAG, "Got library " + lname + " in " + lfile); 1474 mSharedLibraries.put(lname, lfile); 1475 } 1476 XmlUtils.skipCurrentTag(parser); 1477 continue; 1478 1479 } else if ("feature".equals(name)) { 1480 String fname = parser.getAttributeValue(null, "name"); 1481 if (fname == null) { 1482 Slog.w(TAG, "<feature> without name at " 1483 + parser.getPositionDescription()); 1484 } else { 1485 //Log.i(TAG, "Got feature " + fname); 1486 FeatureInfo fi = new FeatureInfo(); 1487 fi.name = fname; 1488 mAvailableFeatures.put(fname, fi); 1489 } 1490 XmlUtils.skipCurrentTag(parser); 1491 continue; 1492 1493 } else { 1494 XmlUtils.skipCurrentTag(parser); 1495 continue; 1496 } 1497 1498 } 1499 permReader.close(); 1500 } catch (XmlPullParserException e) { 1501 Slog.w(TAG, "Got execption parsing permissions.", e); 1502 } catch (IOException e) { 1503 Slog.w(TAG, "Got execption parsing permissions.", e); 1504 } 1505 } 1506 1507 void readPermission(XmlPullParser parser, String name) 1508 throws IOException, XmlPullParserException { 1509 1510 name = name.intern(); 1511 1512 BasePermission bp = mSettings.mPermissions.get(name); 1513 if (bp == null) { 1514 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN); 1515 mSettings.mPermissions.put(name, bp); 1516 } 1517 int outerDepth = parser.getDepth(); 1518 int type; 1519 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1520 && (type != XmlPullParser.END_TAG 1521 || parser.getDepth() > outerDepth)) { 1522 if (type == XmlPullParser.END_TAG 1523 || type == XmlPullParser.TEXT) { 1524 continue; 1525 } 1526 1527 String tagName = parser.getName(); 1528 if ("group".equals(tagName)) { 1529 String gidStr = parser.getAttributeValue(null, "gid"); 1530 if (gidStr != null) { 1531 int gid = Process.getGidForName(gidStr); 1532 bp.gids = appendInt(bp.gids, gid); 1533 } else { 1534 Slog.w(TAG, "<group> without gid at " 1535 + parser.getPositionDescription()); 1536 } 1537 } 1538 XmlUtils.skipCurrentTag(parser); 1539 } 1540 } 1541 1542 static int[] appendInts(int[] cur, int[] add) { 1543 if (add == null) return cur; 1544 if (cur == null) return add; 1545 final int N = add.length; 1546 for (int i=0; i<N; i++) { 1547 cur = appendInt(cur, add[i]); 1548 } 1549 return cur; 1550 } 1551 1552 static int[] removeInts(int[] cur, int[] rem) { 1553 if (rem == null) return cur; 1554 if (cur == null) return cur; 1555 final int N = rem.length; 1556 for (int i=0; i<N; i++) { 1557 cur = removeInt(cur, rem[i]); 1558 } 1559 return cur; 1560 } 1561 1562 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1563 if (!sUserManager.exists(userId)) return null; 1564 PackageInfo pi; 1565 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1566 // The package has been uninstalled but has retained data and resources. 1567 pi = PackageParser.generatePackageInfo(p, null, flags, 0, 0, null, false, 0, userId); 1568 } else { 1569 final PackageSetting ps = (PackageSetting) p.mExtras; 1570 if (ps == null) { 1571 return null; 1572 } 1573 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1574 pi = PackageParser.generatePackageInfo(p, gp.gids, flags, 1575 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1576 ps.getStopped(userId), ps.getEnabled(userId), userId); 1577 pi.applicationInfo.enabledSetting = ps.getEnabled(userId); 1578 pi.applicationInfo.enabled = 1579 pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_DEFAULT 1580 || pi.applicationInfo.enabledSetting == COMPONENT_ENABLED_STATE_ENABLED; 1581 } 1582 return pi; 1583 } 1584 1585 @Override 1586 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1587 if (!sUserManager.exists(userId)) return null; 1588 // reader 1589 synchronized (mPackages) { 1590 PackageParser.Package p = mPackages.get(packageName); 1591 if (DEBUG_PACKAGE_INFO) 1592 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1593 if (p != null) { 1594 return generatePackageInfo(p, flags, userId); 1595 } 1596 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1597 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1598 } 1599 } 1600 return null; 1601 } 1602 1603 public String[] currentToCanonicalPackageNames(String[] names) { 1604 String[] out = new String[names.length]; 1605 // reader 1606 synchronized (mPackages) { 1607 for (int i=names.length-1; i>=0; i--) { 1608 PackageSetting ps = mSettings.mPackages.get(names[i]); 1609 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1610 } 1611 } 1612 return out; 1613 } 1614 1615 public String[] canonicalToCurrentPackageNames(String[] names) { 1616 String[] out = new String[names.length]; 1617 // reader 1618 synchronized (mPackages) { 1619 for (int i=names.length-1; i>=0; i--) { 1620 String cur = mSettings.mRenamedPackages.get(names[i]); 1621 out[i] = cur != null ? cur : names[i]; 1622 } 1623 } 1624 return out; 1625 } 1626 1627 @Override 1628 public int getPackageUid(String packageName, int userId) { 1629 if (!sUserManager.exists(userId)) return -1; 1630 // reader 1631 synchronized (mPackages) { 1632 PackageParser.Package p = mPackages.get(packageName); 1633 if(p != null) { 1634 return UserHandle.getUid(userId, p.applicationInfo.uid); 1635 } 1636 PackageSetting ps = mSettings.mPackages.get(packageName); 1637 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1638 return -1; 1639 } 1640 p = ps.pkg; 1641 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1642 } 1643 } 1644 1645 public int[] getPackageGids(String packageName) { 1646 // reader 1647 synchronized (mPackages) { 1648 PackageParser.Package p = mPackages.get(packageName); 1649 if (DEBUG_PACKAGE_INFO) 1650 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1651 if (p != null) { 1652 final PackageSetting ps = (PackageSetting)p.mExtras; 1653 final SharedUserSetting suid = ps.sharedUser; 1654 int[] gids = suid != null ? suid.gids : ps.gids; 1655 1656 // include GIDs for any unenforced permissions 1657 if (!isPermissionEnforcedLocked(READ_EXTERNAL_STORAGE)) { 1658 final BasePermission basePerm = mSettings.mPermissions.get( 1659 READ_EXTERNAL_STORAGE); 1660 gids = appendInts(gids, basePerm.gids); 1661 } 1662 1663 return gids; 1664 } 1665 } 1666 // stupid thing to indicate an error. 1667 return new int[0]; 1668 } 1669 1670 static final PermissionInfo generatePermissionInfo( 1671 BasePermission bp, int flags) { 1672 if (bp.perm != null) { 1673 return PackageParser.generatePermissionInfo(bp.perm, flags); 1674 } 1675 PermissionInfo pi = new PermissionInfo(); 1676 pi.name = bp.name; 1677 pi.packageName = bp.sourcePackage; 1678 pi.nonLocalizedLabel = bp.name; 1679 pi.protectionLevel = bp.protectionLevel; 1680 return pi; 1681 } 1682 1683 public PermissionInfo getPermissionInfo(String name, int flags) { 1684 // reader 1685 synchronized (mPackages) { 1686 final BasePermission p = mSettings.mPermissions.get(name); 1687 if (p != null) { 1688 return generatePermissionInfo(p, flags); 1689 } 1690 return null; 1691 } 1692 } 1693 1694 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1695 // reader 1696 synchronized (mPackages) { 1697 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1698 for (BasePermission p : mSettings.mPermissions.values()) { 1699 if (group == null) { 1700 if (p.perm == null || p.perm.info.group == null) { 1701 out.add(generatePermissionInfo(p, flags)); 1702 } 1703 } else { 1704 if (p.perm != null && group.equals(p.perm.info.group)) { 1705 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1706 } 1707 } 1708 } 1709 1710 if (out.size() > 0) { 1711 return out; 1712 } 1713 return mPermissionGroups.containsKey(group) ? out : null; 1714 } 1715 } 1716 1717 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1718 // reader 1719 synchronized (mPackages) { 1720 return PackageParser.generatePermissionGroupInfo( 1721 mPermissionGroups.get(name), flags); 1722 } 1723 } 1724 1725 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 1726 // reader 1727 synchronized (mPackages) { 1728 final int N = mPermissionGroups.size(); 1729 ArrayList<PermissionGroupInfo> out 1730 = new ArrayList<PermissionGroupInfo>(N); 1731 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 1732 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 1733 } 1734 return out; 1735 } 1736 } 1737 1738 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 1739 int userId) { 1740 if (!sUserManager.exists(userId)) return null; 1741 PackageSetting ps = mSettings.mPackages.get(packageName); 1742 if (ps != null) { 1743 if (ps.pkg == null) { 1744 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1745 if (pInfo != null) { 1746 return pInfo.applicationInfo; 1747 } 1748 return null; 1749 } 1750 return PackageParser.generateApplicationInfo(ps.pkg, flags, ps.getStopped(userId), 1751 ps.getEnabled(userId), userId); 1752 } 1753 return null; 1754 } 1755 1756 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 1757 int userId) { 1758 if (!sUserManager.exists(userId)) return null; 1759 PackageSetting ps = mSettings.mPackages.get(packageName); 1760 if (ps != null) { 1761 PackageParser.Package pkg = new PackageParser.Package(packageName); 1762 if (ps.pkg == null) { 1763 ps.pkg = new PackageParser.Package(packageName); 1764 ps.pkg.applicationInfo.packageName = packageName; 1765 ps.pkg.applicationInfo.flags = ps.pkgFlags; 1766 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 1767 ps.pkg.applicationInfo.sourceDir = ps.codePathString; 1768 ps.pkg.applicationInfo.dataDir = 1769 getDataPathForPackage(ps.pkg.packageName, 0).getPath(); 1770 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 1771 } 1772 // ps.pkg.mSetEnabled = ps.getEnabled(userId); 1773 // ps.pkg.mSetStopped = ps.getStopped(userId); 1774 return generatePackageInfo(ps.pkg, flags, userId); 1775 } 1776 return null; 1777 } 1778 1779 @Override 1780 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 1781 if (!sUserManager.exists(userId)) return null; 1782 // writer 1783 synchronized (mPackages) { 1784 PackageParser.Package p = mPackages.get(packageName); 1785 if (DEBUG_PACKAGE_INFO) Log.v( 1786 TAG, "getApplicationInfo " + packageName 1787 + ": " + p); 1788 if (p != null) { 1789 PackageSetting ps = mSettings.mPackages.get(packageName); 1790 if (ps == null) return null; 1791 // Note: isEnabledLP() does not apply here - always return info 1792 return PackageParser.generateApplicationInfo(p, flags, ps.getStopped(userId), 1793 ps.getEnabled(userId)); 1794 } 1795 if ("android".equals(packageName)||"system".equals(packageName)) { 1796 return mAndroidApplication; 1797 } 1798 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1799 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 1800 } 1801 } 1802 return null; 1803 } 1804 1805 1806 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 1807 mContext.enforceCallingOrSelfPermission( 1808 android.Manifest.permission.CLEAR_APP_CACHE, null); 1809 // Queue up an async operation since clearing cache may take a little while. 1810 mHandler.post(new Runnable() { 1811 public void run() { 1812 mHandler.removeCallbacks(this); 1813 int retCode = -1; 1814 retCode = mInstaller.freeCache(freeStorageSize); 1815 if (retCode < 0) { 1816 Slog.w(TAG, "Couldn't clear application caches"); 1817 } 1818 if (observer != null) { 1819 try { 1820 observer.onRemoveCompleted(null, (retCode >= 0)); 1821 } catch (RemoteException e) { 1822 Slog.w(TAG, "RemoveException when invoking call back"); 1823 } 1824 } 1825 } 1826 }); 1827 } 1828 1829 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 1830 mContext.enforceCallingOrSelfPermission( 1831 android.Manifest.permission.CLEAR_APP_CACHE, null); 1832 // Queue up an async operation since clearing cache may take a little while. 1833 mHandler.post(new Runnable() { 1834 public void run() { 1835 mHandler.removeCallbacks(this); 1836 int retCode = -1; 1837 retCode = mInstaller.freeCache(freeStorageSize); 1838 if (retCode < 0) { 1839 Slog.w(TAG, "Couldn't clear application caches"); 1840 } 1841 if(pi != null) { 1842 try { 1843 // Callback via pending intent 1844 int code = (retCode >= 0) ? 1 : 0; 1845 pi.sendIntent(null, code, null, 1846 null, null); 1847 } catch (SendIntentException e1) { 1848 Slog.i(TAG, "Failed to send pending intent"); 1849 } 1850 } 1851 } 1852 }); 1853 } 1854 1855 @Override 1856 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 1857 if (!sUserManager.exists(userId)) return null; 1858 synchronized (mPackages) { 1859 PackageParser.Activity a = mActivities.mActivities.get(component); 1860 1861 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 1862 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 1863 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 1864 if (ps == null) return null; 1865 return PackageParser.generateActivityInfo(a, flags, ps.getStopped(userId), 1866 ps.getEnabled(userId), userId); 1867 } 1868 if (mResolveComponentName.equals(component)) { 1869 return mResolveActivity; 1870 } 1871 } 1872 return null; 1873 } 1874 1875 @Override 1876 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 1877 if (!sUserManager.exists(userId)) return null; 1878 synchronized (mPackages) { 1879 PackageParser.Activity a = mReceivers.mActivities.get(component); 1880 if (DEBUG_PACKAGE_INFO) Log.v( 1881 TAG, "getReceiverInfo " + component + ": " + a); 1882 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 1883 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 1884 if (ps == null) return null; 1885 return PackageParser.generateActivityInfo(a, flags, ps.getStopped(userId), 1886 ps.getEnabled(userId), userId); 1887 } 1888 } 1889 return null; 1890 } 1891 1892 @Override 1893 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 1894 if (!sUserManager.exists(userId)) return null; 1895 synchronized (mPackages) { 1896 PackageParser.Service s = mServices.mServices.get(component); 1897 if (DEBUG_PACKAGE_INFO) Log.v( 1898 TAG, "getServiceInfo " + component + ": " + s); 1899 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 1900 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 1901 if (ps == null) return null; 1902 return PackageParser.generateServiceInfo(s, flags, ps.getStopped(userId), 1903 ps.getEnabled(userId), userId); 1904 } 1905 } 1906 return null; 1907 } 1908 1909 @Override 1910 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 1911 if (!sUserManager.exists(userId)) return null; 1912 synchronized (mPackages) { 1913 PackageParser.Provider p = mProvidersByComponent.get(component); 1914 if (DEBUG_PACKAGE_INFO) Log.v( 1915 TAG, "getProviderInfo " + component + ": " + p); 1916 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 1917 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 1918 if (ps == null) return null; 1919 return PackageParser.generateProviderInfo(p, flags, ps.getStopped(userId), 1920 ps.getEnabled(userId), userId); 1921 } 1922 } 1923 return null; 1924 } 1925 1926 public String[] getSystemSharedLibraryNames() { 1927 Set<String> libSet; 1928 synchronized (mPackages) { 1929 libSet = mSharedLibraries.keySet(); 1930 int size = libSet.size(); 1931 if (size > 0) { 1932 String[] libs = new String[size]; 1933 libSet.toArray(libs); 1934 return libs; 1935 } 1936 } 1937 return null; 1938 } 1939 1940 public FeatureInfo[] getSystemAvailableFeatures() { 1941 Collection<FeatureInfo> featSet; 1942 synchronized (mPackages) { 1943 featSet = mAvailableFeatures.values(); 1944 int size = featSet.size(); 1945 if (size > 0) { 1946 FeatureInfo[] features = new FeatureInfo[size+1]; 1947 featSet.toArray(features); 1948 FeatureInfo fi = new FeatureInfo(); 1949 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 1950 FeatureInfo.GL_ES_VERSION_UNDEFINED); 1951 features[size] = fi; 1952 return features; 1953 } 1954 } 1955 return null; 1956 } 1957 1958 public boolean hasSystemFeature(String name) { 1959 synchronized (mPackages) { 1960 return mAvailableFeatures.containsKey(name); 1961 } 1962 } 1963 1964 private void checkValidCaller(int uid, int userId) { 1965 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 1966 return; 1967 1968 throw new SecurityException("Caller uid=" + uid 1969 + " is not privileged to communicate with user=" + userId); 1970 } 1971 1972 public int checkPermission(String permName, String pkgName) { 1973 synchronized (mPackages) { 1974 PackageParser.Package p = mPackages.get(pkgName); 1975 if (p != null && p.mExtras != null) { 1976 PackageSetting ps = (PackageSetting)p.mExtras; 1977 if (ps.sharedUser != null) { 1978 if (ps.sharedUser.grantedPermissions.contains(permName)) { 1979 return PackageManager.PERMISSION_GRANTED; 1980 } 1981 } else if (ps.grantedPermissions.contains(permName)) { 1982 return PackageManager.PERMISSION_GRANTED; 1983 } 1984 } 1985 if (!isPermissionEnforcedLocked(permName)) { 1986 return PackageManager.PERMISSION_GRANTED; 1987 } 1988 } 1989 return PackageManager.PERMISSION_DENIED; 1990 } 1991 1992 public int checkUidPermission(String permName, int uid) { 1993 synchronized (mPackages) { 1994 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 1995 if (obj != null) { 1996 GrantedPermissions gp = (GrantedPermissions)obj; 1997 if (gp.grantedPermissions.contains(permName)) { 1998 return PackageManager.PERMISSION_GRANTED; 1999 } 2000 } else { 2001 HashSet<String> perms = mSystemPermissions.get(uid); 2002 if (perms != null && perms.contains(permName)) { 2003 return PackageManager.PERMISSION_GRANTED; 2004 } 2005 } 2006 if (!isPermissionEnforcedLocked(permName)) { 2007 return PackageManager.PERMISSION_GRANTED; 2008 } 2009 } 2010 return PackageManager.PERMISSION_DENIED; 2011 } 2012 2013 private BasePermission findPermissionTreeLP(String permName) { 2014 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2015 if (permName.startsWith(bp.name) && 2016 permName.length() > bp.name.length() && 2017 permName.charAt(bp.name.length()) == '.') { 2018 return bp; 2019 } 2020 } 2021 return null; 2022 } 2023 2024 private BasePermission checkPermissionTreeLP(String permName) { 2025 if (permName != null) { 2026 BasePermission bp = findPermissionTreeLP(permName); 2027 if (bp != null) { 2028 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2029 return bp; 2030 } 2031 throw new SecurityException("Calling uid " 2032 + Binder.getCallingUid() 2033 + " is not allowed to add to permission tree " 2034 + bp.name + " owned by uid " + bp.uid); 2035 } 2036 } 2037 throw new SecurityException("No permission tree found for " + permName); 2038 } 2039 2040 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2041 if (s1 == null) { 2042 return s2 == null; 2043 } 2044 if (s2 == null) { 2045 return false; 2046 } 2047 if (s1.getClass() != s2.getClass()) { 2048 return false; 2049 } 2050 return s1.equals(s2); 2051 } 2052 2053 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2054 if (pi1.icon != pi2.icon) return false; 2055 if (pi1.logo != pi2.logo) return false; 2056 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2057 if (!compareStrings(pi1.name, pi2.name)) return false; 2058 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2059 // We'll take care of setting this one. 2060 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2061 // These are not currently stored in settings. 2062 //if (!compareStrings(pi1.group, pi2.group)) return false; 2063 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2064 //if (pi1.labelRes != pi2.labelRes) return false; 2065 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2066 return true; 2067 } 2068 2069 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2070 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2071 throw new SecurityException("Label must be specified in permission"); 2072 } 2073 BasePermission tree = checkPermissionTreeLP(info.name); 2074 BasePermission bp = mSettings.mPermissions.get(info.name); 2075 boolean added = bp == null; 2076 boolean changed = true; 2077 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2078 if (added) { 2079 bp = new BasePermission(info.name, tree.sourcePackage, 2080 BasePermission.TYPE_DYNAMIC); 2081 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2082 throw new SecurityException( 2083 "Not allowed to modify non-dynamic permission " 2084 + info.name); 2085 } else { 2086 if (bp.protectionLevel == fixedLevel 2087 && bp.perm.owner.equals(tree.perm.owner) 2088 && bp.uid == tree.uid 2089 && comparePermissionInfos(bp.perm.info, info)) { 2090 changed = false; 2091 } 2092 } 2093 bp.protectionLevel = fixedLevel; 2094 info = new PermissionInfo(info); 2095 info.protectionLevel = fixedLevel; 2096 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2097 bp.perm.info.packageName = tree.perm.info.packageName; 2098 bp.uid = tree.uid; 2099 if (added) { 2100 mSettings.mPermissions.put(info.name, bp); 2101 } 2102 if (changed) { 2103 if (!async) { 2104 mSettings.writeLPr(); 2105 } else { 2106 scheduleWriteSettingsLocked(); 2107 } 2108 } 2109 return added; 2110 } 2111 2112 public boolean addPermission(PermissionInfo info) { 2113 synchronized (mPackages) { 2114 return addPermissionLocked(info, false); 2115 } 2116 } 2117 2118 public boolean addPermissionAsync(PermissionInfo info) { 2119 synchronized (mPackages) { 2120 return addPermissionLocked(info, true); 2121 } 2122 } 2123 2124 public void removePermission(String name) { 2125 synchronized (mPackages) { 2126 checkPermissionTreeLP(name); 2127 BasePermission bp = mSettings.mPermissions.get(name); 2128 if (bp != null) { 2129 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2130 throw new SecurityException( 2131 "Not allowed to modify non-dynamic permission " 2132 + name); 2133 } 2134 mSettings.mPermissions.remove(name); 2135 mSettings.writeLPr(); 2136 } 2137 } 2138 } 2139 2140 public void grantPermission(String packageName, String permissionName) { 2141 mContext.enforceCallingOrSelfPermission( 2142 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2143 synchronized (mPackages) { 2144 final PackageParser.Package pkg = mPackages.get(packageName); 2145 if (pkg == null) { 2146 throw new IllegalArgumentException("Unknown package: " + packageName); 2147 } 2148 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2149 if (bp == null) { 2150 throw new IllegalArgumentException("Unknown permission: " + packageName); 2151 } 2152 if (!pkg.requestedPermissions.contains(permissionName)) { 2153 throw new SecurityException("Package " + packageName 2154 + " has not requested permission " + permissionName); 2155 } 2156 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) { 2157 throw new SecurityException("Permission " + permissionName 2158 + " is not a development permission"); 2159 } 2160 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2161 if (ps == null) { 2162 return; 2163 } 2164 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 2165 if (gp.grantedPermissions.add(permissionName)) { 2166 if (ps.haveGids) { 2167 gp.gids = appendInts(gp.gids, bp.gids); 2168 } 2169 mSettings.writeLPr(); 2170 } 2171 } 2172 } 2173 2174 public void revokePermission(String packageName, String permissionName) { 2175 synchronized (mPackages) { 2176 final PackageParser.Package pkg = mPackages.get(packageName); 2177 if (pkg == null) { 2178 throw new IllegalArgumentException("Unknown package: " + packageName); 2179 } 2180 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2181 mContext.enforceCallingOrSelfPermission( 2182 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2183 } 2184 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2185 if (bp == null) { 2186 throw new IllegalArgumentException("Unknown permission: " + packageName); 2187 } 2188 if (!pkg.requestedPermissions.contains(permissionName)) { 2189 throw new SecurityException("Package " + packageName 2190 + " has not requested permission " + permissionName); 2191 } 2192 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) == 0) { 2193 throw new SecurityException("Permission " + permissionName 2194 + " is not a development permission"); 2195 } 2196 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2197 if (ps == null) { 2198 return; 2199 } 2200 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 2201 if (gp.grantedPermissions.remove(permissionName)) { 2202 gp.grantedPermissions.remove(permissionName); 2203 if (ps.haveGids) { 2204 gp.gids = removeInts(gp.gids, bp.gids); 2205 } 2206 mSettings.writeLPr(); 2207 } 2208 } 2209 } 2210 2211 public boolean isProtectedBroadcast(String actionName) { 2212 synchronized (mPackages) { 2213 return mProtectedBroadcasts.contains(actionName); 2214 } 2215 } 2216 2217 public int checkSignatures(String pkg1, String pkg2) { 2218 synchronized (mPackages) { 2219 final PackageParser.Package p1 = mPackages.get(pkg1); 2220 final PackageParser.Package p2 = mPackages.get(pkg2); 2221 if (p1 == null || p1.mExtras == null 2222 || p2 == null || p2.mExtras == null) { 2223 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2224 } 2225 return compareSignatures(p1.mSignatures, p2.mSignatures); 2226 } 2227 } 2228 2229 public int checkUidSignatures(int uid1, int uid2) { 2230 // Map to base uids. 2231 uid1 = UserHandle.getAppId(uid1); 2232 uid2 = UserHandle.getAppId(uid2); 2233 // reader 2234 synchronized (mPackages) { 2235 Signature[] s1; 2236 Signature[] s2; 2237 Object obj = mSettings.getUserIdLPr(uid1); 2238 if (obj != null) { 2239 if (obj instanceof SharedUserSetting) { 2240 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2241 } else if (obj instanceof PackageSetting) { 2242 s1 = ((PackageSetting)obj).signatures.mSignatures; 2243 } else { 2244 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2245 } 2246 } else { 2247 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2248 } 2249 obj = mSettings.getUserIdLPr(uid2); 2250 if (obj != null) { 2251 if (obj instanceof SharedUserSetting) { 2252 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2253 } else if (obj instanceof PackageSetting) { 2254 s2 = ((PackageSetting)obj).signatures.mSignatures; 2255 } else { 2256 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2257 } 2258 } else { 2259 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2260 } 2261 return compareSignatures(s1, s2); 2262 } 2263 } 2264 2265 static int compareSignatures(Signature[] s1, Signature[] s2) { 2266 if (s1 == null) { 2267 return s2 == null 2268 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2269 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2270 } 2271 if (s2 == null) { 2272 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2273 } 2274 HashSet<Signature> set1 = new HashSet<Signature>(); 2275 for (Signature sig : s1) { 2276 set1.add(sig); 2277 } 2278 HashSet<Signature> set2 = new HashSet<Signature>(); 2279 for (Signature sig : s2) { 2280 set2.add(sig); 2281 } 2282 // Make sure s2 contains all signatures in s1. 2283 if (set1.equals(set2)) { 2284 return PackageManager.SIGNATURE_MATCH; 2285 } 2286 return PackageManager.SIGNATURE_NO_MATCH; 2287 } 2288 2289 public String[] getPackagesForUid(int uid) { 2290 uid = UserHandle.getAppId(uid); 2291 // reader 2292 synchronized (mPackages) { 2293 Object obj = mSettings.getUserIdLPr(uid); 2294 if (obj instanceof SharedUserSetting) { 2295 final SharedUserSetting sus = (SharedUserSetting) obj; 2296 final int N = sus.packages.size(); 2297 final String[] res = new String[N]; 2298 final Iterator<PackageSetting> it = sus.packages.iterator(); 2299 int i = 0; 2300 while (it.hasNext()) { 2301 res[i++] = it.next().name; 2302 } 2303 return res; 2304 } else if (obj instanceof PackageSetting) { 2305 final PackageSetting ps = (PackageSetting) obj; 2306 return new String[] { ps.name }; 2307 } 2308 } 2309 return null; 2310 } 2311 2312 public String getNameForUid(int uid) { 2313 // reader 2314 synchronized (mPackages) { 2315 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2316 if (obj instanceof SharedUserSetting) { 2317 final SharedUserSetting sus = (SharedUserSetting) obj; 2318 return sus.name + ":" + sus.userId; 2319 } else if (obj instanceof PackageSetting) { 2320 final PackageSetting ps = (PackageSetting) obj; 2321 return ps.name; 2322 } 2323 } 2324 return null; 2325 } 2326 2327 public int getUidForSharedUser(String sharedUserName) { 2328 if(sharedUserName == null) { 2329 return -1; 2330 } 2331 // reader 2332 synchronized (mPackages) { 2333 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2334 if (suid == null) { 2335 return -1; 2336 } 2337 return suid.userId; 2338 } 2339 } 2340 2341 @Override 2342 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2343 int flags, int userId) { 2344 if (!sUserManager.exists(userId)) return null; 2345 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2346 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2347 } 2348 2349 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2350 int flags, List<ResolveInfo> query, int userId) { 2351 if (query != null) { 2352 final int N = query.size(); 2353 if (N == 1) { 2354 return query.get(0); 2355 } else if (N > 1) { 2356 // If there is more than one activity with the same priority, 2357 // then let the user decide between them. 2358 ResolveInfo r0 = query.get(0); 2359 ResolveInfo r1 = query.get(1); 2360 if (DEBUG_INTENT_MATCHING) { 2361 Log.d(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2362 + r1.activityInfo.name + "=" + r1.priority); 2363 } 2364 // If the first activity has a higher priority, or a different 2365 // default, then it is always desireable to pick it. 2366 if (r0.priority != r1.priority 2367 || r0.preferredOrder != r1.preferredOrder 2368 || r0.isDefault != r1.isDefault) { 2369 return query.get(0); 2370 } 2371 // If we have saved a preference for a preferred activity for 2372 // this Intent, use that. 2373 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2374 flags, query, r0.priority, userId); 2375 if (ri != null) { 2376 return ri; 2377 } 2378 return mResolveInfo; 2379 } 2380 } 2381 return null; 2382 } 2383 2384 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, 2385 int flags, List<ResolveInfo> query, int priority, int userId) { 2386 if (!sUserManager.exists(userId)) return null; 2387 // writer 2388 synchronized (mPackages) { 2389 if (intent.getSelector() != null) { 2390 intent = intent.getSelector(); 2391 } 2392 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 2393 List<PreferredActivity> prefs = 2394 mSettings.mPreferredActivities.queryIntent(intent, resolvedType, 2395 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 2396 if (prefs != null && prefs.size() > 0) { 2397 // First figure out how good the original match set is. 2398 // We will only allow preferred activities that came 2399 // from the same match quality. 2400 int match = 0; 2401 2402 if (DEBUG_PREFERRED) { 2403 Log.v(TAG, "Figuring out best match..."); 2404 } 2405 2406 final int N = query.size(); 2407 for (int j=0; j<N; j++) { 2408 final ResolveInfo ri = query.get(j); 2409 if (DEBUG_PREFERRED) { 2410 Log.v(TAG, "Match for " + ri.activityInfo + ": 0x" 2411 + Integer.toHexString(match)); 2412 } 2413 if (ri.match > match) { 2414 match = ri.match; 2415 } 2416 } 2417 2418 if (DEBUG_PREFERRED) { 2419 Log.v(TAG, "Best match: 0x" + Integer.toHexString(match)); 2420 } 2421 2422 match &= IntentFilter.MATCH_CATEGORY_MASK; 2423 final int M = prefs.size(); 2424 for (int i=0; i<M; i++) { 2425 final PreferredActivity pa = prefs.get(i); 2426 if (pa.mUserId != userId) { 2427 continue; 2428 } 2429 if (pa.mPref.mMatch != match) { 2430 continue; 2431 } 2432 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, flags, userId); 2433 if (DEBUG_PREFERRED) { 2434 Log.v(TAG, "Got preferred activity:"); 2435 if (ai != null) { 2436 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 2437 } else { 2438 Log.v(TAG, " null"); 2439 } 2440 } 2441 if (ai == null) { 2442 // This previously registered preferred activity 2443 // component is no longer known. Most likely an update 2444 // to the app was installed and in the new version this 2445 // component no longer exists. Clean it up by removing 2446 // it from the preferred activities list, and skip it. 2447 Slog.w(TAG, "Removing dangling preferred activity: " 2448 + pa.mPref.mComponent); 2449 mSettings.mPreferredActivities.removeFilter(pa); 2450 continue; 2451 } 2452 for (int j=0; j<N; j++) { 2453 final ResolveInfo ri = query.get(j); 2454 if (!ri.activityInfo.applicationInfo.packageName 2455 .equals(ai.applicationInfo.packageName)) { 2456 continue; 2457 } 2458 if (!ri.activityInfo.name.equals(ai.name)) { 2459 continue; 2460 } 2461 2462 // Okay we found a previously set preferred app. 2463 // If the result set is different from when this 2464 // was created, we need to clear it and re-ask the 2465 // user their preference. 2466 if (!pa.mPref.sameSet(query, priority)) { 2467 Slog.i(TAG, "Result set changed, dropping preferred activity for " 2468 + intent + " type " + resolvedType); 2469 mSettings.mPreferredActivities.removeFilter(pa); 2470 return null; 2471 } 2472 2473 // Yay! 2474 return ri; 2475 } 2476 } 2477 } 2478 } 2479 return null; 2480 } 2481 2482 @Override 2483 public List<ResolveInfo> queryIntentActivities(Intent intent, 2484 String resolvedType, int flags, int userId) { 2485 if (!sUserManager.exists(userId)) return null; 2486 ComponentName comp = intent.getComponent(); 2487 if (comp == null) { 2488 if (intent.getSelector() != null) { 2489 intent = intent.getSelector(); 2490 comp = intent.getComponent(); 2491 } 2492 } 2493 2494 if (comp != null) { 2495 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 2496 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 2497 if (ai != null) { 2498 final ResolveInfo ri = new ResolveInfo(); 2499 ri.activityInfo = ai; 2500 list.add(ri); 2501 } 2502 return list; 2503 } 2504 2505 // reader 2506 synchronized (mPackages) { 2507 final String pkgName = intent.getPackage(); 2508 if (pkgName == null) { 2509 return mActivities.queryIntent(intent, resolvedType, flags, userId); 2510 } 2511 final PackageParser.Package pkg = mPackages.get(pkgName); 2512 if (pkg != null) { 2513 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 2514 pkg.activities, userId); 2515 } 2516 return new ArrayList<ResolveInfo>(); 2517 } 2518 } 2519 2520 @Override 2521 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 2522 Intent[] specifics, String[] specificTypes, Intent intent, 2523 String resolvedType, int flags, int userId) { 2524 if (!sUserManager.exists(userId)) return null; 2525 final String resultsAction = intent.getAction(); 2526 2527 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 2528 | PackageManager.GET_RESOLVED_FILTER, userId); 2529 2530 if (DEBUG_INTENT_MATCHING) { 2531 Log.v(TAG, "Query " + intent + ": " + results); 2532 } 2533 2534 int specificsPos = 0; 2535 int N; 2536 2537 // todo: note that the algorithm used here is O(N^2). This 2538 // isn't a problem in our current environment, but if we start running 2539 // into situations where we have more than 5 or 10 matches then this 2540 // should probably be changed to something smarter... 2541 2542 // First we go through and resolve each of the specific items 2543 // that were supplied, taking care of removing any corresponding 2544 // duplicate items in the generic resolve list. 2545 if (specifics != null) { 2546 for (int i=0; i<specifics.length; i++) { 2547 final Intent sintent = specifics[i]; 2548 if (sintent == null) { 2549 continue; 2550 } 2551 2552 if (DEBUG_INTENT_MATCHING) { 2553 Log.v(TAG, "Specific #" + i + ": " + sintent); 2554 } 2555 2556 String action = sintent.getAction(); 2557 if (resultsAction != null && resultsAction.equals(action)) { 2558 // If this action was explicitly requested, then don't 2559 // remove things that have it. 2560 action = null; 2561 } 2562 2563 ResolveInfo ri = null; 2564 ActivityInfo ai = null; 2565 2566 ComponentName comp = sintent.getComponent(); 2567 if (comp == null) { 2568 ri = resolveIntent( 2569 sintent, 2570 specificTypes != null ? specificTypes[i] : null, 2571 flags, userId); 2572 if (ri == null) { 2573 continue; 2574 } 2575 if (ri == mResolveInfo) { 2576 // ACK! Must do something better with this. 2577 } 2578 ai = ri.activityInfo; 2579 comp = new ComponentName(ai.applicationInfo.packageName, 2580 ai.name); 2581 } else { 2582 ai = getActivityInfo(comp, flags, userId); 2583 if (ai == null) { 2584 continue; 2585 } 2586 } 2587 2588 // Look for any generic query activities that are duplicates 2589 // of this specific one, and remove them from the results. 2590 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 2591 N = results.size(); 2592 int j; 2593 for (j=specificsPos; j<N; j++) { 2594 ResolveInfo sri = results.get(j); 2595 if ((sri.activityInfo.name.equals(comp.getClassName()) 2596 && sri.activityInfo.applicationInfo.packageName.equals( 2597 comp.getPackageName())) 2598 || (action != null && sri.filter.matchAction(action))) { 2599 results.remove(j); 2600 if (DEBUG_INTENT_MATCHING) Log.v( 2601 TAG, "Removing duplicate item from " + j 2602 + " due to specific " + specificsPos); 2603 if (ri == null) { 2604 ri = sri; 2605 } 2606 j--; 2607 N--; 2608 } 2609 } 2610 2611 // Add this specific item to its proper place. 2612 if (ri == null) { 2613 ri = new ResolveInfo(); 2614 ri.activityInfo = ai; 2615 } 2616 results.add(specificsPos, ri); 2617 ri.specificIndex = i; 2618 specificsPos++; 2619 } 2620 } 2621 2622 // Now we go through the remaining generic results and remove any 2623 // duplicate actions that are found here. 2624 N = results.size(); 2625 for (int i=specificsPos; i<N-1; i++) { 2626 final ResolveInfo rii = results.get(i); 2627 if (rii.filter == null) { 2628 continue; 2629 } 2630 2631 // Iterate over all of the actions of this result's intent 2632 // filter... typically this should be just one. 2633 final Iterator<String> it = rii.filter.actionsIterator(); 2634 if (it == null) { 2635 continue; 2636 } 2637 while (it.hasNext()) { 2638 final String action = it.next(); 2639 if (resultsAction != null && resultsAction.equals(action)) { 2640 // If this action was explicitly requested, then don't 2641 // remove things that have it. 2642 continue; 2643 } 2644 for (int j=i+1; j<N; j++) { 2645 final ResolveInfo rij = results.get(j); 2646 if (rij.filter != null && rij.filter.hasAction(action)) { 2647 results.remove(j); 2648 if (DEBUG_INTENT_MATCHING) Log.v( 2649 TAG, "Removing duplicate item from " + j 2650 + " due to action " + action + " at " + i); 2651 j--; 2652 N--; 2653 } 2654 } 2655 } 2656 2657 // If the caller didn't request filter information, drop it now 2658 // so we don't have to marshall/unmarshall it. 2659 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 2660 rii.filter = null; 2661 } 2662 } 2663 2664 // Filter out the caller activity if so requested. 2665 if (caller != null) { 2666 N = results.size(); 2667 for (int i=0; i<N; i++) { 2668 ActivityInfo ainfo = results.get(i).activityInfo; 2669 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 2670 && caller.getClassName().equals(ainfo.name)) { 2671 results.remove(i); 2672 break; 2673 } 2674 } 2675 } 2676 2677 // If the caller didn't request filter information, 2678 // drop them now so we don't have to 2679 // marshall/unmarshall it. 2680 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 2681 N = results.size(); 2682 for (int i=0; i<N; i++) { 2683 results.get(i).filter = null; 2684 } 2685 } 2686 2687 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 2688 return results; 2689 } 2690 2691 @Override 2692 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 2693 int userId) { 2694 if (!sUserManager.exists(userId)) return null; 2695 ComponentName comp = intent.getComponent(); 2696 if (comp == null) { 2697 if (intent.getSelector() != null) { 2698 intent = intent.getSelector(); 2699 comp = intent.getComponent(); 2700 } 2701 } 2702 if (comp != null) { 2703 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 2704 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 2705 if (ai != null) { 2706 ResolveInfo ri = new ResolveInfo(); 2707 ri.activityInfo = ai; 2708 list.add(ri); 2709 } 2710 return list; 2711 } 2712 2713 // reader 2714 synchronized (mPackages) { 2715 String pkgName = intent.getPackage(); 2716 if (pkgName == null) { 2717 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 2718 } 2719 final PackageParser.Package pkg = mPackages.get(pkgName); 2720 if (pkg != null) { 2721 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 2722 userId); 2723 } 2724 return null; 2725 } 2726 } 2727 2728 @Override 2729 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 2730 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 2731 if (!sUserManager.exists(userId)) return null; 2732 if (query != null) { 2733 if (query.size() >= 1) { 2734 // If there is more than one service with the same priority, 2735 // just arbitrarily pick the first one. 2736 return query.get(0); 2737 } 2738 } 2739 return null; 2740 } 2741 2742 @Override 2743 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 2744 int userId) { 2745 if (!sUserManager.exists(userId)) return null; 2746 ComponentName comp = intent.getComponent(); 2747 if (comp == null) { 2748 if (intent.getSelector() != null) { 2749 intent = intent.getSelector(); 2750 comp = intent.getComponent(); 2751 } 2752 } 2753 if (comp != null) { 2754 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 2755 final ServiceInfo si = getServiceInfo(comp, flags, userId); 2756 if (si != null) { 2757 final ResolveInfo ri = new ResolveInfo(); 2758 ri.serviceInfo = si; 2759 list.add(ri); 2760 } 2761 return list; 2762 } 2763 2764 // reader 2765 synchronized (mPackages) { 2766 String pkgName = intent.getPackage(); 2767 if (pkgName == null) { 2768 return mServices.queryIntent(intent, resolvedType, flags, userId); 2769 } 2770 final PackageParser.Package pkg = mPackages.get(pkgName); 2771 if (pkg != null) { 2772 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 2773 userId); 2774 } 2775 return null; 2776 } 2777 } 2778 2779 private static final int getContinuationPoint(final String[] keys, final String key) { 2780 final int index; 2781 if (key == null) { 2782 index = 0; 2783 } else { 2784 final int insertPoint = Arrays.binarySearch(keys, key); 2785 if (insertPoint < 0) { 2786 index = -insertPoint; 2787 } else { 2788 index = insertPoint + 1; 2789 } 2790 } 2791 return index; 2792 } 2793 2794 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, String lastRead) { 2795 final ParceledListSlice<PackageInfo> list = new ParceledListSlice<PackageInfo>(); 2796 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 2797 final String[] keys; 2798 int userId = UserHandle.getCallingUserId(); 2799 2800 // writer 2801 synchronized (mPackages) { 2802 if (listUninstalled) { 2803 keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]); 2804 } else { 2805 keys = mPackages.keySet().toArray(new String[mPackages.size()]); 2806 } 2807 2808 Arrays.sort(keys); 2809 int i = getContinuationPoint(keys, lastRead); 2810 final int N = keys.length; 2811 2812 while (i < N) { 2813 final String packageName = keys[i++]; 2814 2815 PackageInfo pi = null; 2816 if (listUninstalled) { 2817 final PackageSetting ps = mSettings.mPackages.get(packageName); 2818 if (ps != null) { 2819 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 2820 } 2821 } else { 2822 final PackageParser.Package p = mPackages.get(packageName); 2823 if (p != null) { 2824 pi = generatePackageInfo(p, flags, userId); 2825 } 2826 } 2827 2828 if (pi != null && list.append(pi)) { 2829 break; 2830 } 2831 } 2832 2833 if (i == N) { 2834 list.setLastSlice(true); 2835 } 2836 } 2837 2838 return list; 2839 } 2840 2841 @Override 2842 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, 2843 String lastRead, int userId) { 2844 if (!sUserManager.exists(userId)) return null; 2845 final ParceledListSlice<ApplicationInfo> list = new ParceledListSlice<ApplicationInfo>(); 2846 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 2847 final String[] keys; 2848 2849 // writer 2850 synchronized (mPackages) { 2851 if (listUninstalled) { 2852 keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]); 2853 } else { 2854 keys = mPackages.keySet().toArray(new String[mPackages.size()]); 2855 } 2856 2857 Arrays.sort(keys); 2858 int i = getContinuationPoint(keys, lastRead); 2859 final int N = keys.length; 2860 2861 while (i < N) { 2862 final String packageName = keys[i++]; 2863 2864 ApplicationInfo ai = null; 2865 final PackageSetting ps = mSettings.mPackages.get(packageName); 2866 if (listUninstalled) { 2867 if (ps != null) { 2868 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 2869 } 2870 } else { 2871 final PackageParser.Package p = mPackages.get(packageName); 2872 if (p != null && ps != null) { 2873 ai = PackageParser.generateApplicationInfo(p, flags, ps.getStopped(userId), 2874 ps.getEnabled(userId), userId); 2875 } 2876 } 2877 2878 if (ai != null && list.append(ai)) { 2879 break; 2880 } 2881 } 2882 2883 if (i == N) { 2884 list.setLastSlice(true); 2885 } 2886 } 2887 2888 return list; 2889 } 2890 2891 public List<ApplicationInfo> getPersistentApplications(int flags) { 2892 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 2893 2894 // reader 2895 synchronized (mPackages) { 2896 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 2897 final int userId = UserHandle.getCallingUserId(); 2898 while (i.hasNext()) { 2899 final PackageParser.Package p = i.next(); 2900 if (p.applicationInfo != null 2901 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 2902 && (!mSafeMode || isSystemApp(p))) { 2903 PackageSetting ps = mSettings.mPackages.get(p.packageName); 2904 finalList.add(PackageParser.generateApplicationInfo(p, flags, 2905 ps != null ? ps.getStopped(userId) : false, 2906 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT, 2907 userId)); 2908 } 2909 } 2910 } 2911 2912 return finalList; 2913 } 2914 2915 @Override 2916 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 2917 if (!sUserManager.exists(userId)) return null; 2918 // reader 2919 synchronized (mPackages) { 2920 final PackageParser.Provider provider = mProviders.get(name); 2921 PackageSetting ps = provider != null 2922 ? mSettings.mPackages.get(provider.owner.packageName) 2923 : null; 2924 return provider != null 2925 && mSettings.isEnabledLPr(provider.info, flags, userId) 2926 && (!mSafeMode || (provider.info.applicationInfo.flags 2927 &ApplicationInfo.FLAG_SYSTEM) != 0) 2928 ? PackageParser.generateProviderInfo(provider, flags, 2929 ps != null ? ps.getStopped(userId) : false, 2930 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT, 2931 userId) 2932 : null; 2933 } 2934 } 2935 2936 /** 2937 * @deprecated 2938 */ 2939 @Deprecated 2940 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 2941 // reader 2942 synchronized (mPackages) { 2943 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProviders.entrySet() 2944 .iterator(); 2945 final int userId = UserHandle.getCallingUserId(); 2946 while (i.hasNext()) { 2947 Map.Entry<String, PackageParser.Provider> entry = i.next(); 2948 PackageParser.Provider p = entry.getValue(); 2949 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 2950 2951 if (p.syncable 2952 && (!mSafeMode || (p.info.applicationInfo.flags 2953 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 2954 outNames.add(entry.getKey()); 2955 outInfo.add(PackageParser.generateProviderInfo(p, 0, 2956 ps != null ? ps.getStopped(userId) : false, 2957 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT, 2958 userId)); 2959 } 2960 } 2961 } 2962 } 2963 2964 public List<ProviderInfo> queryContentProviders(String processName, 2965 int uid, int flags) { 2966 ArrayList<ProviderInfo> finalList = null; 2967 2968 // reader 2969 synchronized (mPackages) { 2970 final Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator(); 2971 final int userId = processName != null ? 2972 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 2973 while (i.hasNext()) { 2974 final PackageParser.Provider p = i.next(); 2975 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 2976 if (p.info.authority != null 2977 && (processName == null 2978 || (p.info.processName.equals(processName) 2979 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 2980 && mSettings.isEnabledLPr(p.info, flags, userId) 2981 && (!mSafeMode 2982 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 2983 if (finalList == null) { 2984 finalList = new ArrayList<ProviderInfo>(3); 2985 } 2986 finalList.add(PackageParser.generateProviderInfo(p, flags, 2987 ps != null ? ps.getStopped(userId) : false, 2988 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT, 2989 userId)); 2990 } 2991 } 2992 } 2993 2994 if (finalList != null) { 2995 Collections.sort(finalList, mProviderInitOrderSorter); 2996 } 2997 2998 return finalList; 2999 } 3000 3001 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3002 int flags) { 3003 // reader 3004 synchronized (mPackages) { 3005 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3006 return PackageParser.generateInstrumentationInfo(i, flags); 3007 } 3008 } 3009 3010 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3011 int flags) { 3012 ArrayList<InstrumentationInfo> finalList = 3013 new ArrayList<InstrumentationInfo>(); 3014 3015 // reader 3016 synchronized (mPackages) { 3017 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3018 while (i.hasNext()) { 3019 final PackageParser.Instrumentation p = i.next(); 3020 if (targetPackage == null 3021 || targetPackage.equals(p.info.targetPackage)) { 3022 finalList.add(PackageParser.generateInstrumentationInfo(p, 3023 flags)); 3024 } 3025 } 3026 } 3027 3028 return finalList; 3029 } 3030 3031 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 3032 String[] files = dir.list(); 3033 if (files == null) { 3034 Log.d(TAG, "No files in app dir " + dir); 3035 return; 3036 } 3037 3038 if (DEBUG_PACKAGE_SCANNING) { 3039 Log.d(TAG, "Scanning app dir " + dir); 3040 } 3041 3042 int i; 3043 for (i=0; i<files.length; i++) { 3044 File file = new File(dir, files[i]); 3045 if (!isPackageFilename(files[i])) { 3046 // Ignore entries which are not apk's 3047 continue; 3048 } 3049 PackageParser.Package pkg = scanPackageLI(file, 3050 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime); 3051 // Don't mess around with apps in system partition. 3052 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 3053 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 3054 // Delete the apk 3055 Slog.w(TAG, "Cleaning up failed install of " + file); 3056 file.delete(); 3057 } 3058 } 3059 } 3060 3061 private static File getSettingsProblemFile() { 3062 File dataDir = Environment.getDataDirectory(); 3063 File systemDir = new File(dataDir, "system"); 3064 File fname = new File(systemDir, "uiderrors.txt"); 3065 return fname; 3066 } 3067 3068 static void reportSettingsProblem(int priority, String msg) { 3069 try { 3070 File fname = getSettingsProblemFile(); 3071 FileOutputStream out = new FileOutputStream(fname, true); 3072 PrintWriter pw = new PrintWriter(out); 3073 SimpleDateFormat formatter = new SimpleDateFormat(); 3074 String dateString = formatter.format(new Date(System.currentTimeMillis())); 3075 pw.println(dateString + ": " + msg); 3076 pw.close(); 3077 FileUtils.setPermissions( 3078 fname.toString(), 3079 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 3080 -1, -1); 3081 } catch (java.io.IOException e) { 3082 } 3083 Slog.println(priority, TAG, msg); 3084 } 3085 3086 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 3087 PackageParser.Package pkg, File srcFile, int parseFlags) { 3088 if (GET_CERTIFICATES) { 3089 if (ps != null 3090 && ps.codePath.equals(srcFile) 3091 && ps.timeStamp == srcFile.lastModified()) { 3092 if (ps.signatures.mSignatures != null 3093 && ps.signatures.mSignatures.length != 0) { 3094 // Optimization: reuse the existing cached certificates 3095 // if the package appears to be unchanged. 3096 pkg.mSignatures = ps.signatures.mSignatures; 3097 return true; 3098 } 3099 3100 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 3101 } else { 3102 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 3103 } 3104 3105 if (!pp.collectCertificates(pkg, parseFlags)) { 3106 mLastScanError = pp.getParseError(); 3107 return false; 3108 } 3109 } 3110 return true; 3111 } 3112 3113 /* 3114 * Scan a package and return the newly parsed package. 3115 * Returns null in case of errors and the error code is stored in mLastScanError 3116 */ 3117 private PackageParser.Package scanPackageLI(File scanFile, 3118 int parseFlags, int scanMode, long currentTime) { 3119 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 3120 String scanPath = scanFile.getPath(); 3121 parseFlags |= mDefParseFlags; 3122 PackageParser pp = new PackageParser(scanPath); 3123 pp.setSeparateProcesses(mSeparateProcesses); 3124 pp.setOnlyCoreApps(mOnlyCore); 3125 final PackageParser.Package pkg = pp.parsePackage(scanFile, 3126 scanPath, mMetrics, parseFlags); 3127 if (pkg == null) { 3128 mLastScanError = pp.getParseError(); 3129 return null; 3130 } 3131 PackageSetting ps = null; 3132 PackageSetting updatedPkg; 3133 // reader 3134 synchronized (mPackages) { 3135 // Look to see if we already know about this package. 3136 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 3137 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 3138 // This package has been renamed to its original name. Let's 3139 // use that. 3140 ps = mSettings.peekPackageLPr(oldName); 3141 } 3142 // If there was no original package, see one for the real package name. 3143 if (ps == null) { 3144 ps = mSettings.peekPackageLPr(pkg.packageName); 3145 } 3146 // Check to see if this package could be hiding/updating a system 3147 // package. Must look for it either under the original or real 3148 // package name depending on our state. 3149 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 3150 } 3151 // First check if this is a system package that may involve an update 3152 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 3153 if (ps != null && !ps.codePath.equals(scanFile)) { 3154 // The path has changed from what was last scanned... check the 3155 // version of the new path against what we have stored to determine 3156 // what to do. 3157 if (pkg.mVersionCode < ps.versionCode) { 3158 // The system package has been updated and the code path does not match 3159 // Ignore entry. Skip it. 3160 Log.i(TAG, "Package " + ps.name + " at " + scanFile 3161 + " ignored: updated version " + ps.versionCode 3162 + " better than this " + pkg.mVersionCode); 3163 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3164 return null; 3165 } else { 3166 // The current app on the system partion is better than 3167 // what we have updated to on the data partition; switch 3168 // back to the system partition version. 3169 // At this point, its safely assumed that package installation for 3170 // apps in system partition will go through. If not there won't be a working 3171 // version of the app 3172 // writer 3173 synchronized (mPackages) { 3174 // Just remove the loaded entries from package lists. 3175 mPackages.remove(ps.name); 3176 } 3177 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 3178 + "reverting from " + ps.codePathString 3179 + ": new version " + pkg.mVersionCode 3180 + " better than installed " + ps.versionCode); 3181 3182 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 3183 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString); 3184 synchronized (mInstaller) { 3185 args.cleanUpResourcesLI(); 3186 } 3187 synchronized (mPackages) { 3188 mSettings.enableSystemPackageLPw(ps.name); 3189 } 3190 } 3191 } 3192 } 3193 3194 if (updatedPkg != null) { 3195 // An updated system app will not have the PARSE_IS_SYSTEM flag set 3196 // initially 3197 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 3198 } 3199 // Verify certificates against what was last scanned 3200 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 3201 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 3202 return null; 3203 } 3204 3205 /* 3206 * A new system app appeared, but we already had a non-system one of the 3207 * same name installed earlier. 3208 */ 3209 boolean shouldHideSystemApp = false; 3210 if (updatedPkg == null && ps != null 3211 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 3212 /* 3213 * Check to make sure the signatures match first. If they don't, 3214 * wipe the installed application and its data. 3215 */ 3216 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 3217 != PackageManager.SIGNATURE_MATCH) { 3218 deletePackageLI(pkg.packageName, true, 0, null, false); 3219 ps = null; 3220 } else { 3221 /* 3222 * If the newly-added system app is an older version than the 3223 * already installed version, hide it. It will be scanned later 3224 * and re-added like an update. 3225 */ 3226 if (pkg.mVersionCode < ps.versionCode) { 3227 shouldHideSystemApp = true; 3228 } else { 3229 /* 3230 * The newly found system app is a newer version that the 3231 * one previously installed. Simply remove the 3232 * already-installed application and replace it with our own 3233 * while keeping the application data. 3234 */ 3235 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 3236 + ps.codePathString + ": new version " + pkg.mVersionCode 3237 + " better than installed " + ps.versionCode); 3238 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 3239 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString); 3240 synchronized (mInstaller) { 3241 args.cleanUpResourcesLI(); 3242 } 3243 } 3244 } 3245 } 3246 3247 // The apk is forward locked (not public) if its code and resources 3248 // are kept in different files. 3249 // TODO grab this value from PackageSettings 3250 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 3251 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 3252 } 3253 3254 String codePath = null; 3255 String resPath = null; 3256 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) { 3257 if (ps != null && ps.resourcePathString != null) { 3258 resPath = ps.resourcePathString; 3259 } else { 3260 // Should not happen at all. Just log an error. 3261 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 3262 } 3263 } else { 3264 resPath = pkg.mScanPath; 3265 } 3266 codePath = pkg.mScanPath; 3267 // Set application objects path explicitly. 3268 setApplicationInfoPaths(pkg, codePath, resPath); 3269 // Note that we invoke the following method only if we are about to unpack an application 3270 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 3271 | SCAN_UPDATE_SIGNATURE, currentTime); 3272 3273 /* 3274 * If the system app should be overridden by a previously installed 3275 * data, hide the system app now and let the /data/app scan pick it up 3276 * again. 3277 */ 3278 if (shouldHideSystemApp) { 3279 synchronized (mPackages) { 3280 /* 3281 * We have to grant systems permissions before we hide, because 3282 * grantPermissions will assume the package update is trying to 3283 * expand its permissions. 3284 */ 3285 grantPermissionsLPw(pkg, true); 3286 mSettings.disableSystemPackageLPw(pkg.packageName); 3287 } 3288 } 3289 3290 return scannedPkg; 3291 } 3292 3293 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath, 3294 String destResPath) { 3295 pkg.mPath = pkg.mScanPath = destCodePath; 3296 pkg.applicationInfo.sourceDir = destCodePath; 3297 pkg.applicationInfo.publicSourceDir = destResPath; 3298 } 3299 3300 private static String fixProcessName(String defProcessName, 3301 String processName, int uid) { 3302 if (processName == null) { 3303 return defProcessName; 3304 } 3305 return processName; 3306 } 3307 3308 private boolean verifySignaturesLP(PackageSetting pkgSetting, 3309 PackageParser.Package pkg) { 3310 if (pkgSetting.signatures.mSignatures != null) { 3311 // Already existing package. Make sure signatures match 3312 if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) != 3313 PackageManager.SIGNATURE_MATCH) { 3314 Slog.e(TAG, "Package " + pkg.packageName 3315 + " signatures do not match the previously installed version; ignoring!"); 3316 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 3317 return false; 3318 } 3319 } 3320 // Check for shared user signatures 3321 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 3322 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 3323 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 3324 Slog.e(TAG, "Package " + pkg.packageName 3325 + " has no signatures that match those in shared user " 3326 + pkgSetting.sharedUser.name + "; ignoring!"); 3327 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 3328 return false; 3329 } 3330 } 3331 return true; 3332 } 3333 3334 /** 3335 * Enforces that only the system UID or root's UID can call a method exposed 3336 * via Binder. 3337 * 3338 * @param message used as message if SecurityException is thrown 3339 * @throws SecurityException if the caller is not system or root 3340 */ 3341 private static final void enforceSystemOrRoot(String message) { 3342 final int uid = Binder.getCallingUid(); 3343 if (uid != Process.SYSTEM_UID && uid != 0) { 3344 throw new SecurityException(message); 3345 } 3346 } 3347 3348 public void performBootDexOpt() { 3349 ArrayList<PackageParser.Package> pkgs = null; 3350 synchronized (mPackages) { 3351 if (mDeferredDexOpt.size() > 0) { 3352 pkgs = new ArrayList<PackageParser.Package>(mDeferredDexOpt); 3353 mDeferredDexOpt.clear(); 3354 } 3355 } 3356 if (pkgs != null) { 3357 for (int i=0; i<pkgs.size(); i++) { 3358 if (!isFirstBoot()) { 3359 try { 3360 ActivityManagerNative.getDefault().showBootMessage( 3361 mContext.getResources().getString( 3362 com.android.internal.R.string.android_upgrading_apk, 3363 i+1, pkgs.size()), true); 3364 } catch (RemoteException e) { 3365 } 3366 } 3367 PackageParser.Package p = pkgs.get(i); 3368 synchronized (mInstallLock) { 3369 if (!p.mDidDexOpt) { 3370 performDexOptLI(p, false, false); 3371 } 3372 } 3373 } 3374 } 3375 } 3376 3377 public boolean performDexOpt(String packageName) { 3378 enforceSystemOrRoot("Only the system can request dexopt be performed"); 3379 3380 if (!mNoDexOpt) { 3381 return false; 3382 } 3383 3384 PackageParser.Package p; 3385 synchronized (mPackages) { 3386 p = mPackages.get(packageName); 3387 if (p == null || p.mDidDexOpt) { 3388 return false; 3389 } 3390 } 3391 synchronized (mInstallLock) { 3392 return performDexOptLI(p, false, false) == DEX_OPT_PERFORMED; 3393 } 3394 } 3395 3396 static final int DEX_OPT_SKIPPED = 0; 3397 static final int DEX_OPT_PERFORMED = 1; 3398 static final int DEX_OPT_DEFERRED = 2; 3399 static final int DEX_OPT_FAILED = -1; 3400 3401 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer) { 3402 boolean performed = false; 3403 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 3404 String path = pkg.mScanPath; 3405 int ret = 0; 3406 try { 3407 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) { 3408 if (!forceDex && defer) { 3409 mDeferredDexOpt.add(pkg); 3410 return DEX_OPT_DEFERRED; 3411 } else { 3412 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 3413 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid, 3414 !isForwardLocked(pkg)); 3415 pkg.mDidDexOpt = true; 3416 performed = true; 3417 } 3418 } 3419 } catch (FileNotFoundException e) { 3420 Slog.w(TAG, "Apk not found for dexopt: " + path); 3421 ret = -1; 3422 } catch (IOException e) { 3423 Slog.w(TAG, "IOException reading apk: " + path, e); 3424 ret = -1; 3425 } catch (dalvik.system.StaleDexCacheError e) { 3426 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 3427 ret = -1; 3428 } catch (Exception e) { 3429 Slog.w(TAG, "Exception when doing dexopt : ", e); 3430 ret = -1; 3431 } 3432 if (ret < 0) { 3433 //error from installer 3434 return DEX_OPT_FAILED; 3435 } 3436 } 3437 3438 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 3439 } 3440 3441 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 3442 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 3443 Slog.w(TAG, "Unable to update from " + oldPkg.name 3444 + " to " + newPkg.packageName 3445 + ": old package not in system partition"); 3446 return false; 3447 } else if (mPackages.get(oldPkg.name) != null) { 3448 Slog.w(TAG, "Unable to update from " + oldPkg.name 3449 + " to " + newPkg.packageName 3450 + ": old package still exists"); 3451 return false; 3452 } 3453 return true; 3454 } 3455 3456 File getDataPathForUser(int userId) { 3457 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 3458 } 3459 3460 private File getDataPathForPackage(String packageName, int userId) { 3461 /* 3462 * Until we fully support multiple users, return the directory we 3463 * previously would have. The PackageManagerTests will need to be 3464 * revised when this is changed back.. 3465 */ 3466 if (userId == 0) { 3467 return new File(mAppDataDir, packageName); 3468 } else { 3469 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 3470 + File.separator + packageName); 3471 } 3472 } 3473 3474 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 3475 int parseFlags, int scanMode, long currentTime) { 3476 File scanFile = new File(pkg.mScanPath); 3477 if (scanFile == null || pkg.applicationInfo.sourceDir == null || 3478 pkg.applicationInfo.publicSourceDir == null) { 3479 // Bail out. The resource and code paths haven't been set. 3480 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 3481 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 3482 return null; 3483 } 3484 mScanningPath = scanFile; 3485 3486 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 3487 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 3488 } 3489 3490 if (pkg.packageName.equals("android")) { 3491 synchronized (mPackages) { 3492 if (mAndroidApplication != null) { 3493 Slog.w(TAG, "*************************************************"); 3494 Slog.w(TAG, "Core android package being redefined. Skipping."); 3495 Slog.w(TAG, " file=" + mScanningPath); 3496 Slog.w(TAG, "*************************************************"); 3497 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3498 return null; 3499 } 3500 3501 // Set up information for our fall-back user intent resolution 3502 // activity. 3503 mPlatformPackage = pkg; 3504 pkg.mVersionCode = mSdkVersion; 3505 mAndroidApplication = pkg.applicationInfo; 3506 mResolveActivity.applicationInfo = mAndroidApplication; 3507 mResolveActivity.name = ResolverActivity.class.getName(); 3508 mResolveActivity.packageName = mAndroidApplication.packageName; 3509 mResolveActivity.processName = mAndroidApplication.processName; 3510 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 3511 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 3512 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert; 3513 mResolveActivity.exported = true; 3514 mResolveActivity.enabled = true; 3515 mResolveInfo.activityInfo = mResolveActivity; 3516 mResolveInfo.priority = 0; 3517 mResolveInfo.preferredOrder = 0; 3518 mResolveInfo.match = 0; 3519 mResolveComponentName = new ComponentName( 3520 mAndroidApplication.packageName, mResolveActivity.name); 3521 } 3522 } 3523 3524 if (DEBUG_PACKAGE_SCANNING) { 3525 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 3526 Log.d(TAG, "Scanning package " + pkg.packageName); 3527 } 3528 3529 if (mPackages.containsKey(pkg.packageName) 3530 || mSharedLibraries.containsKey(pkg.packageName)) { 3531 Slog.w(TAG, "Application package " + pkg.packageName 3532 + " already installed. Skipping duplicate."); 3533 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3534 return null; 3535 } 3536 3537 // Initialize package source and resource directories 3538 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 3539 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 3540 3541 SharedUserSetting suid = null; 3542 PackageSetting pkgSetting = null; 3543 3544 if (!isSystemApp(pkg)) { 3545 // Only system apps can use these features. 3546 pkg.mOriginalPackages = null; 3547 pkg.mRealPackage = null; 3548 pkg.mAdoptPermissions = null; 3549 } 3550 3551 // writer 3552 synchronized (mPackages) { 3553 // Check all shared libraries and map to their actual file path. 3554 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 3555 if (mTmpSharedLibraries == null || 3556 mTmpSharedLibraries.length < mSharedLibraries.size()) { 3557 mTmpSharedLibraries = new String[mSharedLibraries.size()]; 3558 } 3559 int num = 0; 3560 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 3561 for (int i=0; i<N; i++) { 3562 final String file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 3563 if (file == null) { 3564 Slog.e(TAG, "Package " + pkg.packageName 3565 + " requires unavailable shared library " 3566 + pkg.usesLibraries.get(i) + "; failing!"); 3567 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 3568 return null; 3569 } 3570 mTmpSharedLibraries[num] = file; 3571 num++; 3572 } 3573 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 3574 for (int i=0; i<N; i++) { 3575 final String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 3576 if (file == null) { 3577 Slog.w(TAG, "Package " + pkg.packageName 3578 + " desires unavailable shared library " 3579 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 3580 } else { 3581 mTmpSharedLibraries[num] = file; 3582 num++; 3583 } 3584 } 3585 if (num > 0) { 3586 pkg.usesLibraryFiles = new String[num]; 3587 System.arraycopy(mTmpSharedLibraries, 0, 3588 pkg.usesLibraryFiles, 0, num); 3589 } 3590 } 3591 3592 if (pkg.mSharedUserId != null) { 3593 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 3594 pkg.applicationInfo.flags, true); 3595 if (suid == null) { 3596 Slog.w(TAG, "Creating application package " + pkg.packageName 3597 + " for shared user failed"); 3598 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 3599 return null; 3600 } 3601 if (DEBUG_PACKAGE_SCANNING) { 3602 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 3603 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 3604 + "): packages=" + suid.packages); 3605 } 3606 } 3607 3608 // Check if we are renaming from an original package name. 3609 PackageSetting origPackage = null; 3610 String realName = null; 3611 if (pkg.mOriginalPackages != null) { 3612 // This package may need to be renamed to a previously 3613 // installed name. Let's check on that... 3614 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 3615 if (pkg.mOriginalPackages.contains(renamed)) { 3616 // This package had originally been installed as the 3617 // original name, and we have already taken care of 3618 // transitioning to the new one. Just update the new 3619 // one to continue using the old name. 3620 realName = pkg.mRealPackage; 3621 if (!pkg.packageName.equals(renamed)) { 3622 // Callers into this function may have already taken 3623 // care of renaming the package; only do it here if 3624 // it is not already done. 3625 pkg.setPackageName(renamed); 3626 } 3627 3628 } else { 3629 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 3630 if ((origPackage = mSettings.peekPackageLPr( 3631 pkg.mOriginalPackages.get(i))) != null) { 3632 // We do have the package already installed under its 3633 // original name... should we use it? 3634 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 3635 // New package is not compatible with original. 3636 origPackage = null; 3637 continue; 3638 } else if (origPackage.sharedUser != null) { 3639 // Make sure uid is compatible between packages. 3640 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 3641 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 3642 + " to " + pkg.packageName + ": old uid " 3643 + origPackage.sharedUser.name 3644 + " differs from " + pkg.mSharedUserId); 3645 origPackage = null; 3646 continue; 3647 } 3648 } else { 3649 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 3650 + pkg.packageName + " to old name " + origPackage.name); 3651 } 3652 break; 3653 } 3654 } 3655 } 3656 } 3657 3658 if (mTransferedPackages.contains(pkg.packageName)) { 3659 Slog.w(TAG, "Package " + pkg.packageName 3660 + " was transferred to another, but its .apk remains"); 3661 } 3662 3663 // Just create the setting, don't add it yet. For already existing packages 3664 // the PkgSetting exists already and doesn't have to be created. 3665 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 3666 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 3667 pkg.applicationInfo.flags, true, false); 3668 if (pkgSetting == null) { 3669 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 3670 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 3671 return null; 3672 } 3673 3674 if (pkgSetting.origPackage != null) { 3675 // If we are first transitioning from an original package, 3676 // fix up the new package's name now. We need to do this after 3677 // looking up the package under its new name, so getPackageLP 3678 // can take care of fiddling things correctly. 3679 pkg.setPackageName(origPackage.name); 3680 3681 // File a report about this. 3682 String msg = "New package " + pkgSetting.realName 3683 + " renamed to replace old package " + pkgSetting.name; 3684 reportSettingsProblem(Log.WARN, msg); 3685 3686 // Make a note of it. 3687 mTransferedPackages.add(origPackage.name); 3688 3689 // No longer need to retain this. 3690 pkgSetting.origPackage = null; 3691 } 3692 3693 if (realName != null) { 3694 // Make a note of it. 3695 mTransferedPackages.add(pkg.packageName); 3696 } 3697 3698 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 3699 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 3700 } 3701 3702 pkg.applicationInfo.uid = pkgSetting.appId; 3703 pkg.mExtras = pkgSetting; 3704 3705 if (!verifySignaturesLP(pkgSetting, pkg)) { 3706 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 3707 return null; 3708 } 3709 // The signature has changed, but this package is in the system 3710 // image... let's recover! 3711 pkgSetting.signatures.mSignatures = pkg.mSignatures; 3712 // However... if this package is part of a shared user, but it 3713 // doesn't match the signature of the shared user, let's fail. 3714 // What this means is that you can't change the signatures 3715 // associated with an overall shared user, which doesn't seem all 3716 // that unreasonable. 3717 if (pkgSetting.sharedUser != null) { 3718 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 3719 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 3720 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 3721 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 3722 return null; 3723 } 3724 } 3725 // File a report about this. 3726 String msg = "System package " + pkg.packageName 3727 + " signature changed; retaining data."; 3728 reportSettingsProblem(Log.WARN, msg); 3729 } 3730 3731 // Verify that this new package doesn't have any content providers 3732 // that conflict with existing packages. Only do this if the 3733 // package isn't already installed, since we don't want to break 3734 // things that are installed. 3735 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 3736 final int N = pkg.providers.size(); 3737 int i; 3738 for (i=0; i<N; i++) { 3739 PackageParser.Provider p = pkg.providers.get(i); 3740 if (p.info.authority != null) { 3741 String names[] = p.info.authority.split(";"); 3742 for (int j = 0; j < names.length; j++) { 3743 if (mProviders.containsKey(names[j])) { 3744 PackageParser.Provider other = mProviders.get(names[j]); 3745 Slog.w(TAG, "Can't install because provider name " + names[j] + 3746 " (in package " + pkg.applicationInfo.packageName + 3747 ") is already used by " 3748 + ((other != null && other.getComponentName() != null) 3749 ? other.getComponentName().getPackageName() : "?")); 3750 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 3751 return null; 3752 } 3753 } 3754 } 3755 } 3756 } 3757 3758 if (pkg.mAdoptPermissions != null) { 3759 // This package wants to adopt ownership of permissions from 3760 // another package. 3761 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 3762 final String origName = pkg.mAdoptPermissions.get(i); 3763 final PackageSetting orig = mSettings.peekPackageLPr(origName); 3764 if (orig != null) { 3765 if (verifyPackageUpdateLPr(orig, pkg)) { 3766 Slog.i(TAG, "Adopting permissions from " + origName + " to " 3767 + pkg.packageName); 3768 mSettings.transferPermissionsLPw(origName, pkg.packageName); 3769 } 3770 } 3771 } 3772 } 3773 } 3774 3775 final String pkgName = pkg.packageName; 3776 3777 final long scanFileTime = scanFile.lastModified(); 3778 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 3779 pkg.applicationInfo.processName = fixProcessName( 3780 pkg.applicationInfo.packageName, 3781 pkg.applicationInfo.processName, 3782 pkg.applicationInfo.uid); 3783 3784 File dataPath; 3785 if (mPlatformPackage == pkg) { 3786 // The system package is special. 3787 dataPath = new File (Environment.getDataDirectory(), "system"); 3788 pkg.applicationInfo.dataDir = dataPath.getPath(); 3789 } else { 3790 // This is a normal package, need to make its data directory. 3791 dataPath = getDataPathForPackage(pkg.packageName, 0); 3792 3793 boolean uidError = false; 3794 3795 if (dataPath.exists()) { 3796 int currentUid = 0; 3797 try { 3798 StructStat stat = Libcore.os.stat(dataPath.getPath()); 3799 currentUid = stat.st_uid; 3800 } catch (ErrnoException e) { 3801 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 3802 } 3803 3804 // If we have mismatched owners for the data path, we have a problem. 3805 if (currentUid != pkg.applicationInfo.uid) { 3806 boolean recovered = false; 3807 if (currentUid == 0) { 3808 // The directory somehow became owned by root. Wow. 3809 // This is probably because the system was stopped while 3810 // installd was in the middle of messing with its libs 3811 // directory. Ask installd to fix that. 3812 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 3813 pkg.applicationInfo.uid); 3814 if (ret >= 0) { 3815 recovered = true; 3816 String msg = "Package " + pkg.packageName 3817 + " unexpectedly changed to uid 0; recovered to " + 3818 + pkg.applicationInfo.uid; 3819 reportSettingsProblem(Log.WARN, msg); 3820 } 3821 } 3822 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 3823 || (scanMode&SCAN_BOOTING) != 0)) { 3824 // If this is a system app, we can at least delete its 3825 // current data so the application will still work. 3826 int ret = mInstaller.remove(pkgName, 0); 3827 if (ret >= 0) { 3828 // TODO: Kill the processes first 3829 // Remove the data directories for all users 3830 sUserManager.removePackageForAllUsers(pkgName); 3831 // Old data gone! 3832 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 3833 ? "System package " : "Third party package "; 3834 String msg = prefix + pkg.packageName 3835 + " has changed from uid: " 3836 + currentUid + " to " 3837 + pkg.applicationInfo.uid + "; old data erased"; 3838 reportSettingsProblem(Log.WARN, msg); 3839 recovered = true; 3840 3841 // And now re-install the app. 3842 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid, 3843 pkg.applicationInfo.uid); 3844 if (ret == -1) { 3845 // Ack should not happen! 3846 msg = prefix + pkg.packageName 3847 + " could not have data directory re-created after delete."; 3848 reportSettingsProblem(Log.WARN, msg); 3849 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 3850 return null; 3851 } 3852 // Create data directories for all users 3853 sUserManager.installPackageForAllUsers(pkgName, 3854 pkg.applicationInfo.uid); 3855 } 3856 if (!recovered) { 3857 mHasSystemUidErrors = true; 3858 } 3859 } else if (!recovered) { 3860 // If we allow this install to proceed, we will be broken. 3861 // Abort, abort! 3862 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 3863 return null; 3864 } 3865 if (!recovered) { 3866 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 3867 + pkg.applicationInfo.uid + "/fs_" 3868 + currentUid; 3869 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 3870 String msg = "Package " + pkg.packageName 3871 + " has mismatched uid: " 3872 + currentUid + " on disk, " 3873 + pkg.applicationInfo.uid + " in settings"; 3874 // writer 3875 synchronized (mPackages) { 3876 mSettings.mReadMessages.append(msg); 3877 mSettings.mReadMessages.append('\n'); 3878 uidError = true; 3879 if (!pkgSetting.uidError) { 3880 reportSettingsProblem(Log.ERROR, msg); 3881 } 3882 } 3883 } 3884 } 3885 pkg.applicationInfo.dataDir = dataPath.getPath(); 3886 } else { 3887 if (DEBUG_PACKAGE_SCANNING) { 3888 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 3889 Log.v(TAG, "Want this data dir: " + dataPath); 3890 } 3891 //invoke installer to do the actual installation 3892 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid, 3893 pkg.applicationInfo.uid); 3894 if (ret < 0) { 3895 // Error from installer 3896 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 3897 return null; 3898 } 3899 // Create data directories for all users 3900 sUserManager.installPackageForAllUsers(pkgName, pkg.applicationInfo.uid); 3901 3902 if (dataPath.exists()) { 3903 pkg.applicationInfo.dataDir = dataPath.getPath(); 3904 } else { 3905 Slog.w(TAG, "Unable to create data directory: " + dataPath); 3906 pkg.applicationInfo.dataDir = null; 3907 } 3908 } 3909 3910 /* 3911 * Set the data dir to the default "/data/data/<package name>/lib" 3912 * if we got here without anyone telling us different (e.g., apps 3913 * stored on SD card have their native libraries stored in the ASEC 3914 * container with the APK). 3915 * 3916 * This happens during an upgrade from a package settings file that 3917 * doesn't have a native library path attribute at all. 3918 */ 3919 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 3920 if (pkgSetting.nativeLibraryPathString == null) { 3921 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath(); 3922 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 3923 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 3924 } else { 3925 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 3926 } 3927 } 3928 3929 pkgSetting.uidError = uidError; 3930 } 3931 3932 String path = scanFile.getPath(); 3933 /* Note: We don't want to unpack the native binaries for 3934 * system applications, unless they have been updated 3935 * (the binaries are already under /system/lib). 3936 * Also, don't unpack libs for apps on the external card 3937 * since they should have their libraries in the ASEC 3938 * container already. 3939 * 3940 * In other words, we're going to unpack the binaries 3941 * only for non-system apps and system app upgrades. 3942 */ 3943 if (pkg.applicationInfo.nativeLibraryDir != null) { 3944 try { 3945 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 3946 final String dataPathString = dataPath.getCanonicalPath(); 3947 3948 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 3949 /* 3950 * Upgrading from a previous version of the OS sometimes 3951 * leaves native libraries in the /data/data/<app>/lib 3952 * directory for system apps even when they shouldn't be. 3953 * Recent changes in the JNI library search path 3954 * necessitates we remove those to match previous behavior. 3955 */ 3956 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 3957 Log.i(TAG, "removed obsolete native libraries for system package " 3958 + path); 3959 } 3960 } else if (nativeLibraryDir.getParentFile().getCanonicalPath() 3961 .equals(dataPathString)) { 3962 /* 3963 * Make sure the native library dir isn't a symlink to 3964 * something. If it is, ask installd to remove it and create 3965 * a directory so we can copy to it afterwards. 3966 */ 3967 boolean isSymLink; 3968 try { 3969 isSymLink = S_ISLNK(Libcore.os.lstat(nativeLibraryDir.getPath()).st_mode); 3970 } catch (ErrnoException e) { 3971 // This shouldn't happen, but we'll fail-safe. 3972 isSymLink = true; 3973 } 3974 if (isSymLink) { 3975 mInstaller.unlinkNativeLibraryDirectory(dataPathString); 3976 } 3977 3978 /* 3979 * If this is an internal application or our 3980 * nativeLibraryPath points to our data directory, unpack 3981 * the libraries if necessary. 3982 */ 3983 NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir); 3984 } else { 3985 Slog.i(TAG, "Linking native library dir for " + path); 3986 mInstaller.linkNativeLibraryDirectory(dataPathString, 3987 pkg.applicationInfo.nativeLibraryDir); 3988 } 3989 } catch (IOException ioe) { 3990 Log.e(TAG, "Unable to get canonical file " + ioe.toString()); 3991 } 3992 } 3993 pkg.mScanPath = path; 3994 3995 if ((scanMode&SCAN_NO_DEX) == 0) { 3996 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0) 3997 == DEX_OPT_FAILED) { 3998 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 3999 return null; 4000 } 4001 } 4002 4003 if (mFactoryTest && pkg.requestedPermissions.contains( 4004 android.Manifest.permission.FACTORY_TEST)) { 4005 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 4006 } 4007 4008 // Request the ActivityManager to kill the process(only for existing packages) 4009 // so that we do not end up in a confused state while the user is still using the older 4010 // version of the application while the new one gets installed. 4011 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 4012 killApplication(pkg.applicationInfo.packageName, 4013 pkg.applicationInfo.uid); 4014 } 4015 4016 // writer 4017 synchronized (mPackages) { 4018 // We don't expect installation to fail beyond this point, 4019 if ((scanMode&SCAN_MONITOR) != 0) { 4020 mAppDirs.put(pkg.mPath, pkg); 4021 } 4022 // Add the new setting to mSettings 4023 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 4024 // Add the new setting to mPackages 4025 mPackages.put(pkg.applicationInfo.packageName, pkg); 4026 // Make sure we don't accidentally delete its data. 4027 mSettings.mPackagesToBeCleaned.remove(pkgName); 4028 4029 // Take care of first install / last update times. 4030 if (currentTime != 0) { 4031 if (pkgSetting.firstInstallTime == 0) { 4032 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 4033 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 4034 pkgSetting.lastUpdateTime = currentTime; 4035 } 4036 } else if (pkgSetting.firstInstallTime == 0) { 4037 // We need *something*. Take time time stamp of the file. 4038 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 4039 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 4040 if (scanFileTime != pkgSetting.timeStamp) { 4041 // A package on the system image has changed; consider this 4042 // to be an update. 4043 pkgSetting.lastUpdateTime = scanFileTime; 4044 } 4045 } 4046 4047 int N = pkg.providers.size(); 4048 StringBuilder r = null; 4049 int i; 4050 for (i=0; i<N; i++) { 4051 PackageParser.Provider p = pkg.providers.get(i); 4052 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 4053 p.info.processName, pkg.applicationInfo.uid); 4054 mProvidersByComponent.put(new ComponentName(p.info.packageName, 4055 p.info.name), p); 4056 p.syncable = p.info.isSyncable; 4057 if (p.info.authority != null) { 4058 String names[] = p.info.authority.split(";"); 4059 p.info.authority = null; 4060 for (int j = 0; j < names.length; j++) { 4061 if (j == 1 && p.syncable) { 4062 // We only want the first authority for a provider to possibly be 4063 // syncable, so if we already added this provider using a different 4064 // authority clear the syncable flag. We copy the provider before 4065 // changing it because the mProviders object contains a reference 4066 // to a provider that we don't want to change. 4067 // Only do this for the second authority since the resulting provider 4068 // object can be the same for all future authorities for this provider. 4069 p = new PackageParser.Provider(p); 4070 p.syncable = false; 4071 } 4072 if (!mProviders.containsKey(names[j])) { 4073 mProviders.put(names[j], p); 4074 if (p.info.authority == null) { 4075 p.info.authority = names[j]; 4076 } else { 4077 p.info.authority = p.info.authority + ";" + names[j]; 4078 } 4079 if (DEBUG_PACKAGE_SCANNING) { 4080 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4081 Log.d(TAG, "Registered content provider: " + names[j] 4082 + ", className = " + p.info.name + ", isSyncable = " 4083 + p.info.isSyncable); 4084 } 4085 } else { 4086 PackageParser.Provider other = mProviders.get(names[j]); 4087 Slog.w(TAG, "Skipping provider name " + names[j] + 4088 " (in package " + pkg.applicationInfo.packageName + 4089 "): name already used by " 4090 + ((other != null && other.getComponentName() != null) 4091 ? other.getComponentName().getPackageName() : "?")); 4092 } 4093 } 4094 } 4095 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4096 if (r == null) { 4097 r = new StringBuilder(256); 4098 } else { 4099 r.append(' '); 4100 } 4101 r.append(p.info.name); 4102 } 4103 } 4104 if (r != null) { 4105 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 4106 } 4107 4108 N = pkg.services.size(); 4109 r = null; 4110 for (i=0; i<N; i++) { 4111 PackageParser.Service s = pkg.services.get(i); 4112 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 4113 s.info.processName, pkg.applicationInfo.uid); 4114 mServices.addService(s); 4115 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4116 if (r == null) { 4117 r = new StringBuilder(256); 4118 } else { 4119 r.append(' '); 4120 } 4121 r.append(s.info.name); 4122 } 4123 } 4124 if (r != null) { 4125 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 4126 } 4127 4128 N = pkg.receivers.size(); 4129 r = null; 4130 for (i=0; i<N; i++) { 4131 PackageParser.Activity a = pkg.receivers.get(i); 4132 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 4133 a.info.processName, pkg.applicationInfo.uid); 4134 mReceivers.addActivity(a, "receiver"); 4135 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4136 if (r == null) { 4137 r = new StringBuilder(256); 4138 } else { 4139 r.append(' '); 4140 } 4141 r.append(a.info.name); 4142 } 4143 } 4144 if (r != null) { 4145 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 4146 } 4147 4148 N = pkg.activities.size(); 4149 r = null; 4150 for (i=0; i<N; i++) { 4151 PackageParser.Activity a = pkg.activities.get(i); 4152 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 4153 a.info.processName, pkg.applicationInfo.uid); 4154 mActivities.addActivity(a, "activity"); 4155 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4156 if (r == null) { 4157 r = new StringBuilder(256); 4158 } else { 4159 r.append(' '); 4160 } 4161 r.append(a.info.name); 4162 } 4163 } 4164 if (r != null) { 4165 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 4166 } 4167 4168 N = pkg.permissionGroups.size(); 4169 r = null; 4170 for (i=0; i<N; i++) { 4171 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 4172 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 4173 if (cur == null) { 4174 mPermissionGroups.put(pg.info.name, pg); 4175 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4176 if (r == null) { 4177 r = new StringBuilder(256); 4178 } else { 4179 r.append(' '); 4180 } 4181 r.append(pg.info.name); 4182 } 4183 } else { 4184 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 4185 + pg.info.packageName + " ignored: original from " 4186 + cur.info.packageName); 4187 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4188 if (r == null) { 4189 r = new StringBuilder(256); 4190 } else { 4191 r.append(' '); 4192 } 4193 r.append("DUP:"); 4194 r.append(pg.info.name); 4195 } 4196 } 4197 } 4198 if (r != null) { 4199 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 4200 } 4201 4202 N = pkg.permissions.size(); 4203 r = null; 4204 for (i=0; i<N; i++) { 4205 PackageParser.Permission p = pkg.permissions.get(i); 4206 HashMap<String, BasePermission> permissionMap = 4207 p.tree ? mSettings.mPermissionTrees 4208 : mSettings.mPermissions; 4209 p.group = mPermissionGroups.get(p.info.group); 4210 if (p.info.group == null || p.group != null) { 4211 BasePermission bp = permissionMap.get(p.info.name); 4212 if (bp == null) { 4213 bp = new BasePermission(p.info.name, p.info.packageName, 4214 BasePermission.TYPE_NORMAL); 4215 permissionMap.put(p.info.name, bp); 4216 } 4217 if (bp.perm == null) { 4218 if (bp.sourcePackage == null 4219 || bp.sourcePackage.equals(p.info.packageName)) { 4220 BasePermission tree = findPermissionTreeLP(p.info.name); 4221 if (tree == null 4222 || tree.sourcePackage.equals(p.info.packageName)) { 4223 bp.packageSetting = pkgSetting; 4224 bp.perm = p; 4225 bp.uid = pkg.applicationInfo.uid; 4226 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4227 if (r == null) { 4228 r = new StringBuilder(256); 4229 } else { 4230 r.append(' '); 4231 } 4232 r.append(p.info.name); 4233 } 4234 } else { 4235 Slog.w(TAG, "Permission " + p.info.name + " from package " 4236 + p.info.packageName + " ignored: base tree " 4237 + tree.name + " is from package " 4238 + tree.sourcePackage); 4239 } 4240 } else { 4241 Slog.w(TAG, "Permission " + p.info.name + " from package " 4242 + p.info.packageName + " ignored: original from " 4243 + bp.sourcePackage); 4244 } 4245 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4246 if (r == null) { 4247 r = new StringBuilder(256); 4248 } else { 4249 r.append(' '); 4250 } 4251 r.append("DUP:"); 4252 r.append(p.info.name); 4253 } 4254 if (bp.perm == p) { 4255 bp.protectionLevel = p.info.protectionLevel; 4256 } 4257 } else { 4258 Slog.w(TAG, "Permission " + p.info.name + " from package " 4259 + p.info.packageName + " ignored: no group " 4260 + p.group); 4261 } 4262 } 4263 if (r != null) { 4264 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 4265 } 4266 4267 N = pkg.instrumentation.size(); 4268 r = null; 4269 for (i=0; i<N; i++) { 4270 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 4271 a.info.packageName = pkg.applicationInfo.packageName; 4272 a.info.sourceDir = pkg.applicationInfo.sourceDir; 4273 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 4274 a.info.dataDir = pkg.applicationInfo.dataDir; 4275 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 4276 mInstrumentation.put(a.getComponentName(), a); 4277 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4278 if (r == null) { 4279 r = new StringBuilder(256); 4280 } else { 4281 r.append(' '); 4282 } 4283 r.append(a.info.name); 4284 } 4285 } 4286 if (r != null) { 4287 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 4288 } 4289 4290 if (pkg.protectedBroadcasts != null) { 4291 N = pkg.protectedBroadcasts.size(); 4292 for (i=0; i<N; i++) { 4293 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 4294 } 4295 } 4296 4297 pkgSetting.setTimeStamp(scanFileTime); 4298 } 4299 4300 return pkg; 4301 } 4302 4303 private void killApplication(String pkgName, int uid) { 4304 // Request the ActivityManager to kill the process(only for existing packages) 4305 // so that we do not end up in a confused state while the user is still using the older 4306 // version of the application while the new one gets installed. 4307 IActivityManager am = ActivityManagerNative.getDefault(); 4308 if (am != null) { 4309 try { 4310 am.killApplicationWithUid(pkgName, uid); 4311 } catch (RemoteException e) { 4312 } 4313 } 4314 } 4315 4316 void removePackageLI(PackageParser.Package pkg, boolean chatty) { 4317 if (DEBUG_INSTALL) { 4318 if (chatty) 4319 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 4320 } 4321 4322 // writer 4323 synchronized (mPackages) { 4324 mPackages.remove(pkg.applicationInfo.packageName); 4325 if (pkg.mPath != null) { 4326 mAppDirs.remove(pkg.mPath); 4327 } 4328 4329 int N = pkg.providers.size(); 4330 StringBuilder r = null; 4331 int i; 4332 for (i=0; i<N; i++) { 4333 PackageParser.Provider p = pkg.providers.get(i); 4334 mProvidersByComponent.remove(new ComponentName(p.info.packageName, 4335 p.info.name)); 4336 if (p.info.authority == null) { 4337 4338 /* The is another ContentProvider with this authority when 4339 * this app was installed so this authority is null, 4340 * Ignore it as we don't have to unregister the provider. 4341 */ 4342 continue; 4343 } 4344 String names[] = p.info.authority.split(";"); 4345 for (int j = 0; j < names.length; j++) { 4346 if (mProviders.get(names[j]) == p) { 4347 mProviders.remove(names[j]); 4348 if (DEBUG_REMOVE) { 4349 if (chatty) 4350 Log.d(TAG, "Unregistered content provider: " + names[j] 4351 + ", className = " + p.info.name + ", isSyncable = " 4352 + p.info.isSyncable); 4353 } 4354 } 4355 } 4356 if (chatty) { 4357 if (r == null) { 4358 r = new StringBuilder(256); 4359 } else { 4360 r.append(' '); 4361 } 4362 r.append(p.info.name); 4363 } 4364 } 4365 if (r != null) { 4366 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 4367 } 4368 4369 N = pkg.services.size(); 4370 r = null; 4371 for (i=0; i<N; i++) { 4372 PackageParser.Service s = pkg.services.get(i); 4373 mServices.removeService(s); 4374 if (chatty) { 4375 if (r == null) { 4376 r = new StringBuilder(256); 4377 } else { 4378 r.append(' '); 4379 } 4380 r.append(s.info.name); 4381 } 4382 } 4383 if (r != null) { 4384 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 4385 } 4386 4387 N = pkg.receivers.size(); 4388 r = null; 4389 for (i=0; i<N; i++) { 4390 PackageParser.Activity a = pkg.receivers.get(i); 4391 mReceivers.removeActivity(a, "receiver"); 4392 if (chatty) { 4393 if (r == null) { 4394 r = new StringBuilder(256); 4395 } else { 4396 r.append(' '); 4397 } 4398 r.append(a.info.name); 4399 } 4400 } 4401 if (r != null) { 4402 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 4403 } 4404 4405 N = pkg.activities.size(); 4406 r = null; 4407 for (i=0; i<N; i++) { 4408 PackageParser.Activity a = pkg.activities.get(i); 4409 mActivities.removeActivity(a, "activity"); 4410 if (chatty) { 4411 if (r == null) { 4412 r = new StringBuilder(256); 4413 } else { 4414 r.append(' '); 4415 } 4416 r.append(a.info.name); 4417 } 4418 } 4419 if (r != null) { 4420 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 4421 } 4422 4423 N = pkg.permissions.size(); 4424 r = null; 4425 for (i=0; i<N; i++) { 4426 PackageParser.Permission p = pkg.permissions.get(i); 4427 BasePermission bp = mSettings.mPermissions.get(p.info.name); 4428 if (bp == null) { 4429 bp = mSettings.mPermissionTrees.get(p.info.name); 4430 } 4431 if (bp != null && bp.perm == p) { 4432 bp.perm = null; 4433 if (chatty) { 4434 if (r == null) { 4435 r = new StringBuilder(256); 4436 } else { 4437 r.append(' '); 4438 } 4439 r.append(p.info.name); 4440 } 4441 } 4442 } 4443 if (r != null) { 4444 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 4445 } 4446 4447 N = pkg.instrumentation.size(); 4448 r = null; 4449 for (i=0; i<N; i++) { 4450 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 4451 mInstrumentation.remove(a.getComponentName()); 4452 if (chatty) { 4453 if (r == null) { 4454 r = new StringBuilder(256); 4455 } else { 4456 r.append(' '); 4457 } 4458 r.append(a.info.name); 4459 } 4460 } 4461 if (r != null) { 4462 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 4463 } 4464 } 4465 } 4466 4467 private static final boolean isPackageFilename(String name) { 4468 return name != null && name.endsWith(".apk"); 4469 } 4470 4471 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 4472 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 4473 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 4474 return true; 4475 } 4476 } 4477 return false; 4478 } 4479 4480 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 4481 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 4482 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 4483 4484 private void updatePermissionsLPw(String changingPkg, 4485 PackageParser.Package pkgInfo, int flags) { 4486 // Make sure there are no dangling permission trees. 4487 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 4488 while (it.hasNext()) { 4489 final BasePermission bp = it.next(); 4490 if (bp.packageSetting == null) { 4491 // We may not yet have parsed the package, so just see if 4492 // we still know about its settings. 4493 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 4494 } 4495 if (bp.packageSetting == null) { 4496 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 4497 + " from package " + bp.sourcePackage); 4498 it.remove(); 4499 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 4500 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 4501 Slog.i(TAG, "Removing old permission tree: " + bp.name 4502 + " from package " + bp.sourcePackage); 4503 flags |= UPDATE_PERMISSIONS_ALL; 4504 it.remove(); 4505 } 4506 } 4507 } 4508 4509 // Make sure all dynamic permissions have been assigned to a package, 4510 // and make sure there are no dangling permissions. 4511 it = mSettings.mPermissions.values().iterator(); 4512 while (it.hasNext()) { 4513 final BasePermission bp = it.next(); 4514 if (bp.type == BasePermission.TYPE_DYNAMIC) { 4515 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 4516 + bp.name + " pkg=" + bp.sourcePackage 4517 + " info=" + bp.pendingInfo); 4518 if (bp.packageSetting == null && bp.pendingInfo != null) { 4519 final BasePermission tree = findPermissionTreeLP(bp.name); 4520 if (tree != null && tree.perm != null) { 4521 bp.packageSetting = tree.packageSetting; 4522 bp.perm = new PackageParser.Permission(tree.perm.owner, 4523 new PermissionInfo(bp.pendingInfo)); 4524 bp.perm.info.packageName = tree.perm.info.packageName; 4525 bp.perm.info.name = bp.name; 4526 bp.uid = tree.uid; 4527 } 4528 } 4529 } 4530 if (bp.packageSetting == null) { 4531 // We may not yet have parsed the package, so just see if 4532 // we still know about its settings. 4533 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 4534 } 4535 if (bp.packageSetting == null) { 4536 Slog.w(TAG, "Removing dangling permission: " + bp.name 4537 + " from package " + bp.sourcePackage); 4538 it.remove(); 4539 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 4540 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 4541 Slog.i(TAG, "Removing old permission: " + bp.name 4542 + " from package " + bp.sourcePackage); 4543 flags |= UPDATE_PERMISSIONS_ALL; 4544 it.remove(); 4545 } 4546 } 4547 } 4548 4549 // Now update the permissions for all packages, in particular 4550 // replace the granted permissions of the system packages. 4551 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 4552 for (PackageParser.Package pkg : mPackages.values()) { 4553 if (pkg != pkgInfo) { 4554 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 4555 } 4556 } 4557 } 4558 4559 if (pkgInfo != null) { 4560 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 4561 } 4562 } 4563 4564 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 4565 final PackageSetting ps = (PackageSetting) pkg.mExtras; 4566 if (ps == null) { 4567 return; 4568 } 4569 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 4570 HashSet<String> origPermissions = gp.grantedPermissions; 4571 boolean changedPermission = false; 4572 4573 if (replace) { 4574 ps.permissionsFixed = false; 4575 if (gp == ps) { 4576 origPermissions = new HashSet<String>(gp.grantedPermissions); 4577 gp.grantedPermissions.clear(); 4578 gp.gids = mGlobalGids; 4579 } 4580 } 4581 4582 if (gp.gids == null) { 4583 gp.gids = mGlobalGids; 4584 } 4585 4586 final int N = pkg.requestedPermissions.size(); 4587 for (int i=0; i<N; i++) { 4588 final String name = pkg.requestedPermissions.get(i); 4589 //final boolean required = pkg.requestedPermssionsRequired.get(i); 4590 final BasePermission bp = mSettings.mPermissions.get(name); 4591 if (DEBUG_INSTALL) { 4592 if (gp != ps) { 4593 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 4594 } 4595 } 4596 if (bp != null && bp.packageSetting != null) { 4597 final String perm = bp.name; 4598 boolean allowed; 4599 boolean allowedSig = false; 4600 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 4601 if (level == PermissionInfo.PROTECTION_NORMAL 4602 || level == PermissionInfo.PROTECTION_DANGEROUS) { 4603 allowed = true; 4604 } else if (bp.packageSetting == null) { 4605 // This permission is invalid; skip it. 4606 allowed = false; 4607 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 4608 allowed = (compareSignatures( 4609 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 4610 == PackageManager.SIGNATURE_MATCH) 4611 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 4612 == PackageManager.SIGNATURE_MATCH); 4613 if (!allowed && (bp.protectionLevel 4614 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 4615 if (isSystemApp(pkg)) { 4616 // For updated system applications, a system permission 4617 // is granted only if it had been defined by the original application. 4618 if (isUpdatedSystemApp(pkg)) { 4619 final PackageSetting sysPs = mSettings 4620 .getDisabledSystemPkgLPr(pkg.packageName); 4621 final GrantedPermissions origGp = sysPs.sharedUser != null 4622 ? sysPs.sharedUser : sysPs; 4623 if (origGp.grantedPermissions.contains(perm)) { 4624 allowed = true; 4625 } else { 4626 allowed = false; 4627 } 4628 } else { 4629 allowed = true; 4630 } 4631 } 4632 } 4633 if (!allowed && (bp.protectionLevel 4634 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 4635 // For development permissions, a development permission 4636 // is granted only if it was already granted. 4637 if (origPermissions.contains(perm)) { 4638 allowed = true; 4639 } else { 4640 allowed = false; 4641 } 4642 } 4643 if (allowed) { 4644 allowedSig = true; 4645 } 4646 } else { 4647 allowed = false; 4648 } 4649 if (DEBUG_INSTALL) { 4650 if (gp != ps) { 4651 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 4652 } 4653 } 4654 if (allowed) { 4655 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 4656 && ps.permissionsFixed) { 4657 // If this is an existing, non-system package, then 4658 // we can't add any new permissions to it. 4659 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 4660 allowed = false; 4661 // Except... if this is a permission that was added 4662 // to the platform (note: need to only do this when 4663 // updating the platform). 4664 final int NP = PackageParser.NEW_PERMISSIONS.length; 4665 for (int ip=0; ip<NP; ip++) { 4666 final PackageParser.NewPermissionInfo npi 4667 = PackageParser.NEW_PERMISSIONS[ip]; 4668 if (npi.name.equals(perm) 4669 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 4670 allowed = true; 4671 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 4672 + pkg.packageName); 4673 break; 4674 } 4675 } 4676 } 4677 } 4678 if (allowed) { 4679 if (!gp.grantedPermissions.contains(perm)) { 4680 changedPermission = true; 4681 gp.grantedPermissions.add(perm); 4682 gp.gids = appendInts(gp.gids, bp.gids); 4683 } else if (!ps.haveGids) { 4684 gp.gids = appendInts(gp.gids, bp.gids); 4685 } 4686 } else { 4687 Slog.w(TAG, "Not granting permission " + perm 4688 + " to package " + pkg.packageName 4689 + " because it was previously installed without"); 4690 } 4691 } else { 4692 if (gp.grantedPermissions.remove(perm)) { 4693 changedPermission = true; 4694 gp.gids = removeInts(gp.gids, bp.gids); 4695 Slog.i(TAG, "Un-granting permission " + perm 4696 + " from package " + pkg.packageName 4697 + " (protectionLevel=" + bp.protectionLevel 4698 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 4699 + ")"); 4700 } else { 4701 Slog.w(TAG, "Not granting permission " + perm 4702 + " to package " + pkg.packageName 4703 + " (protectionLevel=" + bp.protectionLevel 4704 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 4705 + ")"); 4706 } 4707 } 4708 } else { 4709 Slog.w(TAG, "Unknown permission " + name 4710 + " in package " + pkg.packageName); 4711 } 4712 } 4713 4714 if ((changedPermission || replace) && !ps.permissionsFixed && 4715 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) || 4716 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){ 4717 // This is the first that we have heard about this package, so the 4718 // permissions we have now selected are fixed until explicitly 4719 // changed. 4720 ps.permissionsFixed = true; 4721 } 4722 ps.haveGids = true; 4723 } 4724 4725 private final class ActivityIntentResolver 4726 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 4727 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 4728 boolean defaultOnly, int userId) { 4729 if (!sUserManager.exists(userId)) return null; 4730 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 4731 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 4732 } 4733 4734 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 4735 int userId) { 4736 if (!sUserManager.exists(userId)) return null; 4737 mFlags = flags; 4738 return super.queryIntent(intent, resolvedType, 4739 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 4740 } 4741 4742 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 4743 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 4744 if (!sUserManager.exists(userId)) return null; 4745 if (packageActivities == null) { 4746 return null; 4747 } 4748 mFlags = flags; 4749 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 4750 final int N = packageActivities.size(); 4751 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 4752 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 4753 4754 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 4755 for (int i = 0; i < N; ++i) { 4756 intentFilters = packageActivities.get(i).intents; 4757 if (intentFilters != null && intentFilters.size() > 0) { 4758 PackageParser.ActivityIntentInfo[] array = 4759 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 4760 intentFilters.toArray(array); 4761 listCut.add(array); 4762 } 4763 } 4764 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 4765 } 4766 4767 public final void addActivity(PackageParser.Activity a, String type) { 4768 final boolean systemApp = isSystemApp(a.info.applicationInfo); 4769 mActivities.put(a.getComponentName(), a); 4770 if (DEBUG_SHOW_INFO) 4771 Log.v( 4772 TAG, " " + type + " " + 4773 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 4774 if (DEBUG_SHOW_INFO) 4775 Log.v(TAG, " Class=" + a.info.name); 4776 final int NI = a.intents.size(); 4777 for (int j=0; j<NI; j++) { 4778 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 4779 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 4780 intent.setPriority(0); 4781 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 4782 + a.className + " with priority > 0, forcing to 0"); 4783 } 4784 if (DEBUG_SHOW_INFO) { 4785 Log.v(TAG, " IntentFilter:"); 4786 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 4787 } 4788 if (!intent.debugCheck()) { 4789 Log.w(TAG, "==> For Activity " + a.info.name); 4790 } 4791 addFilter(intent); 4792 } 4793 } 4794 4795 public final void removeActivity(PackageParser.Activity a, String type) { 4796 mActivities.remove(a.getComponentName()); 4797 if (DEBUG_SHOW_INFO) { 4798 Log.v(TAG, " " + type + " " 4799 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 4800 : a.info.name) + ":"); 4801 Log.v(TAG, " Class=" + a.info.name); 4802 } 4803 final int NI = a.intents.size(); 4804 for (int j=0; j<NI; j++) { 4805 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 4806 if (DEBUG_SHOW_INFO) { 4807 Log.v(TAG, " IntentFilter:"); 4808 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 4809 } 4810 removeFilter(intent); 4811 } 4812 } 4813 4814 @Override 4815 protected boolean allowFilterResult( 4816 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 4817 ActivityInfo filterAi = filter.activity.info; 4818 for (int i=dest.size()-1; i>=0; i--) { 4819 ActivityInfo destAi = dest.get(i).activityInfo; 4820 if (destAi.name == filterAi.name 4821 && destAi.packageName == filterAi.packageName) { 4822 return false; 4823 } 4824 } 4825 return true; 4826 } 4827 4828 @Override 4829 protected ActivityIntentInfo[] newArray(int size) { 4830 return new ActivityIntentInfo[size]; 4831 } 4832 4833 @Override 4834 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 4835 if (!sUserManager.exists(userId)) return true; 4836 PackageParser.Package p = filter.activity.owner; 4837 if (p != null) { 4838 PackageSetting ps = (PackageSetting)p.mExtras; 4839 if (ps != null) { 4840 // System apps are never considered stopped for purposes of 4841 // filtering, because there may be no way for the user to 4842 // actually re-launch them. 4843 return ps.getStopped(userId) && (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0; 4844 } 4845 } 4846 return false; 4847 } 4848 4849 @Override 4850 protected String packageForFilter(PackageParser.ActivityIntentInfo info) { 4851 return info.activity.owner.packageName; 4852 } 4853 4854 @Override 4855 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 4856 int match, int userId) { 4857 if (!sUserManager.exists(userId)) return null; 4858 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 4859 return null; 4860 } 4861 final PackageParser.Activity activity = info.activity; 4862 if (mSafeMode && (activity.info.applicationInfo.flags 4863 &ApplicationInfo.FLAG_SYSTEM) == 0) { 4864 return null; 4865 } 4866 final ResolveInfo res = new ResolveInfo(); 4867 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 4868 res.activityInfo = PackageParser.generateActivityInfo(activity, mFlags, 4869 ps != null ? ps.getStopped(userId) : false, 4870 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT, 4871 userId); 4872 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 4873 res.filter = info; 4874 } 4875 res.priority = info.getPriority(); 4876 res.preferredOrder = activity.owner.mPreferredOrder; 4877 //System.out.println("Result: " + res.activityInfo.className + 4878 // " = " + res.priority); 4879 res.match = match; 4880 res.isDefault = info.hasDefault; 4881 res.labelRes = info.labelRes; 4882 res.nonLocalizedLabel = info.nonLocalizedLabel; 4883 res.icon = info.icon; 4884 res.system = isSystemApp(res.activityInfo.applicationInfo); 4885 return res; 4886 } 4887 4888 @Override 4889 protected void sortResults(List<ResolveInfo> results) { 4890 Collections.sort(results, mResolvePrioritySorter); 4891 } 4892 4893 @Override 4894 protected void dumpFilter(PrintWriter out, String prefix, 4895 PackageParser.ActivityIntentInfo filter) { 4896 out.print(prefix); out.print( 4897 Integer.toHexString(System.identityHashCode(filter.activity))); 4898 out.print(' '); 4899 out.print(filter.activity.getComponentShortName()); 4900 out.print(" filter "); 4901 out.println(Integer.toHexString(System.identityHashCode(filter))); 4902 } 4903 4904// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 4905// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 4906// final List<ResolveInfo> retList = Lists.newArrayList(); 4907// while (i.hasNext()) { 4908// final ResolveInfo resolveInfo = i.next(); 4909// if (isEnabledLP(resolveInfo.activityInfo)) { 4910// retList.add(resolveInfo); 4911// } 4912// } 4913// return retList; 4914// } 4915 4916 // Keys are String (activity class name), values are Activity. 4917 private final HashMap<ComponentName, PackageParser.Activity> mActivities 4918 = new HashMap<ComponentName, PackageParser.Activity>(); 4919 private int mFlags; 4920 } 4921 4922 private final class ServiceIntentResolver 4923 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 4924 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 4925 boolean defaultOnly, int userId) { 4926 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 4927 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 4928 } 4929 4930 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 4931 int userId) { 4932 if (!sUserManager.exists(userId)) return null; 4933 mFlags = flags; 4934 return super.queryIntent(intent, resolvedType, 4935 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 4936 } 4937 4938 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 4939 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 4940 if (!sUserManager.exists(userId)) return null; 4941 if (packageServices == null) { 4942 return null; 4943 } 4944 mFlags = flags; 4945 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 4946 final int N = packageServices.size(); 4947 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 4948 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 4949 4950 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 4951 for (int i = 0; i < N; ++i) { 4952 intentFilters = packageServices.get(i).intents; 4953 if (intentFilters != null && intentFilters.size() > 0) { 4954 PackageParser.ServiceIntentInfo[] array = 4955 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 4956 intentFilters.toArray(array); 4957 listCut.add(array); 4958 } 4959 } 4960 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 4961 } 4962 4963 public final void addService(PackageParser.Service s) { 4964 mServices.put(s.getComponentName(), s); 4965 if (DEBUG_SHOW_INFO) { 4966 Log.v(TAG, " " 4967 + (s.info.nonLocalizedLabel != null 4968 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 4969 Log.v(TAG, " Class=" + s.info.name); 4970 } 4971 final int NI = s.intents.size(); 4972 int j; 4973 for (j=0; j<NI; j++) { 4974 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 4975 if (DEBUG_SHOW_INFO) { 4976 Log.v(TAG, " IntentFilter:"); 4977 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 4978 } 4979 if (!intent.debugCheck()) { 4980 Log.w(TAG, "==> For Service " + s.info.name); 4981 } 4982 addFilter(intent); 4983 } 4984 } 4985 4986 public final void removeService(PackageParser.Service s) { 4987 mServices.remove(s.getComponentName()); 4988 if (DEBUG_SHOW_INFO) { 4989 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 4990 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 4991 Log.v(TAG, " Class=" + s.info.name); 4992 } 4993 final int NI = s.intents.size(); 4994 int j; 4995 for (j=0; j<NI; j++) { 4996 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 4997 if (DEBUG_SHOW_INFO) { 4998 Log.v(TAG, " IntentFilter:"); 4999 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5000 } 5001 removeFilter(intent); 5002 } 5003 } 5004 5005 @Override 5006 protected boolean allowFilterResult( 5007 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 5008 ServiceInfo filterSi = filter.service.info; 5009 for (int i=dest.size()-1; i>=0; i--) { 5010 ServiceInfo destAi = dest.get(i).serviceInfo; 5011 if (destAi.name == filterSi.name 5012 && destAi.packageName == filterSi.packageName) { 5013 return false; 5014 } 5015 } 5016 return true; 5017 } 5018 5019 @Override 5020 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 5021 return new PackageParser.ServiceIntentInfo[size]; 5022 } 5023 5024 @Override 5025 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 5026 if (!sUserManager.exists(userId)) return true; 5027 PackageParser.Package p = filter.service.owner; 5028 if (p != null) { 5029 PackageSetting ps = (PackageSetting)p.mExtras; 5030 if (ps != null) { 5031 // System apps are never considered stopped for purposes of 5032 // filtering, because there may be no way for the user to 5033 // actually re-launch them. 5034 return ps.getStopped(userId) 5035 && (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0; 5036 } 5037 } 5038 return false; 5039 } 5040 5041 @Override 5042 protected String packageForFilter(PackageParser.ServiceIntentInfo info) { 5043 return info.service.owner.packageName; 5044 } 5045 5046 @Override 5047 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 5048 int match, int userId) { 5049 if (!sUserManager.exists(userId)) return null; 5050 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 5051 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 5052 return null; 5053 } 5054 final PackageParser.Service service = info.service; 5055 if (mSafeMode && (service.info.applicationInfo.flags 5056 &ApplicationInfo.FLAG_SYSTEM) == 0) { 5057 return null; 5058 } 5059 final ResolveInfo res = new ResolveInfo(); 5060 PackageSetting ps = (PackageSetting) service.owner.mExtras; 5061 res.serviceInfo = PackageParser.generateServiceInfo(service, mFlags, 5062 ps != null ? ps.getStopped(userId) : false, 5063 ps != null ? ps.getEnabled(userId) : COMPONENT_ENABLED_STATE_DEFAULT, 5064 userId); 5065 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 5066 res.filter = filter; 5067 } 5068 res.priority = info.getPriority(); 5069 res.preferredOrder = service.owner.mPreferredOrder; 5070 //System.out.println("Result: " + res.activityInfo.className + 5071 // " = " + res.priority); 5072 res.match = match; 5073 res.isDefault = info.hasDefault; 5074 res.labelRes = info.labelRes; 5075 res.nonLocalizedLabel = info.nonLocalizedLabel; 5076 res.icon = info.icon; 5077 res.system = isSystemApp(res.serviceInfo.applicationInfo); 5078 return res; 5079 } 5080 5081 @Override 5082 protected void sortResults(List<ResolveInfo> results) { 5083 Collections.sort(results, mResolvePrioritySorter); 5084 } 5085 5086 @Override 5087 protected void dumpFilter(PrintWriter out, String prefix, 5088 PackageParser.ServiceIntentInfo filter) { 5089 out.print(prefix); out.print( 5090 Integer.toHexString(System.identityHashCode(filter.service))); 5091 out.print(' '); 5092 out.print(filter.service.getComponentShortName()); 5093 out.print(" filter "); 5094 out.println(Integer.toHexString(System.identityHashCode(filter))); 5095 } 5096 5097// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 5098// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 5099// final List<ResolveInfo> retList = Lists.newArrayList(); 5100// while (i.hasNext()) { 5101// final ResolveInfo resolveInfo = (ResolveInfo) i; 5102// if (isEnabledLP(resolveInfo.serviceInfo)) { 5103// retList.add(resolveInfo); 5104// } 5105// } 5106// return retList; 5107// } 5108 5109 // Keys are String (activity class name), values are Activity. 5110 private final HashMap<ComponentName, PackageParser.Service> mServices 5111 = new HashMap<ComponentName, PackageParser.Service>(); 5112 private int mFlags; 5113 }; 5114 5115 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 5116 new Comparator<ResolveInfo>() { 5117 public int compare(ResolveInfo r1, ResolveInfo r2) { 5118 int v1 = r1.priority; 5119 int v2 = r2.priority; 5120 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 5121 if (v1 != v2) { 5122 return (v1 > v2) ? -1 : 1; 5123 } 5124 v1 = r1.preferredOrder; 5125 v2 = r2.preferredOrder; 5126 if (v1 != v2) { 5127 return (v1 > v2) ? -1 : 1; 5128 } 5129 if (r1.isDefault != r2.isDefault) { 5130 return r1.isDefault ? -1 : 1; 5131 } 5132 v1 = r1.match; 5133 v2 = r2.match; 5134 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 5135 if (v1 != v2) { 5136 return (v1 > v2) ? -1 : 1; 5137 } 5138 if (r1.system != r2.system) { 5139 return r1.system ? -1 : 1; 5140 } 5141 return 0; 5142 } 5143 }; 5144 5145 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 5146 new Comparator<ProviderInfo>() { 5147 public int compare(ProviderInfo p1, ProviderInfo p2) { 5148 final int v1 = p1.initOrder; 5149 final int v2 = p2.initOrder; 5150 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 5151 } 5152 }; 5153 5154 static final void sendPackageBroadcast(String action, String pkg, 5155 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, int userId) { 5156 IActivityManager am = ActivityManagerNative.getDefault(); 5157 if (am != null) { 5158 try { 5159 int[] userIds = userId == UserHandle.USER_ALL 5160 ? sUserManager.getUserIds() 5161 : new int[] {userId}; 5162 for (int id : userIds) { 5163 final Intent intent = new Intent(action, 5164 pkg != null ? Uri.fromParts("package", pkg, null) : null); 5165 if (extras != null) { 5166 intent.putExtras(extras); 5167 } 5168 if (targetPkg != null) { 5169 intent.setPackage(targetPkg); 5170 } 5171 // Modify the UID when posting to other users 5172 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 5173 if (uid > 0 && id > 0) { 5174 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 5175 intent.putExtra(Intent.EXTRA_UID, uid); 5176 } 5177 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 5178 am.broadcastIntent(null, intent, null, finishedReceiver, 5179 0, null, null, null, finishedReceiver != null, false, id); 5180 } 5181 } catch (RemoteException ex) { 5182 } 5183 } 5184 } 5185 5186 /** 5187 * Check if the external storage media is available. This is true if there 5188 * is a mounted external storage medium or if the external storage is 5189 * emulated. 5190 */ 5191 private boolean isExternalMediaAvailable() { 5192 return mMediaMounted || Environment.isExternalStorageEmulated(); 5193 } 5194 5195 public String nextPackageToClean(String lastPackage) { 5196 // writer 5197 synchronized (mPackages) { 5198 if (!isExternalMediaAvailable()) { 5199 // If the external storage is no longer mounted at this point, 5200 // the caller may not have been able to delete all of this 5201 // packages files and can not delete any more. Bail. 5202 return null; 5203 } 5204 if (lastPackage != null) { 5205 mSettings.mPackagesToBeCleaned.remove(lastPackage); 5206 } 5207 return mSettings.mPackagesToBeCleaned.size() > 0 5208 ? mSettings.mPackagesToBeCleaned.get(0) : null; 5209 } 5210 } 5211 5212 void schedulePackageCleaning(String packageName) { 5213 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName)); 5214 } 5215 5216 void startCleaningPackages() { 5217 // reader 5218 synchronized (mPackages) { 5219 if (!isExternalMediaAvailable()) { 5220 return; 5221 } 5222 if (mSettings.mPackagesToBeCleaned.size() <= 0) { 5223 return; 5224 } 5225 } 5226 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 5227 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 5228 IActivityManager am = ActivityManagerNative.getDefault(); 5229 if (am != null) { 5230 try { 5231 am.startService(null, intent, null); 5232 } catch (RemoteException e) { 5233 } 5234 } 5235 } 5236 5237 private final class AppDirObserver extends FileObserver { 5238 public AppDirObserver(String path, int mask, boolean isrom) { 5239 super(path, mask); 5240 mRootDir = path; 5241 mIsRom = isrom; 5242 } 5243 5244 public void onEvent(int event, String path) { 5245 String removedPackage = null; 5246 int removedUid = -1; 5247 String addedPackage = null; 5248 int addedUid = -1; 5249 5250 // TODO post a message to the handler to obtain serial ordering 5251 synchronized (mInstallLock) { 5252 String fullPathStr = null; 5253 File fullPath = null; 5254 if (path != null) { 5255 fullPath = new File(mRootDir, path); 5256 fullPathStr = fullPath.getPath(); 5257 } 5258 5259 if (DEBUG_APP_DIR_OBSERVER) 5260 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 5261 5262 if (!isPackageFilename(path)) { 5263 if (DEBUG_APP_DIR_OBSERVER) 5264 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 5265 return; 5266 } 5267 5268 // Ignore packages that are being installed or 5269 // have just been installed. 5270 if (ignoreCodePath(fullPathStr)) { 5271 return; 5272 } 5273 PackageParser.Package p = null; 5274 // reader 5275 synchronized (mPackages) { 5276 p = mAppDirs.get(fullPathStr); 5277 } 5278 if ((event&REMOVE_EVENTS) != 0) { 5279 if (p != null) { 5280 removePackageLI(p, true); 5281 removedPackage = p.applicationInfo.packageName; 5282 removedUid = p.applicationInfo.uid; 5283 } 5284 } 5285 5286 if ((event&ADD_EVENTS) != 0) { 5287 if (p == null) { 5288 p = scanPackageLI(fullPath, 5289 (mIsRom ? PackageParser.PARSE_IS_SYSTEM 5290 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) | 5291 PackageParser.PARSE_CHATTY | 5292 PackageParser.PARSE_MUST_BE_APK, 5293 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 5294 System.currentTimeMillis()); 5295 if (p != null) { 5296 /* 5297 * TODO this seems dangerous as the package may have 5298 * changed since we last acquired the mPackages 5299 * lock. 5300 */ 5301 // writer 5302 synchronized (mPackages) { 5303 updatePermissionsLPw(p.packageName, p, 5304 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 5305 } 5306 addedPackage = p.applicationInfo.packageName; 5307 addedUid = p.applicationInfo.uid; 5308 } 5309 } 5310 } 5311 5312 // reader 5313 synchronized (mPackages) { 5314 mSettings.writeLPr(); 5315 } 5316 } 5317 5318 if (removedPackage != null) { 5319 Bundle extras = new Bundle(1); 5320 extras.putInt(Intent.EXTRA_UID, removedUid); 5321 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 5322 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 5323 extras, null, null, UserHandle.USER_ALL); 5324 } 5325 if (addedPackage != null) { 5326 Bundle extras = new Bundle(1); 5327 extras.putInt(Intent.EXTRA_UID, addedUid); 5328 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 5329 extras, null, null, UserHandle.USER_ALL); 5330 } 5331 } 5332 5333 private final String mRootDir; 5334 private final boolean mIsRom; 5335 } 5336 5337 /* Called when a downloaded package installation has been confirmed by the user */ 5338 public void installPackage( 5339 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 5340 installPackage(packageURI, observer, flags, null); 5341 } 5342 5343 /* Called when a downloaded package installation has been confirmed by the user */ 5344 public void installPackage( 5345 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 5346 final String installerPackageName) { 5347 installPackageWithVerification(packageURI, observer, flags, installerPackageName, null, 5348 null, null); 5349 } 5350 5351 @Override 5352 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 5353 int flags, String installerPackageName, Uri verificationURI, 5354 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 5355 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 5356 manifestDigest); 5357 installPackageWithVerificationAndEncryption(packageURI, observer, flags, 5358 installerPackageName, verificationParams, encryptionParams); 5359 } 5360 5361 public void installPackageWithVerificationAndEncryption(Uri packageURI, 5362 IPackageInstallObserver observer, int flags, String installerPackageName, 5363 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 5364 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 5365 null); 5366 5367 final int uid = Binder.getCallingUid(); 5368 5369 final int filteredFlags; 5370 5371 if (uid == Process.SHELL_UID || uid == 0) { 5372 if (DEBUG_INSTALL) { 5373 Slog.v(TAG, "Install from ADB"); 5374 } 5375 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 5376 } else { 5377 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 5378 } 5379 5380 final Message msg = mHandler.obtainMessage(INIT_COPY); 5381 msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName, 5382 verificationParams, encryptionParams); 5383 mHandler.sendMessage(msg); 5384 } 5385 5386 @Override 5387 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 5388 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 5389 final PackageVerificationResponse response = new PackageVerificationResponse( 5390 verificationCode, Binder.getCallingUid()); 5391 msg.arg1 = id; 5392 msg.obj = response; 5393 mHandler.sendMessage(msg); 5394 } 5395 5396 private ComponentName matchComponentForVerifier(String packageName, 5397 List<ResolveInfo> receivers) { 5398 ActivityInfo targetReceiver = null; 5399 5400 final int NR = receivers.size(); 5401 for (int i = 0; i < NR; i++) { 5402 final ResolveInfo info = receivers.get(i); 5403 if (info.activityInfo == null) { 5404 continue; 5405 } 5406 5407 if (packageName.equals(info.activityInfo.packageName)) { 5408 targetReceiver = info.activityInfo; 5409 break; 5410 } 5411 } 5412 5413 if (targetReceiver == null) { 5414 return null; 5415 } 5416 5417 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 5418 } 5419 5420 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 5421 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 5422 if (pkgInfo.verifiers.length == 0) { 5423 return null; 5424 } 5425 5426 final int N = pkgInfo.verifiers.length; 5427 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 5428 for (int i = 0; i < N; i++) { 5429 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 5430 5431 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 5432 receivers); 5433 if (comp == null) { 5434 continue; 5435 } 5436 5437 final int verifierUid = getUidForVerifier(verifierInfo); 5438 if (verifierUid == -1) { 5439 continue; 5440 } 5441 5442 if (DEBUG_VERIFY) { 5443 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 5444 + " with the correct signature"); 5445 } 5446 sufficientVerifiers.add(comp); 5447 verificationState.addSufficientVerifier(verifierUid); 5448 } 5449 5450 return sufficientVerifiers; 5451 } 5452 5453 private int getUidForVerifier(VerifierInfo verifierInfo) { 5454 synchronized (mPackages) { 5455 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 5456 if (pkg == null) { 5457 return -1; 5458 } else if (pkg.mSignatures.length != 1) { 5459 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 5460 + " has more than one signature; ignoring"); 5461 return -1; 5462 } 5463 5464 /* 5465 * If the public key of the package's signature does not match 5466 * our expected public key, then this is a different package and 5467 * we should skip. 5468 */ 5469 5470 final byte[] expectedPublicKey; 5471 try { 5472 final Signature verifierSig = pkg.mSignatures[0]; 5473 final PublicKey publicKey = verifierSig.getPublicKey(); 5474 expectedPublicKey = publicKey.getEncoded(); 5475 } catch (CertificateException e) { 5476 return -1; 5477 } 5478 5479 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 5480 5481 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 5482 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 5483 + " does not have the expected public key; ignoring"); 5484 return -1; 5485 } 5486 5487 return pkg.applicationInfo.uid; 5488 } 5489 } 5490 5491 public void finishPackageInstall(int token) { 5492 enforceSystemOrRoot("Only the system is allowed to finish installs"); 5493 5494 if (DEBUG_INSTALL) { 5495 Slog.v(TAG, "BM finishing package install for " + token); 5496 } 5497 5498 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 5499 mHandler.sendMessage(msg); 5500 } 5501 5502 /** 5503 * Get the verification agent timeout. 5504 * 5505 * @return verification timeout in milliseconds 5506 */ 5507 private long getVerificationTimeout() { 5508 return android.provider.Settings.Secure.getLong(mContext.getContentResolver(), 5509 android.provider.Settings.Secure.PACKAGE_VERIFIER_TIMEOUT, 5510 DEFAULT_VERIFICATION_TIMEOUT); 5511 } 5512 5513 /** 5514 * Get the default verification agent response code. 5515 * 5516 * @return default verification response code 5517 */ 5518 private int getDefaultVerificationResponse() { 5519 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 5520 android.provider.Settings.Secure.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 5521 DEFAULT_VERIFICATION_RESPONSE); 5522 } 5523 5524 /** 5525 * Check whether or not package verification has been enabled. 5526 * 5527 * @return true if verification should be performed 5528 */ 5529 private boolean isVerificationEnabled() { 5530 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 5531 android.provider.Settings.Secure.PACKAGE_VERIFIER_ENABLE, 5532 DEFAULT_VERIFY_ENABLE ? 1 : 0) == 1 ? true : false; 5533 } 5534 5535 /** 5536 * Get the "allow unknown sources" setting. 5537 * 5538 * @return the current "allow unknown sources" setting 5539 */ 5540 private int getUnknownSourcesSettings() { 5541 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 5542 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 5543 -1); 5544 } 5545 5546 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 5547 final int uid = Binder.getCallingUid(); 5548 // writer 5549 synchronized (mPackages) { 5550 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 5551 if (targetPackageSetting == null) { 5552 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 5553 } 5554 5555 PackageSetting installerPackageSetting; 5556 if (installerPackageName != null) { 5557 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 5558 if (installerPackageSetting == null) { 5559 throw new IllegalArgumentException("Unknown installer package: " 5560 + installerPackageName); 5561 } 5562 } else { 5563 installerPackageSetting = null; 5564 } 5565 5566 Signature[] callerSignature; 5567 Object obj = mSettings.getUserIdLPr(uid); 5568 if (obj != null) { 5569 if (obj instanceof SharedUserSetting) { 5570 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 5571 } else if (obj instanceof PackageSetting) { 5572 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 5573 } else { 5574 throw new SecurityException("Bad object " + obj + " for uid " + uid); 5575 } 5576 } else { 5577 throw new SecurityException("Unknown calling uid " + uid); 5578 } 5579 5580 // Verify: can't set installerPackageName to a package that is 5581 // not signed with the same cert as the caller. 5582 if (installerPackageSetting != null) { 5583 if (compareSignatures(callerSignature, 5584 installerPackageSetting.signatures.mSignatures) 5585 != PackageManager.SIGNATURE_MATCH) { 5586 throw new SecurityException( 5587 "Caller does not have same cert as new installer package " 5588 + installerPackageName); 5589 } 5590 } 5591 5592 // Verify: if target already has an installer package, it must 5593 // be signed with the same cert as the caller. 5594 if (targetPackageSetting.installerPackageName != null) { 5595 PackageSetting setting = mSettings.mPackages.get( 5596 targetPackageSetting.installerPackageName); 5597 // If the currently set package isn't valid, then it's always 5598 // okay to change it. 5599 if (setting != null) { 5600 if (compareSignatures(callerSignature, 5601 setting.signatures.mSignatures) 5602 != PackageManager.SIGNATURE_MATCH) { 5603 throw new SecurityException( 5604 "Caller does not have same cert as old installer package " 5605 + targetPackageSetting.installerPackageName); 5606 } 5607 } 5608 } 5609 5610 // Okay! 5611 targetPackageSetting.installerPackageName = installerPackageName; 5612 scheduleWriteSettingsLocked(); 5613 } 5614 } 5615 5616 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 5617 // Queue up an async operation since the package installation may take a little while. 5618 mHandler.post(new Runnable() { 5619 public void run() { 5620 mHandler.removeCallbacks(this); 5621 // Result object to be returned 5622 PackageInstalledInfo res = new PackageInstalledInfo(); 5623 res.returnCode = currentStatus; 5624 res.uid = -1; 5625 res.pkg = null; 5626 res.removedInfo = new PackageRemovedInfo(); 5627 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 5628 args.doPreInstall(res.returnCode); 5629 synchronized (mInstallLock) { 5630 installPackageLI(args, true, res); 5631 } 5632 args.doPostInstall(res.returnCode, res.uid); 5633 } 5634 5635 // A restore should be performed at this point if (a) the install 5636 // succeeded, (b) the operation is not an update, and (c) the new 5637 // package has a backupAgent defined. 5638 final boolean update = res.removedInfo.removedPackage != null; 5639 boolean doRestore = (!update 5640 && res.pkg != null 5641 && res.pkg.applicationInfo.backupAgentName != null); 5642 5643 // Set up the post-install work request bookkeeping. This will be used 5644 // and cleaned up by the post-install event handling regardless of whether 5645 // there's a restore pass performed. Token values are >= 1. 5646 int token; 5647 if (mNextInstallToken < 0) mNextInstallToken = 1; 5648 token = mNextInstallToken++; 5649 5650 PostInstallData data = new PostInstallData(args, res); 5651 mRunningInstalls.put(token, data); 5652 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 5653 5654 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 5655 // Pass responsibility to the Backup Manager. It will perform a 5656 // restore if appropriate, then pass responsibility back to the 5657 // Package Manager to run the post-install observer callbacks 5658 // and broadcasts. 5659 IBackupManager bm = IBackupManager.Stub.asInterface( 5660 ServiceManager.getService(Context.BACKUP_SERVICE)); 5661 if (bm != null) { 5662 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 5663 + " to BM for possible restore"); 5664 try { 5665 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 5666 } catch (RemoteException e) { 5667 // can't happen; the backup manager is local 5668 } catch (Exception e) { 5669 Slog.e(TAG, "Exception trying to enqueue restore", e); 5670 doRestore = false; 5671 } 5672 } else { 5673 Slog.e(TAG, "Backup Manager not found!"); 5674 doRestore = false; 5675 } 5676 } 5677 5678 if (!doRestore) { 5679 // No restore possible, or the Backup Manager was mysteriously not 5680 // available -- just fire the post-install work request directly. 5681 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 5682 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 5683 mHandler.sendMessage(msg); 5684 } 5685 } 5686 }); 5687 } 5688 5689 private abstract class HandlerParams { 5690 private static final int MAX_RETRIES = 4; 5691 5692 /** 5693 * Number of times startCopy() has been attempted and had a non-fatal 5694 * error. 5695 */ 5696 private int mRetries = 0; 5697 5698 final boolean startCopy() { 5699 boolean res; 5700 try { 5701 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy"); 5702 5703 if (++mRetries > MAX_RETRIES) { 5704 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 5705 mHandler.sendEmptyMessage(MCS_GIVE_UP); 5706 handleServiceError(); 5707 return false; 5708 } else { 5709 handleStartCopy(); 5710 res = true; 5711 } 5712 } catch (RemoteException e) { 5713 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 5714 mHandler.sendEmptyMessage(MCS_RECONNECT); 5715 res = false; 5716 } 5717 handleReturnCode(); 5718 return res; 5719 } 5720 5721 final void serviceError() { 5722 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 5723 handleServiceError(); 5724 handleReturnCode(); 5725 } 5726 5727 abstract void handleStartCopy() throws RemoteException; 5728 abstract void handleServiceError(); 5729 abstract void handleReturnCode(); 5730 } 5731 5732 class MeasureParams extends HandlerParams { 5733 private final PackageStats mStats; 5734 private boolean mSuccess; 5735 5736 private final IPackageStatsObserver mObserver; 5737 5738 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 5739 mObserver = observer; 5740 mStats = stats; 5741 } 5742 5743 @Override 5744 void handleStartCopy() throws RemoteException { 5745 synchronized (mInstallLock) { 5746 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats); 5747 } 5748 5749 final boolean mounted; 5750 if (Environment.isExternalStorageEmulated()) { 5751 mounted = true; 5752 } else { 5753 final String status = Environment.getExternalStorageState(); 5754 5755 mounted = status.equals(Environment.MEDIA_MOUNTED) 5756 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 5757 } 5758 5759 if (mounted) { 5760 final File externalCacheDir = Environment 5761 .getExternalStorageAppCacheDirectory(mStats.packageName); 5762 final long externalCacheSize = mContainerService 5763 .calculateDirectorySize(externalCacheDir.getPath()); 5764 mStats.externalCacheSize = externalCacheSize; 5765 5766 final File externalDataDir = Environment 5767 .getExternalStorageAppDataDirectory(mStats.packageName); 5768 long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir 5769 .getPath()); 5770 5771 if (externalCacheDir.getParentFile().equals(externalDataDir)) { 5772 externalDataSize -= externalCacheSize; 5773 } 5774 mStats.externalDataSize = externalDataSize; 5775 5776 final File externalMediaDir = Environment 5777 .getExternalStorageAppMediaDirectory(mStats.packageName); 5778 mStats.externalMediaSize = mContainerService 5779 .calculateDirectorySize(externalMediaDir.getPath()); 5780 5781 final File externalObbDir = Environment 5782 .getExternalStorageAppObbDirectory(mStats.packageName); 5783 mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir 5784 .getPath()); 5785 } 5786 } 5787 5788 @Override 5789 void handleReturnCode() { 5790 if (mObserver != null) { 5791 try { 5792 mObserver.onGetStatsCompleted(mStats, mSuccess); 5793 } catch (RemoteException e) { 5794 Slog.i(TAG, "Observer no longer exists."); 5795 } 5796 } 5797 } 5798 5799 @Override 5800 void handleServiceError() { 5801 Slog.e(TAG, "Could not measure application " + mStats.packageName 5802 + " external storage"); 5803 } 5804 } 5805 5806 class InstallParams extends HandlerParams { 5807 final IPackageInstallObserver observer; 5808 int flags; 5809 5810 private final Uri mPackageURI; 5811 final String installerPackageName; 5812 final VerificationParams verificationParams; 5813 private InstallArgs mArgs; 5814 private int mRet; 5815 private File mTempPackage; 5816 final ContainerEncryptionParams encryptionParams; 5817 5818 InstallParams(Uri packageURI, 5819 IPackageInstallObserver observer, int flags, 5820 String installerPackageName, VerificationParams verificationParams, 5821 ContainerEncryptionParams encryptionParams) { 5822 this.mPackageURI = packageURI; 5823 this.flags = flags; 5824 this.observer = observer; 5825 this.installerPackageName = installerPackageName; 5826 this.verificationParams = verificationParams; 5827 this.encryptionParams = encryptionParams; 5828 } 5829 5830 public ManifestDigest getManifestDigest() { 5831 if (verificationParams == null) { 5832 return null; 5833 } 5834 return verificationParams.getManifestDigest(); 5835 } 5836 5837 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 5838 String packageName = pkgLite.packageName; 5839 int installLocation = pkgLite.installLocation; 5840 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 5841 // reader 5842 synchronized (mPackages) { 5843 PackageParser.Package pkg = mPackages.get(packageName); 5844 if (pkg != null) { 5845 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5846 // Check for updated system application. 5847 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 5848 if (onSd) { 5849 Slog.w(TAG, "Cannot install update to system app on sdcard"); 5850 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 5851 } 5852 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 5853 } else { 5854 if (onSd) { 5855 // Install flag overrides everything. 5856 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 5857 } 5858 // If current upgrade specifies particular preference 5859 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 5860 // Application explicitly specified internal. 5861 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 5862 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 5863 // App explictly prefers external. Let policy decide 5864 } else { 5865 // Prefer previous location 5866 if (isExternal(pkg)) { 5867 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 5868 } 5869 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 5870 } 5871 } 5872 } else { 5873 // Invalid install. Return error code 5874 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 5875 } 5876 } 5877 } 5878 // All the special cases have been taken care of. 5879 // Return result based on recommended install location. 5880 if (onSd) { 5881 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 5882 } 5883 return pkgLite.recommendedInstallLocation; 5884 } 5885 5886 /* 5887 * Invoke remote method to get package information and install 5888 * location values. Override install location based on default 5889 * policy if needed and then create install arguments based 5890 * on the install location. 5891 */ 5892 public void handleStartCopy() throws RemoteException { 5893 int ret = PackageManager.INSTALL_SUCCEEDED; 5894 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 5895 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 5896 PackageInfoLite pkgLite = null; 5897 5898 if (onInt && onSd) { 5899 // Check if both bits are set. 5900 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 5901 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 5902 } else { 5903 final long lowThreshold; 5904 5905 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 5906 .getService(DeviceStorageMonitorService.SERVICE); 5907 if (dsm == null) { 5908 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 5909 lowThreshold = 0L; 5910 } else { 5911 lowThreshold = dsm.getMemoryLowThreshold(); 5912 } 5913 5914 try { 5915 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 5916 Intent.FLAG_GRANT_READ_URI_PERMISSION); 5917 5918 final File packageFile; 5919 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 5920 ParcelFileDescriptor out = null; 5921 5922 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 5923 if (mTempPackage != null) { 5924 try { 5925 out = ParcelFileDescriptor.open(mTempPackage, 5926 ParcelFileDescriptor.MODE_READ_WRITE); 5927 } catch (FileNotFoundException e) { 5928 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 5929 } 5930 5931 // Make a temporary file for decryption. 5932 ret = mContainerService 5933 .copyResource(mPackageURI, encryptionParams, out); 5934 5935 packageFile = mTempPackage; 5936 5937 FileUtils.setPermissions(packageFile.getAbsolutePath(), 5938 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IROTH, 5939 -1, -1); 5940 } else { 5941 packageFile = null; 5942 } 5943 } else { 5944 packageFile = new File(mPackageURI.getPath()); 5945 } 5946 5947 if (packageFile != null) { 5948 // Remote call to find out default install location 5949 pkgLite = mContainerService.getMinimalPackageInfo( 5950 packageFile.getAbsolutePath(), flags, lowThreshold); 5951 } 5952 } finally { 5953 mContext.revokeUriPermission(mPackageURI, 5954 Intent.FLAG_GRANT_READ_URI_PERMISSION); 5955 } 5956 } 5957 5958 if (ret == PackageManager.INSTALL_SUCCEEDED) { 5959 int loc = pkgLite.recommendedInstallLocation; 5960 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 5961 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 5962 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 5963 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 5964 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 5965 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5966 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 5967 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 5968 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 5969 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 5970 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 5971 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 5972 } else { 5973 // Override with defaults if needed. 5974 loc = installLocationPolicy(pkgLite, flags); 5975 if (!onSd && !onInt) { 5976 // Override install location with flags 5977 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 5978 // Set the flag to install on external media. 5979 flags |= PackageManager.INSTALL_EXTERNAL; 5980 flags &= ~PackageManager.INSTALL_INTERNAL; 5981 } else { 5982 // Make sure the flag for installing on external 5983 // media is unset 5984 flags |= PackageManager.INSTALL_INTERNAL; 5985 flags &= ~PackageManager.INSTALL_EXTERNAL; 5986 } 5987 } 5988 } 5989 } 5990 5991 final InstallArgs args = createInstallArgs(this); 5992 mArgs = args; 5993 5994 if (ret == PackageManager.INSTALL_SUCCEEDED) { 5995 /* 5996 * Determine if we have any installed package verifiers. If we 5997 * do, then we'll defer to them to verify the packages. 5998 */ 5999 final int requiredUid = mRequiredVerifierPackage == null ? -1 6000 : getPackageUid(mRequiredVerifierPackage, 0); 6001 if (requiredUid != -1 && isVerificationEnabled()) { 6002 final Intent verification = new Intent( 6003 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 6004 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 6005 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 6006 6007 final List<ResolveInfo> receivers = queryIntentReceivers(verification, null, 6008 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 6009 6010 if (DEBUG_VERIFY) { 6011 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 6012 + verification.toString() + " with " + pkgLite.verifiers.length 6013 + " optional verifiers"); 6014 } 6015 6016 final int verificationId = mPendingVerificationToken++; 6017 6018 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 6019 6020 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 6021 installerPackageName); 6022 6023 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 6024 6025 if (verificationParams != null) { 6026 if (verificationParams.getVerificationURI() != null) { 6027 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 6028 verificationParams.getVerificationURI()); 6029 } 6030 if (verificationParams.getOriginatingURI() != null) { 6031 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 6032 verificationParams.getOriginatingURI()); 6033 } 6034 if (verificationParams.getReferrer() != null) { 6035 verification.putExtra(Intent.EXTRA_REFERRER, 6036 verificationParams.getReferrer()); 6037 } 6038 } 6039 6040 final PackageVerificationState verificationState = new PackageVerificationState( 6041 requiredUid, args); 6042 6043 mPendingVerification.append(verificationId, verificationState); 6044 6045 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 6046 receivers, verificationState); 6047 6048 /* 6049 * If any sufficient verifiers were listed in the package 6050 * manifest, attempt to ask them. 6051 */ 6052 if (sufficientVerifiers != null) { 6053 final int N = sufficientVerifiers.size(); 6054 if (N == 0) { 6055 Slog.i(TAG, "Additional verifiers required, but none installed."); 6056 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 6057 } else { 6058 for (int i = 0; i < N; i++) { 6059 final ComponentName verifierComponent = sufficientVerifiers.get(i); 6060 6061 final Intent sufficientIntent = new Intent(verification); 6062 sufficientIntent.setComponent(verifierComponent); 6063 6064 mContext.sendBroadcast(sufficientIntent); 6065 } 6066 } 6067 } 6068 6069 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 6070 mRequiredVerifierPackage, receivers); 6071 if (ret == PackageManager.INSTALL_SUCCEEDED 6072 && mRequiredVerifierPackage != null) { 6073 /* 6074 * Send the intent to the required verification agent, 6075 * but only start the verification timeout after the 6076 * target BroadcastReceivers have run. 6077 */ 6078 verification.setComponent(requiredVerifierComponent); 6079 mContext.sendOrderedBroadcast(verification, 6080 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 6081 new BroadcastReceiver() { 6082 @Override 6083 public void onReceive(Context context, Intent intent) { 6084 final Message msg = mHandler 6085 .obtainMessage(CHECK_PENDING_VERIFICATION); 6086 msg.arg1 = verificationId; 6087 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 6088 } 6089 }, null, 0, null, null); 6090 6091 /* 6092 * We don't want the copy to proceed until verification 6093 * succeeds, so null out this field. 6094 */ 6095 mArgs = null; 6096 } 6097 } else { 6098 /* 6099 * No package verification is enabled, so immediately start 6100 * the remote call to initiate copy using temporary file. 6101 */ 6102 ret = args.copyApk(mContainerService, true); 6103 } 6104 } 6105 6106 mRet = ret; 6107 } 6108 6109 @Override 6110 void handleReturnCode() { 6111 // If mArgs is null, then MCS couldn't be reached. When it 6112 // reconnects, it will try again to install. At that point, this 6113 // will succeed. 6114 if (mArgs != null) { 6115 processPendingInstall(mArgs, mRet); 6116 } 6117 6118 if (mTempPackage != null) { 6119 if (!mTempPackage.delete()) { 6120 Slog.w(TAG, "Couldn't delete temporary file: " 6121 + mTempPackage.getAbsolutePath()); 6122 } 6123 } 6124 } 6125 6126 @Override 6127 void handleServiceError() { 6128 mArgs = createInstallArgs(this); 6129 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 6130 } 6131 6132 public boolean isForwardLocked() { 6133 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6134 } 6135 6136 public Uri getPackageUri() { 6137 if (mTempPackage != null) { 6138 return Uri.fromFile(mTempPackage); 6139 } else { 6140 return mPackageURI; 6141 } 6142 } 6143 } 6144 6145 /* 6146 * Utility class used in movePackage api. 6147 * srcArgs and targetArgs are not set for invalid flags and make 6148 * sure to do null checks when invoking methods on them. 6149 * We probably want to return ErrorPrams for both failed installs 6150 * and moves. 6151 */ 6152 class MoveParams extends HandlerParams { 6153 final IPackageMoveObserver observer; 6154 final int flags; 6155 final String packageName; 6156 final InstallArgs srcArgs; 6157 final InstallArgs targetArgs; 6158 int uid; 6159 int mRet; 6160 6161 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 6162 String packageName, String dataDir, int uid) { 6163 this.srcArgs = srcArgs; 6164 this.observer = observer; 6165 this.flags = flags; 6166 this.packageName = packageName; 6167 this.uid = uid; 6168 if (srcArgs != null) { 6169 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 6170 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir); 6171 } else { 6172 targetArgs = null; 6173 } 6174 } 6175 6176 public void handleStartCopy() throws RemoteException { 6177 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6178 // Check for storage space on target medium 6179 if (!targetArgs.checkFreeStorage(mContainerService)) { 6180 Log.w(TAG, "Insufficient storage to install"); 6181 return; 6182 } 6183 6184 mRet = srcArgs.doPreCopy(); 6185 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6186 return; 6187 } 6188 6189 mRet = targetArgs.copyApk(mContainerService, false); 6190 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6191 srcArgs.doPostCopy(uid); 6192 return; 6193 } 6194 6195 mRet = srcArgs.doPostCopy(uid); 6196 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6197 return; 6198 } 6199 6200 mRet = targetArgs.doPreInstall(mRet); 6201 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6202 return; 6203 } 6204 6205 if (DEBUG_SD_INSTALL) { 6206 StringBuilder builder = new StringBuilder(); 6207 if (srcArgs != null) { 6208 builder.append("src: "); 6209 builder.append(srcArgs.getCodePath()); 6210 } 6211 if (targetArgs != null) { 6212 builder.append(" target : "); 6213 builder.append(targetArgs.getCodePath()); 6214 } 6215 Log.i(TAG, builder.toString()); 6216 } 6217 } 6218 6219 @Override 6220 void handleReturnCode() { 6221 targetArgs.doPostInstall(mRet, uid); 6222 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 6223 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 6224 currentStatus = PackageManager.MOVE_SUCCEEDED; 6225 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 6226 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 6227 } 6228 processPendingMove(this, currentStatus); 6229 } 6230 6231 @Override 6232 void handleServiceError() { 6233 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 6234 } 6235 } 6236 6237 /** 6238 * Used during creation of InstallArgs 6239 * 6240 * @param flags package installation flags 6241 * @return true if should be installed on external storage 6242 */ 6243 private static boolean installOnSd(int flags) { 6244 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 6245 return false; 6246 } 6247 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 6248 return true; 6249 } 6250 return false; 6251 } 6252 6253 /** 6254 * Used during creation of InstallArgs 6255 * 6256 * @param flags package installation flags 6257 * @return true if should be installed as forward locked 6258 */ 6259 private static boolean installForwardLocked(int flags) { 6260 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6261 } 6262 6263 private InstallArgs createInstallArgs(InstallParams params) { 6264 if (installOnSd(params.flags) || params.isForwardLocked()) { 6265 return new AsecInstallArgs(params); 6266 } else { 6267 return new FileInstallArgs(params); 6268 } 6269 } 6270 6271 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 6272 String nativeLibraryPath) { 6273 final boolean isInAsec; 6274 if (installOnSd(flags)) { 6275 /* Apps on SD card are always in ASEC containers. */ 6276 isInAsec = true; 6277 } else if (installForwardLocked(flags) 6278 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 6279 /* 6280 * Forward-locked apps are only in ASEC containers if they're the 6281 * new style 6282 */ 6283 isInAsec = true; 6284 } else { 6285 isInAsec = false; 6286 } 6287 6288 if (isInAsec) { 6289 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 6290 installOnSd(flags), installForwardLocked(flags)); 6291 } else { 6292 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath); 6293 } 6294 } 6295 6296 // Used by package mover 6297 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) { 6298 if (installOnSd(flags) || installForwardLocked(flags)) { 6299 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 6300 + AsecInstallArgs.RES_FILE_NAME); 6301 return new AsecInstallArgs(packageURI, cid, installOnSd(flags), 6302 installForwardLocked(flags)); 6303 } else { 6304 return new FileInstallArgs(packageURI, pkgName, dataDir); 6305 } 6306 } 6307 6308 static abstract class InstallArgs { 6309 final IPackageInstallObserver observer; 6310 // Always refers to PackageManager flags only 6311 final int flags; 6312 final Uri packageURI; 6313 final String installerPackageName; 6314 final ManifestDigest manifestDigest; 6315 6316 InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags, 6317 String installerPackageName, ManifestDigest manifestDigest) { 6318 this.packageURI = packageURI; 6319 this.flags = flags; 6320 this.observer = observer; 6321 this.installerPackageName = installerPackageName; 6322 this.manifestDigest = manifestDigest; 6323 } 6324 6325 abstract void createCopyFile(); 6326 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 6327 abstract int doPreInstall(int status); 6328 abstract boolean doRename(int status, String pkgName, String oldCodePath); 6329 6330 abstract int doPostInstall(int status, int uid); 6331 abstract String getCodePath(); 6332 abstract String getResourcePath(); 6333 abstract String getNativeLibraryPath(); 6334 // Need installer lock especially for dex file removal. 6335 abstract void cleanUpResourcesLI(); 6336 abstract boolean doPostDeleteLI(boolean delete); 6337 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 6338 6339 /** 6340 * Called before the source arguments are copied. This is used mostly 6341 * for MoveParams when it needs to read the source file to put it in the 6342 * destination. 6343 */ 6344 int doPreCopy() { 6345 return PackageManager.INSTALL_SUCCEEDED; 6346 } 6347 6348 /** 6349 * Called after the source arguments are copied. This is used mostly for 6350 * MoveParams when it needs to read the source file to put it in the 6351 * destination. 6352 * 6353 * @return 6354 */ 6355 int doPostCopy(int uid) { 6356 return PackageManager.INSTALL_SUCCEEDED; 6357 } 6358 6359 protected boolean isFwdLocked() { 6360 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6361 } 6362 } 6363 6364 class FileInstallArgs extends InstallArgs { 6365 File installDir; 6366 String codeFileName; 6367 String resourceFileName; 6368 String libraryPath; 6369 boolean created = false; 6370 6371 FileInstallArgs(InstallParams params) { 6372 super(params.getPackageUri(), params.observer, params.flags, 6373 params.installerPackageName, params.getManifestDigest()); 6374 } 6375 6376 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) { 6377 super(null, null, 0, null, null); 6378 File codeFile = new File(fullCodePath); 6379 installDir = codeFile.getParentFile(); 6380 codeFileName = fullCodePath; 6381 resourceFileName = fullResourcePath; 6382 libraryPath = nativeLibraryPath; 6383 } 6384 6385 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) { 6386 super(packageURI, null, 0, null, null); 6387 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 6388 String apkName = getNextCodePath(null, pkgName, ".apk"); 6389 codeFileName = new File(installDir, apkName + ".apk").getPath(); 6390 resourceFileName = getResourcePathFromCodePath(); 6391 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath(); 6392 } 6393 6394 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 6395 final long lowThreshold; 6396 6397 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 6398 .getService(DeviceStorageMonitorService.SERVICE); 6399 if (dsm == null) { 6400 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 6401 lowThreshold = 0L; 6402 } else { 6403 if (dsm.isMemoryLow()) { 6404 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 6405 return false; 6406 } 6407 6408 lowThreshold = dsm.getMemoryLowThreshold(); 6409 } 6410 6411 try { 6412 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 6413 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6414 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 6415 } finally { 6416 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 6417 } 6418 } 6419 6420 String getCodePath() { 6421 return codeFileName; 6422 } 6423 6424 void createCopyFile() { 6425 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 6426 codeFileName = createTempPackageFile(installDir).getPath(); 6427 resourceFileName = getResourcePathFromCodePath(); 6428 created = true; 6429 } 6430 6431 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 6432 if (temp) { 6433 // Generate temp file name 6434 createCopyFile(); 6435 } 6436 // Get a ParcelFileDescriptor to write to the output file 6437 File codeFile = new File(codeFileName); 6438 if (!created) { 6439 try { 6440 codeFile.createNewFile(); 6441 // Set permissions 6442 if (!setPermissions()) { 6443 // Failed setting permissions. 6444 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6445 } 6446 } catch (IOException e) { 6447 Slog.w(TAG, "Failed to create file " + codeFile); 6448 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6449 } 6450 } 6451 ParcelFileDescriptor out = null; 6452 try { 6453 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 6454 } catch (FileNotFoundException e) { 6455 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 6456 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6457 } 6458 // Copy the resource now 6459 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6460 try { 6461 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 6462 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6463 ret = imcs.copyResource(packageURI, null, out); 6464 } finally { 6465 IoUtils.closeQuietly(out); 6466 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 6467 } 6468 6469 if (isFwdLocked()) { 6470 final File destResourceFile = new File(getResourcePath()); 6471 6472 // Copy the public files 6473 try { 6474 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 6475 } catch (IOException e) { 6476 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 6477 + " forward-locked app."); 6478 destResourceFile.delete(); 6479 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6480 } 6481 } 6482 return ret; 6483 } 6484 6485 int doPreInstall(int status) { 6486 if (status != PackageManager.INSTALL_SUCCEEDED) { 6487 cleanUp(); 6488 } 6489 return status; 6490 } 6491 6492 boolean doRename(int status, final String pkgName, String oldCodePath) { 6493 if (status != PackageManager.INSTALL_SUCCEEDED) { 6494 cleanUp(); 6495 return false; 6496 } else { 6497 final File oldCodeFile = new File(getCodePath()); 6498 final File oldResourceFile = new File(getResourcePath()); 6499 6500 // Rename APK file based on packageName 6501 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 6502 final File newCodeFile = new File(installDir, apkName + ".apk"); 6503 if (!oldCodeFile.renameTo(newCodeFile)) { 6504 return false; 6505 } 6506 codeFileName = newCodeFile.getPath(); 6507 6508 // Rename public resource file if it's forward-locked. 6509 final File newResFile = new File(getResourcePathFromCodePath()); 6510 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 6511 return false; 6512 } 6513 resourceFileName = getResourcePathFromCodePath(); 6514 6515 // Attempt to set permissions 6516 if (!setPermissions()) { 6517 return false; 6518 } 6519 6520 if (!SELinux.restorecon(newCodeFile)) { 6521 return false; 6522 } 6523 6524 return true; 6525 } 6526 } 6527 6528 int doPostInstall(int status, int uid) { 6529 if (status != PackageManager.INSTALL_SUCCEEDED) { 6530 cleanUp(); 6531 } 6532 return status; 6533 } 6534 6535 String getResourcePath() { 6536 return resourceFileName; 6537 } 6538 6539 private String getResourcePathFromCodePath() { 6540 final String codePath = getCodePath(); 6541 if (isFwdLocked()) { 6542 final StringBuilder sb = new StringBuilder(); 6543 6544 sb.append(mAppInstallDir.getPath()); 6545 sb.append('/'); 6546 sb.append(getApkName(codePath)); 6547 sb.append(".zip"); 6548 6549 /* 6550 * If our APK is a temporary file, mark the resource as a 6551 * temporary file as well so it can be cleaned up after 6552 * catastrophic failure. 6553 */ 6554 if (codePath.endsWith(".tmp")) { 6555 sb.append(".tmp"); 6556 } 6557 6558 return sb.toString(); 6559 } else { 6560 return codePath; 6561 } 6562 } 6563 6564 @Override 6565 String getNativeLibraryPath() { 6566 return libraryPath; 6567 } 6568 6569 private boolean cleanUp() { 6570 boolean ret = true; 6571 String sourceDir = getCodePath(); 6572 String publicSourceDir = getResourcePath(); 6573 if (sourceDir != null) { 6574 File sourceFile = new File(sourceDir); 6575 if (!sourceFile.exists()) { 6576 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 6577 ret = false; 6578 } 6579 // Delete application's code and resources 6580 sourceFile.delete(); 6581 } 6582 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 6583 final File publicSourceFile = new File(publicSourceDir); 6584 if (!publicSourceFile.exists()) { 6585 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 6586 } 6587 if (publicSourceFile.exists()) { 6588 publicSourceFile.delete(); 6589 } 6590 } 6591 return ret; 6592 } 6593 6594 void cleanUpResourcesLI() { 6595 String sourceDir = getCodePath(); 6596 if (cleanUp()) { 6597 int retCode = mInstaller.rmdex(sourceDir); 6598 if (retCode < 0) { 6599 Slog.w(TAG, "Couldn't remove dex file for package: " 6600 + " at location " 6601 + sourceDir + ", retcode=" + retCode); 6602 // we don't consider this to be a failure of the core package deletion 6603 } 6604 } 6605 } 6606 6607 private boolean setPermissions() { 6608 // TODO Do this in a more elegant way later on. for now just a hack 6609 if (!isFwdLocked()) { 6610 final int filePermissions = 6611 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 6612 |FileUtils.S_IROTH; 6613 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 6614 if (retCode != 0) { 6615 Slog.e(TAG, "Couldn't set new package file permissions for " + 6616 getCodePath() 6617 + ". The return code was: " + retCode); 6618 // TODO Define new internal error 6619 return false; 6620 } 6621 return true; 6622 } 6623 return true; 6624 } 6625 6626 boolean doPostDeleteLI(boolean delete) { 6627 // XXX err, shouldn't we respect the delete flag? 6628 cleanUpResourcesLI(); 6629 return true; 6630 } 6631 } 6632 6633 private boolean isAsecExternal(String cid) { 6634 final String asecPath = PackageHelper.getSdFilesystem(cid); 6635 return !asecPath.startsWith(mAsecInternalPath); 6636 } 6637 6638 /** 6639 * Extract the MountService "container ID" from the full code path of an 6640 * .apk. 6641 */ 6642 static String cidFromCodePath(String fullCodePath) { 6643 int eidx = fullCodePath.lastIndexOf("/"); 6644 String subStr1 = fullCodePath.substring(0, eidx); 6645 int sidx = subStr1.lastIndexOf("/"); 6646 return subStr1.substring(sidx+1, eidx); 6647 } 6648 6649 class AsecInstallArgs extends InstallArgs { 6650 static final String RES_FILE_NAME = "pkg.apk"; 6651 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 6652 6653 String cid; 6654 String packagePath; 6655 String resourcePath; 6656 String libraryPath; 6657 6658 AsecInstallArgs(InstallParams params) { 6659 super(params.getPackageUri(), params.observer, params.flags, 6660 params.installerPackageName, params.getManifestDigest()); 6661 } 6662 6663 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 6664 boolean isExternal, boolean isForwardLocked) { 6665 super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 6666 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), null, null); 6667 // Extract cid from fullCodePath 6668 int eidx = fullCodePath.lastIndexOf("/"); 6669 String subStr1 = fullCodePath.substring(0, eidx); 6670 int sidx = subStr1.lastIndexOf("/"); 6671 cid = subStr1.substring(sidx+1, eidx); 6672 setCachePath(subStr1); 6673 } 6674 6675 AsecInstallArgs(String cid, boolean isForwardLocked) { 6676 super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 6677 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), null, null); 6678 this.cid = cid; 6679 setCachePath(PackageHelper.getSdDir(cid)); 6680 } 6681 6682 AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) { 6683 super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 6684 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), null, null); 6685 this.cid = cid; 6686 } 6687 6688 void createCopyFile() { 6689 cid = getTempContainerId(); 6690 } 6691 6692 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 6693 try { 6694 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 6695 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6696 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked()); 6697 } finally { 6698 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 6699 } 6700 } 6701 6702 private final boolean isExternal() { 6703 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 6704 } 6705 6706 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 6707 if (temp) { 6708 createCopyFile(); 6709 } else { 6710 /* 6711 * Pre-emptively destroy the container since it's destroyed if 6712 * copying fails due to it existing anyway. 6713 */ 6714 PackageHelper.destroySdDir(cid); 6715 } 6716 6717 final String newCachePath; 6718 try { 6719 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 6720 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6721 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 6722 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked()); 6723 } finally { 6724 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 6725 } 6726 6727 if (newCachePath != null) { 6728 setCachePath(newCachePath); 6729 return PackageManager.INSTALL_SUCCEEDED; 6730 } else { 6731 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 6732 } 6733 } 6734 6735 @Override 6736 String getCodePath() { 6737 return packagePath; 6738 } 6739 6740 @Override 6741 String getResourcePath() { 6742 return resourcePath; 6743 } 6744 6745 @Override 6746 String getNativeLibraryPath() { 6747 return libraryPath; 6748 } 6749 6750 int doPreInstall(int status) { 6751 if (status != PackageManager.INSTALL_SUCCEEDED) { 6752 // Destroy container 6753 PackageHelper.destroySdDir(cid); 6754 } else { 6755 boolean mounted = PackageHelper.isContainerMounted(cid); 6756 if (!mounted) { 6757 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 6758 Process.SYSTEM_UID); 6759 if (newCachePath != null) { 6760 setCachePath(newCachePath); 6761 } else { 6762 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 6763 } 6764 } 6765 } 6766 return status; 6767 } 6768 6769 boolean doRename(int status, final String pkgName, 6770 String oldCodePath) { 6771 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 6772 String newCachePath = null; 6773 if (PackageHelper.isContainerMounted(cid)) { 6774 // Unmount the container 6775 if (!PackageHelper.unMountSdDir(cid)) { 6776 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 6777 return false; 6778 } 6779 } 6780 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 6781 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 6782 " which might be stale. Will try to clean up."); 6783 // Clean up the stale container and proceed to recreate. 6784 if (!PackageHelper.destroySdDir(newCacheId)) { 6785 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 6786 return false; 6787 } 6788 // Successfully cleaned up stale container. Try to rename again. 6789 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 6790 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 6791 + " inspite of cleaning it up."); 6792 return false; 6793 } 6794 } 6795 if (!PackageHelper.isContainerMounted(newCacheId)) { 6796 Slog.w(TAG, "Mounting container " + newCacheId); 6797 newCachePath = PackageHelper.mountSdDir(newCacheId, 6798 getEncryptKey(), Process.SYSTEM_UID); 6799 } else { 6800 newCachePath = PackageHelper.getSdDir(newCacheId); 6801 } 6802 if (newCachePath == null) { 6803 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 6804 return false; 6805 } 6806 Log.i(TAG, "Succesfully renamed " + cid + 6807 " to " + newCacheId + 6808 " at new path: " + newCachePath); 6809 cid = newCacheId; 6810 setCachePath(newCachePath); 6811 return true; 6812 } 6813 6814 private void setCachePath(String newCachePath) { 6815 File cachePath = new File(newCachePath); 6816 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 6817 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 6818 6819 if (isFwdLocked()) { 6820 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 6821 } else { 6822 resourcePath = packagePath; 6823 } 6824 } 6825 6826 int doPostInstall(int status, int uid) { 6827 if (status != PackageManager.INSTALL_SUCCEEDED) { 6828 cleanUp(); 6829 } else { 6830 final int groupOwner; 6831 final String protectedFile; 6832 if (isFwdLocked()) { 6833 groupOwner = uid; 6834 protectedFile = RES_FILE_NAME; 6835 } else { 6836 groupOwner = -1; 6837 protectedFile = null; 6838 } 6839 6840 if (uid < Process.FIRST_APPLICATION_UID 6841 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 6842 Slog.e(TAG, "Failed to finalize " + cid); 6843 PackageHelper.destroySdDir(cid); 6844 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 6845 } 6846 6847 boolean mounted = PackageHelper.isContainerMounted(cid); 6848 if (!mounted) { 6849 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 6850 } 6851 } 6852 return status; 6853 } 6854 6855 private void cleanUp() { 6856 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 6857 6858 // Destroy secure container 6859 PackageHelper.destroySdDir(cid); 6860 } 6861 6862 void cleanUpResourcesLI() { 6863 String sourceFile = getCodePath(); 6864 // Remove dex file 6865 int retCode = mInstaller.rmdex(sourceFile); 6866 if (retCode < 0) { 6867 Slog.w(TAG, "Couldn't remove dex file for package: " 6868 + " at location " 6869 + sourceFile.toString() + ", retcode=" + retCode); 6870 // we don't consider this to be a failure of the core package deletion 6871 } 6872 cleanUp(); 6873 } 6874 6875 boolean matchContainer(String app) { 6876 if (cid.startsWith(app)) { 6877 return true; 6878 } 6879 return false; 6880 } 6881 6882 String getPackageName() { 6883 return getAsecPackageName(cid); 6884 } 6885 6886 boolean doPostDeleteLI(boolean delete) { 6887 boolean ret = false; 6888 boolean mounted = PackageHelper.isContainerMounted(cid); 6889 if (mounted) { 6890 // Unmount first 6891 ret = PackageHelper.unMountSdDir(cid); 6892 } 6893 if (ret && delete) { 6894 cleanUpResourcesLI(); 6895 } 6896 return ret; 6897 } 6898 6899 @Override 6900 int doPreCopy() { 6901 if (isFwdLocked()) { 6902 if (!PackageHelper.fixSdPermissions(cid, 6903 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 6904 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 6905 } 6906 } 6907 6908 return PackageManager.INSTALL_SUCCEEDED; 6909 } 6910 6911 @Override 6912 int doPostCopy(int uid) { 6913 if (isFwdLocked()) { 6914 if (uid < Process.FIRST_APPLICATION_UID 6915 || !PackageHelper.fixSdPermissions(cid, uid, RES_FILE_NAME)) { 6916 Slog.e(TAG, "Failed to finalize " + cid); 6917 PackageHelper.destroySdDir(cid); 6918 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 6919 } 6920 } 6921 6922 return PackageManager.INSTALL_SUCCEEDED; 6923 } 6924 }; 6925 6926 static String getAsecPackageName(String packageCid) { 6927 int idx = packageCid.lastIndexOf("-"); 6928 if (idx == -1) { 6929 return packageCid; 6930 } 6931 return packageCid.substring(0, idx); 6932 } 6933 6934 // Utility method used to create code paths based on package name and available index. 6935 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 6936 String idxStr = ""; 6937 int idx = 1; 6938 // Fall back to default value of idx=1 if prefix is not 6939 // part of oldCodePath 6940 if (oldCodePath != null) { 6941 String subStr = oldCodePath; 6942 // Drop the suffix right away 6943 if (subStr.endsWith(suffix)) { 6944 subStr = subStr.substring(0, subStr.length() - suffix.length()); 6945 } 6946 // If oldCodePath already contains prefix find out the 6947 // ending index to either increment or decrement. 6948 int sidx = subStr.lastIndexOf(prefix); 6949 if (sidx != -1) { 6950 subStr = subStr.substring(sidx + prefix.length()); 6951 if (subStr != null) { 6952 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 6953 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 6954 } 6955 try { 6956 idx = Integer.parseInt(subStr); 6957 if (idx <= 1) { 6958 idx++; 6959 } else { 6960 idx--; 6961 } 6962 } catch(NumberFormatException e) { 6963 } 6964 } 6965 } 6966 } 6967 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 6968 return prefix + idxStr; 6969 } 6970 6971 // Utility method used to ignore ADD/REMOVE events 6972 // by directory observer. 6973 private static boolean ignoreCodePath(String fullPathStr) { 6974 String apkName = getApkName(fullPathStr); 6975 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 6976 if (idx != -1 && ((idx+1) < apkName.length())) { 6977 // Make sure the package ends with a numeral 6978 String version = apkName.substring(idx+1); 6979 try { 6980 Integer.parseInt(version); 6981 return true; 6982 } catch (NumberFormatException e) {} 6983 } 6984 return false; 6985 } 6986 6987 // Utility method that returns the relative package path with respect 6988 // to the installation directory. Like say for /data/data/com.test-1.apk 6989 // string com.test-1 is returned. 6990 static String getApkName(String codePath) { 6991 if (codePath == null) { 6992 return null; 6993 } 6994 int sidx = codePath.lastIndexOf("/"); 6995 int eidx = codePath.lastIndexOf("."); 6996 if (eidx == -1) { 6997 eidx = codePath.length(); 6998 } else if (eidx == 0) { 6999 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 7000 return null; 7001 } 7002 return codePath.substring(sidx+1, eidx); 7003 } 7004 7005 class PackageInstalledInfo { 7006 String name; 7007 int uid; 7008 PackageParser.Package pkg; 7009 int returnCode; 7010 PackageRemovedInfo removedInfo; 7011 } 7012 7013 /* 7014 * Install a non-existing package. 7015 */ 7016 private void installNewPackageLI(PackageParser.Package pkg, 7017 int parseFlags, 7018 int scanMode, 7019 String installerPackageName, PackageInstalledInfo res) { 7020 // Remember this for later, in case we need to rollback this install 7021 String pkgName = pkg.packageName; 7022 7023 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 7024 res.name = pkgName; 7025 synchronized(mPackages) { 7026 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 7027 // A package with the same name is already installed, though 7028 // it has been renamed to an older name. The package we 7029 // are trying to install should be installed as an update to 7030 // the existing one, but that has not been requested, so bail. 7031 Slog.w(TAG, "Attempt to re-install " + pkgName 7032 + " without first uninstalling package running as " 7033 + mSettings.mRenamedPackages.get(pkgName)); 7034 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 7035 return; 7036 } 7037 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 7038 // Don't allow installation over an existing package with the same name. 7039 Slog.w(TAG, "Attempt to re-install " + pkgName 7040 + " without first uninstalling."); 7041 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 7042 return; 7043 } 7044 } 7045 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7046 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 7047 System.currentTimeMillis()); 7048 if (newPackage == null) { 7049 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7050 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7051 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7052 } 7053 } else { 7054 updateSettingsLI(newPackage, 7055 installerPackageName, 7056 res); 7057 // delete the partially installed application. the data directory will have to be 7058 // restored if it was already existing 7059 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7060 // remove package from internal structures. Note that we want deletePackageX to 7061 // delete the package data and cache directories that it created in 7062 // scanPackageLocked, unless those directories existed before we even tried to 7063 // install. 7064 deletePackageLI( 7065 pkgName, false, 7066 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0, 7067 res.removedInfo, true); 7068 } 7069 } 7070 } 7071 7072 private void replacePackageLI(PackageParser.Package pkg, 7073 int parseFlags, 7074 int scanMode, 7075 String installerPackageName, PackageInstalledInfo res) { 7076 7077 PackageParser.Package oldPackage; 7078 String pkgName = pkg.packageName; 7079 // First find the old package info and check signatures 7080 synchronized(mPackages) { 7081 oldPackage = mPackages.get(pkgName); 7082 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 7083 != PackageManager.SIGNATURE_MATCH) { 7084 Slog.w(TAG, "New package has a different signature: " + pkgName); 7085 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 7086 return; 7087 } 7088 } 7089 boolean sysPkg = (isSystemApp(oldPackage)); 7090 if (sysPkg) { 7091 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res); 7092 } else { 7093 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res); 7094 } 7095 } 7096 7097 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 7098 PackageParser.Package pkg, 7099 int parseFlags, int scanMode, 7100 String installerPackageName, PackageInstalledInfo res) { 7101 PackageParser.Package newPackage = null; 7102 String pkgName = deletedPackage.packageName; 7103 boolean deletedPkg = true; 7104 boolean updatedSettings = false; 7105 7106 long origUpdateTime; 7107 if (pkg.mExtras != null) { 7108 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 7109 } else { 7110 origUpdateTime = 0; 7111 } 7112 7113 // First delete the existing package while retaining the data directory 7114 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA, 7115 res.removedInfo, true)) { 7116 // If the existing package wasn't successfully deleted 7117 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 7118 deletedPkg = false; 7119 } else { 7120 // Successfully deleted the old package. Now proceed with re-installation 7121 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7122 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 7123 System.currentTimeMillis()); 7124 if (newPackage == null) { 7125 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7126 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7127 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7128 } 7129 } else { 7130 updateSettingsLI(newPackage, 7131 installerPackageName, 7132 res); 7133 updatedSettings = true; 7134 } 7135 } 7136 7137 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7138 // remove package from internal structures. Note that we want deletePackageX to 7139 // delete the package data and cache directories that it created in 7140 // scanPackageLocked, unless those directories existed before we even tried to 7141 // install. 7142 if(updatedSettings) { 7143 deletePackageLI( 7144 pkgName, true, 7145 PackageManager.DONT_DELETE_DATA, 7146 res.removedInfo, true); 7147 } 7148 // Since we failed to install the new package we need to restore the old 7149 // package that we deleted. 7150 if(deletedPkg) { 7151 File restoreFile = new File(deletedPackage.mPath); 7152 // Parse old package 7153 boolean oldOnSd = isExternal(deletedPackage); 7154 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 7155 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 7156 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 7157 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 7158 | SCAN_UPDATE_TIME; 7159 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 7160 origUpdateTime) == null) { 7161 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 7162 return; 7163 } 7164 // Restore of old package succeeded. Update permissions. 7165 // writer 7166 synchronized (mPackages) { 7167 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 7168 UPDATE_PERMISSIONS_ALL); 7169 // can downgrade to reader 7170 mSettings.writeLPr(); 7171 } 7172 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 7173 } 7174 } 7175 } 7176 7177 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 7178 PackageParser.Package pkg, 7179 int parseFlags, int scanMode, 7180 String installerPackageName, PackageInstalledInfo res) { 7181 PackageParser.Package newPackage = null; 7182 boolean updatedSettings = false; 7183 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 7184 PackageParser.PARSE_IS_SYSTEM; 7185 String packageName = deletedPackage.packageName; 7186 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 7187 if (packageName == null) { 7188 Slog.w(TAG, "Attempt to delete null packageName."); 7189 return; 7190 } 7191 PackageParser.Package oldPkg; 7192 PackageSetting oldPkgSetting; 7193 // reader 7194 synchronized (mPackages) { 7195 oldPkg = mPackages.get(packageName); 7196 oldPkgSetting = mSettings.mPackages.get(packageName); 7197 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 7198 (oldPkgSetting == null)) { 7199 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 7200 return; 7201 } 7202 } 7203 7204 killApplication(packageName, oldPkg.applicationInfo.uid); 7205 7206 res.removedInfo.uid = oldPkg.applicationInfo.uid; 7207 res.removedInfo.removedPackage = packageName; 7208 // Remove existing system package 7209 removePackageLI(oldPkg, true); 7210 // writer 7211 synchronized (mPackages) { 7212 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 7213 // We didn't need to disable the .apk as a current system package, 7214 // which means we are replacing another update that is already 7215 // installed. We need to make sure to delete the older one's .apk. 7216 res.removedInfo.args = createInstallArgs(0, 7217 deletedPackage.applicationInfo.sourceDir, 7218 deletedPackage.applicationInfo.publicSourceDir, 7219 deletedPackage.applicationInfo.nativeLibraryDir); 7220 } else { 7221 res.removedInfo.args = null; 7222 } 7223 } 7224 7225 // Successfully disabled the old package. Now proceed with re-installation 7226 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7227 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7228 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0); 7229 if (newPackage == null) { 7230 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7231 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7232 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7233 } 7234 } else { 7235 if (newPackage.mExtras != null) { 7236 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 7237 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 7238 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 7239 } 7240 updateSettingsLI(newPackage, installerPackageName, res); 7241 updatedSettings = true; 7242 } 7243 7244 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7245 // Re installation failed. Restore old information 7246 // Remove new pkg information 7247 if (newPackage != null) { 7248 removePackageLI(newPackage, true); 7249 } 7250 // Add back the old system package 7251 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0); 7252 // Restore the old system information in Settings 7253 synchronized(mPackages) { 7254 if (updatedSettings) { 7255 mSettings.enableSystemPackageLPw(packageName); 7256 mSettings.setInstallerPackageName(packageName, 7257 oldPkgSetting.installerPackageName); 7258 } 7259 mSettings.writeLPr(); 7260 } 7261 } 7262 } 7263 7264 // Utility method used to move dex files during install. 7265 private int moveDexFilesLI(PackageParser.Package newPackage) { 7266 int retCode; 7267 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 7268 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath); 7269 if (retCode != 0) { 7270 if (mNoDexOpt) { 7271 /* 7272 * If we're in an engineering build, programs are lazily run 7273 * through dexopt. If the .dex file doesn't exist yet, it 7274 * will be created when the program is run next. 7275 */ 7276 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath); 7277 } else { 7278 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath); 7279 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 7280 } 7281 } 7282 } 7283 return PackageManager.INSTALL_SUCCEEDED; 7284 } 7285 7286 private void updateSettingsLI(PackageParser.Package newPackage, 7287 String installerPackageName, PackageInstalledInfo res) { 7288 String pkgName = newPackage.packageName; 7289 synchronized (mPackages) { 7290 //write settings. the installStatus will be incomplete at this stage. 7291 //note that the new package setting would have already been 7292 //added to mPackages. It hasn't been persisted yet. 7293 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 7294 mSettings.writeLPr(); 7295 } 7296 7297 if ((res.returnCode = moveDexFilesLI(newPackage)) 7298 != PackageManager.INSTALL_SUCCEEDED) { 7299 // Discontinue if moving dex files failed. 7300 return; 7301 } 7302 7303 Log.d(TAG, "New package installed in " + newPackage.mPath); 7304 7305 synchronized (mPackages) { 7306 updatePermissionsLPw(newPackage.packageName, newPackage, 7307 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 7308 ? UPDATE_PERMISSIONS_ALL : 0)); 7309 res.name = pkgName; 7310 res.uid = newPackage.applicationInfo.uid; 7311 res.pkg = newPackage; 7312 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 7313 mSettings.setInstallerPackageName(pkgName, installerPackageName); 7314 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 7315 //to update install status 7316 mSettings.writeLPr(); 7317 } 7318 } 7319 7320 private void installPackageLI(InstallArgs args, 7321 boolean newInstall, PackageInstalledInfo res) { 7322 int pFlags = args.flags; 7323 String installerPackageName = args.installerPackageName; 7324 File tmpPackageFile = new File(args.getCodePath()); 7325 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 7326 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 7327 boolean replace = false; 7328 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 7329 | (newInstall ? SCAN_NEW_INSTALL : 0); 7330 // Result object to be returned 7331 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 7332 7333 // Retrieve PackageSettings and parse package 7334 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 7335 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 7336 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 7337 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 7338 pp.setSeparateProcesses(mSeparateProcesses); 7339 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 7340 null, mMetrics, parseFlags); 7341 if (pkg == null) { 7342 res.returnCode = pp.getParseError(); 7343 return; 7344 } 7345 String pkgName = res.name = pkg.packageName; 7346 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 7347 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 7348 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 7349 return; 7350 } 7351 } 7352 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) { 7353 res.returnCode = pp.getParseError(); 7354 return; 7355 } 7356 7357 /* If the installer passed in a manifest digest, compare it now. */ 7358 if (args.manifestDigest != null) { 7359 if (DEBUG_INSTALL) { 7360 final String parsedManifest = pkg.manifestDigest == null ? "null" 7361 : pkg.manifestDigest.toString(); 7362 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 7363 + parsedManifest); 7364 } 7365 7366 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 7367 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 7368 return; 7369 } 7370 } else if (DEBUG_INSTALL) { 7371 final String parsedManifest = pkg.manifestDigest == null 7372 ? "null" : pkg.manifestDigest.toString(); 7373 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 7374 } 7375 7376 // Get rid of all references to package scan path via parser. 7377 pp = null; 7378 String oldCodePath = null; 7379 boolean systemApp = false; 7380 synchronized (mPackages) { 7381 // Check if installing already existing package 7382 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 7383 String oldName = mSettings.mRenamedPackages.get(pkgName); 7384 if (pkg.mOriginalPackages != null 7385 && pkg.mOriginalPackages.contains(oldName) 7386 && mPackages.containsKey(oldName)) { 7387 // This package is derived from an original package, 7388 // and this device has been updating from that original 7389 // name. We must continue using the original name, so 7390 // rename the new package here. 7391 pkg.setPackageName(oldName); 7392 pkgName = pkg.packageName; 7393 replace = true; 7394 } else if (mPackages.containsKey(pkgName)) { 7395 // This package, under its official name, already exists 7396 // on the device; we should replace it. 7397 replace = true; 7398 } 7399 } 7400 PackageSetting ps = mSettings.mPackages.get(pkgName); 7401 if (ps != null) { 7402 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 7403 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7404 systemApp = (ps.pkg.applicationInfo.flags & 7405 ApplicationInfo.FLAG_SYSTEM) != 0; 7406 } 7407 } 7408 } 7409 7410 if (systemApp && onSd) { 7411 // Disable updates to system apps on sdcard 7412 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 7413 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 7414 return; 7415 } 7416 7417 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 7418 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 7419 return; 7420 } 7421 // Set application objects path explicitly after the rename 7422 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 7423 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 7424 if (replace) { 7425 replacePackageLI(pkg, parseFlags, scanMode, 7426 installerPackageName, res); 7427 } else { 7428 installNewPackageLI(pkg, parseFlags, scanMode, 7429 installerPackageName,res); 7430 } 7431 } 7432 7433 private static boolean isForwardLocked(PackageParser.Package pkg) { 7434 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 7435 } 7436 7437 7438 private boolean isForwardLocked(PackageSetting ps) { 7439 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 7440 } 7441 7442 private static boolean isExternal(PackageParser.Package pkg) { 7443 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 7444 } 7445 7446 private static boolean isExternal(PackageSetting ps) { 7447 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 7448 } 7449 7450 private static boolean isSystemApp(PackageParser.Package pkg) { 7451 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7452 } 7453 7454 private static boolean isSystemApp(ApplicationInfo info) { 7455 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7456 } 7457 7458 private static boolean isSystemApp(PackageSetting ps) { 7459 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 7460 } 7461 7462 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 7463 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 7464 } 7465 7466 private int packageFlagsToInstallFlags(PackageSetting ps) { 7467 int installFlags = 0; 7468 if (isExternal(ps)) { 7469 installFlags |= PackageManager.INSTALL_EXTERNAL; 7470 } 7471 if (isForwardLocked(ps)) { 7472 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 7473 } 7474 return installFlags; 7475 } 7476 7477 private void deleteTempPackageFiles() { 7478 FilenameFilter filter = new FilenameFilter() { 7479 public boolean accept(File dir, String name) { 7480 return name.startsWith("vmdl") && name.endsWith(".tmp"); 7481 } 7482 }; 7483 String tmpFilesList[] = mAppInstallDir.list(filter); 7484 if(tmpFilesList == null) { 7485 return; 7486 } 7487 for(int i = 0; i < tmpFilesList.length; i++) { 7488 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]); 7489 tmpFile.delete(); 7490 } 7491 } 7492 7493 private File createTempPackageFile(File installDir) { 7494 File tmpPackageFile; 7495 try { 7496 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 7497 } catch (IOException e) { 7498 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 7499 return null; 7500 } 7501 try { 7502 FileUtils.setPermissions( 7503 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 7504 -1, -1); 7505 if (!SELinux.restorecon(tmpPackageFile)) { 7506 return null; 7507 } 7508 } catch (IOException e) { 7509 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 7510 return null; 7511 } 7512 return tmpPackageFile; 7513 } 7514 7515 public void deletePackage(final String packageName, 7516 final IPackageDeleteObserver observer, 7517 final int flags) { 7518 mContext.enforceCallingOrSelfPermission( 7519 android.Manifest.permission.DELETE_PACKAGES, null); 7520 // Queue up an async operation since the package deletion may take a little while. 7521 mHandler.post(new Runnable() { 7522 public void run() { 7523 mHandler.removeCallbacks(this); 7524 final int returnCode = deletePackageX(packageName, true, true, flags); 7525 if (observer != null) { 7526 try { 7527 observer.packageDeleted(packageName, returnCode); 7528 } catch (RemoteException e) { 7529 Log.i(TAG, "Observer no longer exists."); 7530 } //end catch 7531 } //end if 7532 } //end run 7533 }); 7534 } 7535 7536 /** 7537 * This method is an internal method that could be get invoked either 7538 * to delete an installed package or to clean up a failed installation. 7539 * After deleting an installed package, a broadcast is sent to notify any 7540 * listeners that the package has been installed. For cleaning up a failed 7541 * installation, the broadcast is not necessary since the package's 7542 * installation wouldn't have sent the initial broadcast either 7543 * The key steps in deleting a package are 7544 * deleting the package information in internal structures like mPackages, 7545 * deleting the packages base directories through installd 7546 * updating mSettings to reflect current status 7547 * persisting settings for later use 7548 * sending a broadcast if necessary 7549 */ 7550 private int deletePackageX(String packageName, boolean sendBroadCast, 7551 boolean deleteCodeAndResources, int flags) { 7552 final PackageRemovedInfo info = new PackageRemovedInfo(); 7553 final boolean res; 7554 7555 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 7556 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 7557 try { 7558 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) { 7559 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 7560 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 7561 } 7562 } catch (RemoteException e) { 7563 } 7564 7565 synchronized (mInstallLock) { 7566 res = deletePackageLI(packageName, deleteCodeAndResources, 7567 flags | REMOVE_CHATTY, info, true); 7568 } 7569 7570 if (res && sendBroadCast) { 7571 boolean systemUpdate = info.isRemovedPackageSystemUpdate; 7572 info.sendBroadcast(deleteCodeAndResources, systemUpdate); 7573 7574 // If the removed package was a system update, the old system packaged 7575 // was re-enabled; we need to broadcast this information 7576 if (systemUpdate) { 7577 Bundle extras = new Bundle(1); 7578 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid); 7579 extras.putBoolean(Intent.EXTRA_REPLACING, true); 7580 7581 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 7582 extras, null, null, UserHandle.USER_ALL); 7583 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 7584 extras, null, null, UserHandle.USER_ALL); 7585 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 7586 null, packageName, null, UserHandle.USER_ALL); 7587 } 7588 } 7589 // Force a gc here. 7590 Runtime.getRuntime().gc(); 7591 // Delete the resources here after sending the broadcast to let 7592 // other processes clean up before deleting resources. 7593 if (info.args != null) { 7594 synchronized (mInstallLock) { 7595 info.args.doPostDeleteLI(deleteCodeAndResources); 7596 } 7597 } 7598 7599 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 7600 } 7601 7602 static class PackageRemovedInfo { 7603 String removedPackage; 7604 int uid = -1; 7605 int removedUid = -1; 7606 boolean isRemovedPackageSystemUpdate = false; 7607 // Clean up resources deleted packages. 7608 InstallArgs args = null; 7609 7610 void sendBroadcast(boolean fullRemove, boolean replacing) { 7611 Bundle extras = new Bundle(1); 7612 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid); 7613 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 7614 if (replacing) { 7615 extras.putBoolean(Intent.EXTRA_REPLACING, true); 7616 } 7617 if (removedPackage != null) { 7618 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7619 extras, null, null, UserHandle.USER_ALL); 7620 if (fullRemove && !replacing) { 7621 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 7622 extras, null, null, UserHandle.USER_ALL); 7623 } 7624 } 7625 if (removedUid >= 0) { 7626 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 7627 UserHandle.getUserId(removedUid)); 7628 } 7629 } 7630 } 7631 7632 /* 7633 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 7634 * flag is not set, the data directory is removed as well. 7635 * make sure this flag is set for partially installed apps. If not its meaningless to 7636 * delete a partially installed application. 7637 */ 7638 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo, 7639 int flags, boolean writeSettings) { 7640 String packageName = p.packageName; 7641 if (outInfo != null) { 7642 outInfo.removedPackage = packageName; 7643 } 7644 removePackageLI(p, (flags&REMOVE_CHATTY) != 0); 7645 // Retrieve object to delete permissions for shared user later on 7646 final PackageSetting deletedPs; 7647 // reader 7648 synchronized (mPackages) { 7649 deletedPs = mSettings.mPackages.get(packageName); 7650 } 7651 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) { 7652 int retCode = mInstaller.remove(packageName, 0); 7653 if (retCode < 0) { 7654 Slog.w(TAG, "Couldn't remove app data or cache directory for package: " 7655 + packageName + ", retcode=" + retCode); 7656 // we don't consider this to be a failure of the core package deletion 7657 } else { 7658 // TODO: Kill the processes first 7659 sUserManager.removePackageForAllUsers(packageName); 7660 } 7661 schedulePackageCleaning(packageName); 7662 } 7663 // writer 7664 synchronized (mPackages) { 7665 if (deletedPs != null) { 7666 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) { 7667 if (outInfo != null) { 7668 outInfo.removedUid = mSettings.removePackageLPw(packageName); 7669 } 7670 if (deletedPs != null) { 7671 updatePermissionsLPw(deletedPs.name, null, 0); 7672 if (deletedPs.sharedUser != null) { 7673 // remove permissions associated with package 7674 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 7675 } 7676 } 7677 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 7678 } 7679 } 7680 // can downgrade to reader 7681 if (writeSettings) { 7682 // Save settings now 7683 mSettings.writeLPr(); 7684 } 7685 } 7686 } 7687 7688 /* 7689 * Tries to delete system package. 7690 */ 7691 private boolean deleteSystemPackageLI(PackageParser.Package p, 7692 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 7693 ApplicationInfo applicationInfo = p.applicationInfo; 7694 //applicable for non-partially installed applications only 7695 if (applicationInfo == null) { 7696 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo."); 7697 return false; 7698 } 7699 PackageSetting ps = null; 7700 // Confirm if the system package has been updated 7701 // An updated system app can be deleted. This will also have to restore 7702 // the system pkg from system partition 7703 // reader 7704 synchronized (mPackages) { 7705 ps = mSettings.getDisabledSystemPkgLPr(p.packageName); 7706 } 7707 if (ps == null) { 7708 Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName); 7709 return false; 7710 } else { 7711 Log.i(TAG, "Deleting system pkg from data partition"); 7712 } 7713 // Delete the updated package 7714 outInfo.isRemovedPackageSystemUpdate = true; 7715 if (ps.versionCode < p.mVersionCode) { 7716 // Delete data for downgrades 7717 flags &= ~PackageManager.DONT_DELETE_DATA; 7718 } else { 7719 // Preserve data by setting flag 7720 flags |= PackageManager.DONT_DELETE_DATA; 7721 } 7722 boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo, 7723 writeSettings); 7724 if (!ret) { 7725 return false; 7726 } 7727 // writer 7728 synchronized (mPackages) { 7729 // Reinstate the old system package 7730 mSettings.enableSystemPackageLPw(p.packageName); 7731 // Remove any native libraries from the upgraded package. 7732 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir); 7733 } 7734 // Install the system package 7735 PackageParser.Package newPkg = scanPackageLI(ps.codePath, 7736 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM, 7737 SCAN_MONITOR | SCAN_NO_PATHS, 0); 7738 7739 if (newPkg == null) { 7740 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError); 7741 return false; 7742 } 7743 // writer 7744 synchronized (mPackages) { 7745 updatePermissionsLPw(newPkg.packageName, newPkg, 7746 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 7747 // can downgrade to reader here 7748 if (writeSettings) { 7749 mSettings.writeLPr(); 7750 } 7751 } 7752 return true; 7753 } 7754 7755 private boolean deleteInstalledPackageLI(PackageParser.Package p, 7756 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo, 7757 boolean writeSettings) { 7758 ApplicationInfo applicationInfo = p.applicationInfo; 7759 if (applicationInfo == null) { 7760 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo."); 7761 return false; 7762 } 7763 if (outInfo != null) { 7764 outInfo.uid = applicationInfo.uid; 7765 } 7766 7767 // Delete package data from internal structures and also remove data if flag is set 7768 removePackageDataLI(p, outInfo, flags, writeSettings); 7769 7770 // Delete application code and resources 7771 if (deleteCodeAndResources) { 7772 // TODO can pick up from PackageSettings as well 7773 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0; 7774 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0; 7775 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir, 7776 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir); 7777 } 7778 return true; 7779 } 7780 7781 /* 7782 * This method handles package deletion in general 7783 */ 7784 private boolean deletePackageLI(String packageName, 7785 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo, 7786 boolean writeSettings) { 7787 if (packageName == null) { 7788 Slog.w(TAG, "Attempt to delete null packageName."); 7789 return false; 7790 } 7791 PackageParser.Package p; 7792 boolean dataOnly = false; 7793 synchronized (mPackages) { 7794 p = mPackages.get(packageName); 7795 if (p == null) { 7796 //this retrieves partially installed apps 7797 dataOnly = true; 7798 PackageSetting ps = mSettings.mPackages.get(packageName); 7799 if (ps == null) { 7800 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 7801 return false; 7802 } 7803 p = ps.pkg; 7804 } 7805 } 7806 if (p == null) { 7807 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 7808 return false; 7809 } 7810 7811 if (dataOnly) { 7812 // Delete application data first 7813 removePackageDataLI(p, outInfo, flags, writeSettings); 7814 return true; 7815 } 7816 // At this point the package should have ApplicationInfo associated with it 7817 if (p.applicationInfo == null) { 7818 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo."); 7819 return false; 7820 } 7821 boolean ret = false; 7822 if (isSystemApp(p)) { 7823 Log.i(TAG, "Removing system package:"+p.packageName); 7824 // When an updated system application is deleted we delete the existing resources as well and 7825 // fall back to existing code in system partition 7826 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings); 7827 } else { 7828 Log.i(TAG, "Removing non-system package:"+p.packageName); 7829 // Kill application pre-emptively especially for apps on sd. 7830 killApplication(packageName, p.applicationInfo.uid); 7831 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo, 7832 writeSettings); 7833 } 7834 return ret; 7835 } 7836 7837 private final class ClearStorageConnection implements ServiceConnection { 7838 IMediaContainerService mContainerService; 7839 7840 @Override 7841 public void onServiceConnected(ComponentName name, IBinder service) { 7842 synchronized (this) { 7843 mContainerService = IMediaContainerService.Stub.asInterface(service); 7844 notifyAll(); 7845 } 7846 } 7847 7848 @Override 7849 public void onServiceDisconnected(ComponentName name) { 7850 } 7851 } 7852 7853 private void clearExternalStorageDataSync(String packageName, boolean allData) { 7854 final boolean mounted; 7855 if (Environment.isExternalStorageEmulated()) { 7856 mounted = true; 7857 } else { 7858 final String status = Environment.getExternalStorageState(); 7859 7860 mounted = status.equals(Environment.MEDIA_MOUNTED) 7861 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 7862 } 7863 7864 if (!mounted) { 7865 return; 7866 } 7867 7868 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 7869 ClearStorageConnection conn = new ClearStorageConnection(); 7870 if (mContext.bindService(containerIntent, conn, Context.BIND_AUTO_CREATE)) { 7871 try { 7872 long timeout = SystemClock.uptimeMillis() + 5000; 7873 synchronized (conn) { 7874 long now = SystemClock.uptimeMillis(); 7875 while (conn.mContainerService == null && now < timeout) { 7876 try { 7877 conn.wait(timeout - now); 7878 } catch (InterruptedException e) { 7879 } 7880 } 7881 } 7882 if (conn.mContainerService == null) { 7883 return; 7884 } 7885 final File externalCacheDir = Environment 7886 .getExternalStorageAppCacheDirectory(packageName); 7887 try { 7888 conn.mContainerService.clearDirectory(externalCacheDir.toString()); 7889 } catch (RemoteException e) { 7890 } 7891 if (allData) { 7892 final File externalDataDir = Environment 7893 .getExternalStorageAppDataDirectory(packageName); 7894 try { 7895 conn.mContainerService.clearDirectory(externalDataDir.toString()); 7896 } catch (RemoteException e) { 7897 } 7898 final File externalMediaDir = Environment 7899 .getExternalStorageAppMediaDirectory(packageName); 7900 try { 7901 conn.mContainerService.clearDirectory(externalMediaDir.toString()); 7902 } catch (RemoteException e) { 7903 } 7904 } 7905 } finally { 7906 mContext.unbindService(conn); 7907 } 7908 } 7909 } 7910 7911 @Override 7912 public void clearApplicationUserData(final String packageName, 7913 final IPackageDataObserver observer, final int userId) { 7914 mContext.enforceCallingOrSelfPermission( 7915 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 7916 checkValidCaller(Binder.getCallingUid(), userId); 7917 // Queue up an async operation since the package deletion may take a little while. 7918 mHandler.post(new Runnable() { 7919 public void run() { 7920 mHandler.removeCallbacks(this); 7921 final boolean succeeded; 7922 synchronized (mInstallLock) { 7923 succeeded = clearApplicationUserDataLI(packageName, userId); 7924 } 7925 clearExternalStorageDataSync(packageName, true); 7926 if (succeeded) { 7927 // invoke DeviceStorageMonitor's update method to clear any notifications 7928 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) 7929 ServiceManager.getService(DeviceStorageMonitorService.SERVICE); 7930 if (dsm != null) { 7931 dsm.updateMemory(); 7932 } 7933 } 7934 if(observer != null) { 7935 try { 7936 observer.onRemoveCompleted(packageName, succeeded); 7937 } catch (RemoteException e) { 7938 Log.i(TAG, "Observer no longer exists."); 7939 } 7940 } //end if observer 7941 } //end run 7942 }); 7943 } 7944 7945 private boolean clearApplicationUserDataLI(String packageName, int userId) { 7946 if (packageName == null) { 7947 Slog.w(TAG, "Attempt to delete null packageName."); 7948 return false; 7949 } 7950 PackageParser.Package p; 7951 boolean dataOnly = false; 7952 synchronized (mPackages) { 7953 p = mPackages.get(packageName); 7954 if(p == null) { 7955 dataOnly = true; 7956 PackageSetting ps = mSettings.mPackages.get(packageName); 7957 if((ps == null) || (ps.pkg == null)) { 7958 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 7959 return false; 7960 } 7961 p = ps.pkg; 7962 } 7963 } 7964 7965 if (!dataOnly) { 7966 //need to check this only for fully installed applications 7967 if (p == null) { 7968 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 7969 return false; 7970 } 7971 final ApplicationInfo applicationInfo = p.applicationInfo; 7972 if (applicationInfo == null) { 7973 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 7974 return false; 7975 } 7976 } 7977 int retCode = mInstaller.clearUserData(packageName, userId); 7978 if (retCode < 0) { 7979 Slog.w(TAG, "Couldn't remove cache files for package: " 7980 + packageName); 7981 return false; 7982 } 7983 return true; 7984 } 7985 7986 public void deleteApplicationCacheFiles(final String packageName, 7987 final IPackageDataObserver observer) { 7988 mContext.enforceCallingOrSelfPermission( 7989 android.Manifest.permission.DELETE_CACHE_FILES, null); 7990 // Queue up an async operation since the package deletion may take a little while. 7991 final int userId = UserHandle.getCallingUserId(); 7992 mHandler.post(new Runnable() { 7993 public void run() { 7994 mHandler.removeCallbacks(this); 7995 final boolean succeded; 7996 synchronized (mInstallLock) { 7997 succeded = deleteApplicationCacheFilesLI(packageName, userId); 7998 } 7999 clearExternalStorageDataSync(packageName, false); 8000 if(observer != null) { 8001 try { 8002 observer.onRemoveCompleted(packageName, succeded); 8003 } catch (RemoteException e) { 8004 Log.i(TAG, "Observer no longer exists."); 8005 } 8006 } //end if observer 8007 } //end run 8008 }); 8009 } 8010 8011 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 8012 if (packageName == null) { 8013 Slog.w(TAG, "Attempt to delete null packageName."); 8014 return false; 8015 } 8016 PackageParser.Package p; 8017 synchronized (mPackages) { 8018 p = mPackages.get(packageName); 8019 } 8020 if (p == null) { 8021 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8022 return false; 8023 } 8024 final ApplicationInfo applicationInfo = p.applicationInfo; 8025 if (applicationInfo == null) { 8026 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 8027 return false; 8028 } 8029 // TODO: Pass userId to deleteCacheFiles 8030 int retCode = mInstaller.deleteCacheFiles(packageName); 8031 if (retCode < 0) { 8032 Slog.w(TAG, "Couldn't remove cache files for package: " 8033 + packageName); 8034 return false; 8035 } 8036 return true; 8037 } 8038 8039 public void getPackageSizeInfo(final String packageName, 8040 final IPackageStatsObserver observer) { 8041 mContext.enforceCallingOrSelfPermission( 8042 android.Manifest.permission.GET_PACKAGE_SIZE, null); 8043 8044 PackageStats stats = new PackageStats(packageName); 8045 8046 /* 8047 * Queue up an async operation since the package measurement may take a 8048 * little while. 8049 */ 8050 Message msg = mHandler.obtainMessage(INIT_COPY); 8051 msg.obj = new MeasureParams(stats, observer); 8052 mHandler.sendMessage(msg); 8053 } 8054 8055 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) { 8056 if (packageName == null) { 8057 Slog.w(TAG, "Attempt to get size of null packageName."); 8058 return false; 8059 } 8060 PackageParser.Package p; 8061 boolean dataOnly = false; 8062 String asecPath = null; 8063 synchronized (mPackages) { 8064 p = mPackages.get(packageName); 8065 if(p == null) { 8066 dataOnly = true; 8067 PackageSetting ps = mSettings.mPackages.get(packageName); 8068 if((ps == null) || (ps.pkg == null)) { 8069 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8070 return false; 8071 } 8072 p = ps.pkg; 8073 } 8074 if (p != null && (isExternal(p) || isForwardLocked(p))) { 8075 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 8076 if (secureContainerId != null) { 8077 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 8078 } 8079 } 8080 } 8081 String publicSrcDir = null; 8082 if(!dataOnly) { 8083 final ApplicationInfo applicationInfo = p.applicationInfo; 8084 if (applicationInfo == null) { 8085 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 8086 return false; 8087 } 8088 if (isForwardLocked(p)) { 8089 publicSrcDir = applicationInfo.publicSourceDir; 8090 } 8091 } 8092 int res = mInstaller.getSizeInfo(packageName, p.mPath, publicSrcDir, 8093 asecPath, pStats); 8094 if (res < 0) { 8095 return false; 8096 } 8097 8098 // Fix-up for forward-locked applications in ASEC containers. 8099 if (!isExternal(p)) { 8100 pStats.codeSize += pStats.externalCodeSize; 8101 pStats.externalCodeSize = 0L; 8102 } 8103 8104 return true; 8105 } 8106 8107 8108 public void addPackageToPreferred(String packageName) { 8109 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 8110 } 8111 8112 public void removePackageFromPreferred(String packageName) { 8113 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 8114 } 8115 8116 public List<PackageInfo> getPreferredPackages(int flags) { 8117 return new ArrayList<PackageInfo>(); 8118 } 8119 8120 private int getUidTargetSdkVersionLockedLPr(int uid) { 8121 Object obj = mSettings.getUserIdLPr(uid); 8122 if (obj instanceof SharedUserSetting) { 8123 final SharedUserSetting sus = (SharedUserSetting) obj; 8124 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 8125 final Iterator<PackageSetting> it = sus.packages.iterator(); 8126 while (it.hasNext()) { 8127 final PackageSetting ps = it.next(); 8128 if (ps.pkg != null) { 8129 int v = ps.pkg.applicationInfo.targetSdkVersion; 8130 if (v < vers) vers = v; 8131 } 8132 } 8133 return vers; 8134 } else if (obj instanceof PackageSetting) { 8135 final PackageSetting ps = (PackageSetting) obj; 8136 if (ps.pkg != null) { 8137 return ps.pkg.applicationInfo.targetSdkVersion; 8138 } 8139 } 8140 return Build.VERSION_CODES.CUR_DEVELOPMENT; 8141 } 8142 8143 public void addPreferredActivity(IntentFilter filter, int match, 8144 ComponentName[] set, ComponentName activity, int userId) { 8145 // writer 8146 int callingUid = Binder.getCallingUid(); 8147 checkValidCaller(callingUid, userId); 8148 synchronized (mPackages) { 8149 if (mContext.checkCallingOrSelfPermission( 8150 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8151 != PackageManager.PERMISSION_GRANTED) { 8152 if (getUidTargetSdkVersionLockedLPr(callingUid) 8153 < Build.VERSION_CODES.FROYO) { 8154 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 8155 + callingUid); 8156 return; 8157 } 8158 mContext.enforceCallingOrSelfPermission( 8159 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8160 } 8161 8162 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 8163 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 8164 mSettings.mPreferredActivities.addFilter( 8165 new PreferredActivity(filter, match, set, activity, userId)); 8166 scheduleWriteSettingsLocked(); 8167 } 8168 } 8169 8170 public void replacePreferredActivity(IntentFilter filter, int match, 8171 ComponentName[] set, ComponentName activity) { 8172 if (filter.countActions() != 1) { 8173 throw new IllegalArgumentException( 8174 "replacePreferredActivity expects filter to have only 1 action."); 8175 } 8176 if (filter.countCategories() != 1) { 8177 throw new IllegalArgumentException( 8178 "replacePreferredActivity expects filter to have only 1 category."); 8179 } 8180 if (filter.countDataAuthorities() != 0 8181 || filter.countDataPaths() != 0 8182 || filter.countDataSchemes() != 0 8183 || filter.countDataTypes() != 0) { 8184 throw new IllegalArgumentException( 8185 "replacePreferredActivity expects filter to have no data authorities, " + 8186 "paths, schemes or types."); 8187 } 8188 synchronized (mPackages) { 8189 if (mContext.checkCallingOrSelfPermission( 8190 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8191 != PackageManager.PERMISSION_GRANTED) { 8192 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 8193 < Build.VERSION_CODES.FROYO) { 8194 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 8195 + Binder.getCallingUid()); 8196 return; 8197 } 8198 mContext.enforceCallingOrSelfPermission( 8199 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8200 } 8201 8202 final int callingUserId = UserHandle.getCallingUserId(); 8203 ArrayList<PreferredActivity> removed = null; 8204 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator(); 8205 String action = filter.getAction(0); 8206 String category = filter.getCategory(0); 8207 while (it.hasNext()) { 8208 PreferredActivity pa = it.next(); 8209 if (pa.mUserId != callingUserId) continue; 8210 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) { 8211 if (removed == null) { 8212 removed = new ArrayList<PreferredActivity>(); 8213 } 8214 removed.add(pa); 8215 Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":"); 8216 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 8217 } 8218 } 8219 if (removed != null) { 8220 for (int i=0; i<removed.size(); i++) { 8221 PreferredActivity pa = removed.get(i); 8222 mSettings.mPreferredActivities.removeFilter(pa); 8223 } 8224 } 8225 addPreferredActivity(filter, match, set, activity, callingUserId); 8226 } 8227 } 8228 8229 public void clearPackagePreferredActivities(String packageName) { 8230 final int uid = Binder.getCallingUid(); 8231 // writer 8232 synchronized (mPackages) { 8233 PackageParser.Package pkg = mPackages.get(packageName); 8234 if (pkg == null || pkg.applicationInfo.uid != uid) { 8235 if (mContext.checkCallingOrSelfPermission( 8236 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8237 != PackageManager.PERMISSION_GRANTED) { 8238 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 8239 < Build.VERSION_CODES.FROYO) { 8240 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 8241 + Binder.getCallingUid()); 8242 return; 8243 } 8244 mContext.enforceCallingOrSelfPermission( 8245 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8246 } 8247 } 8248 8249 if (clearPackagePreferredActivitiesLPw(packageName, UserHandle.getCallingUserId())) { 8250 scheduleWriteSettingsLocked(); 8251 } 8252 } 8253 } 8254 8255 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 8256 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 8257 ArrayList<PreferredActivity> removed = null; 8258 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator(); 8259 while (it.hasNext()) { 8260 PreferredActivity pa = it.next(); 8261 if (userId != UserHandle.USER_ALL && pa.mUserId != userId) { 8262 continue; 8263 } 8264 if (pa.mPref.mComponent.getPackageName().equals(packageName)) { 8265 if (removed == null) { 8266 removed = new ArrayList<PreferredActivity>(); 8267 } 8268 removed.add(pa); 8269 } 8270 } 8271 if (removed != null) { 8272 for (int i=0; i<removed.size(); i++) { 8273 PreferredActivity pa = removed.get(i); 8274 mSettings.mPreferredActivities.removeFilter(pa); 8275 } 8276 return true; 8277 } 8278 return false; 8279 } 8280 8281 public int getPreferredActivities(List<IntentFilter> outFilters, 8282 List<ComponentName> outActivities, String packageName) { 8283 8284 int num = 0; 8285 final int userId = UserHandle.getCallingUserId(); 8286 // reader 8287 synchronized (mPackages) { 8288 final Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator(); 8289 while (it.hasNext()) { 8290 final PreferredActivity pa = it.next(); 8291 if (pa.mUserId != userId) { 8292 continue; 8293 } 8294 if (packageName == null 8295 || pa.mPref.mComponent.getPackageName().equals(packageName)) { 8296 if (outFilters != null) { 8297 outFilters.add(new IntentFilter(pa)); 8298 } 8299 if (outActivities != null) { 8300 outActivities.add(pa.mPref.mComponent); 8301 } 8302 } 8303 } 8304 } 8305 8306 return num; 8307 } 8308 8309 @Override 8310 public void setApplicationEnabledSetting(String appPackageName, 8311 int newState, int flags, int userId) { 8312 if (!sUserManager.exists(userId)) return; 8313 setEnabledSetting(appPackageName, null, newState, flags, userId); 8314 } 8315 8316 @Override 8317 public void setComponentEnabledSetting(ComponentName componentName, 8318 int newState, int flags, int userId) { 8319 if (!sUserManager.exists(userId)) return; 8320 setEnabledSetting(componentName.getPackageName(), 8321 componentName.getClassName(), newState, flags, userId); 8322 } 8323 8324 private void setEnabledSetting( 8325 final String packageName, String className, int newState, final int flags, int userId) { 8326 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 8327 || newState == COMPONENT_ENABLED_STATE_ENABLED 8328 || newState == COMPONENT_ENABLED_STATE_DISABLED 8329 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER)) { 8330 throw new IllegalArgumentException("Invalid new component state: " 8331 + newState); 8332 } 8333 PackageSetting pkgSetting; 8334 final int uid = Binder.getCallingUid(); 8335 final int permission = mContext.checkCallingPermission( 8336 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 8337 checkValidCaller(uid, userId); 8338 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 8339 boolean sendNow = false; 8340 boolean isApp = (className == null); 8341 String componentName = isApp ? packageName : className; 8342 int packageUid = -1; 8343 ArrayList<String> components; 8344 8345 // writer 8346 synchronized (mPackages) { 8347 pkgSetting = mSettings.mPackages.get(packageName); 8348 if (pkgSetting == null) { 8349 if (className == null) { 8350 throw new IllegalArgumentException( 8351 "Unknown package: " + packageName); 8352 } 8353 throw new IllegalArgumentException( 8354 "Unknown component: " + packageName 8355 + "/" + className); 8356 } 8357 // Allow root and verify that userId is not being specified by a different user 8358 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 8359 throw new SecurityException( 8360 "Permission Denial: attempt to change component state from pid=" 8361 + Binder.getCallingPid() 8362 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 8363 } 8364 if (className == null) { 8365 // We're dealing with an application/package level state change 8366 if (pkgSetting.getEnabled(userId) == newState) { 8367 // Nothing to do 8368 return; 8369 } 8370 pkgSetting.setEnabled(newState, userId); 8371 // pkgSetting.pkg.mSetEnabled = newState; 8372 } else { 8373 // We're dealing with a component level state change 8374 // First, verify that this is a valid class name. 8375 PackageParser.Package pkg = pkgSetting.pkg; 8376 if (pkg == null || !pkg.hasComponentClassName(className)) { 8377 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 8378 throw new IllegalArgumentException("Component class " + className 8379 + " does not exist in " + packageName); 8380 } else { 8381 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 8382 + className + " does not exist in " + packageName); 8383 } 8384 } 8385 switch (newState) { 8386 case COMPONENT_ENABLED_STATE_ENABLED: 8387 if (!pkgSetting.enableComponentLPw(className, userId)) { 8388 return; 8389 } 8390 break; 8391 case COMPONENT_ENABLED_STATE_DISABLED: 8392 if (!pkgSetting.disableComponentLPw(className, userId)) { 8393 return; 8394 } 8395 break; 8396 case COMPONENT_ENABLED_STATE_DEFAULT: 8397 if (!pkgSetting.restoreComponentLPw(className, userId)) { 8398 return; 8399 } 8400 break; 8401 default: 8402 Slog.e(TAG, "Invalid new component state: " + newState); 8403 return; 8404 } 8405 } 8406 mSettings.writePackageRestrictionsLPr(userId); 8407 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 8408 components = mPendingBroadcasts.get(packageName); 8409 final boolean newPackage = components == null; 8410 if (newPackage) { 8411 components = new ArrayList<String>(); 8412 } 8413 if (!components.contains(componentName)) { 8414 components.add(componentName); 8415 } 8416 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 8417 sendNow = true; 8418 // Purge entry from pending broadcast list if another one exists already 8419 // since we are sending one right away. 8420 mPendingBroadcasts.remove(packageName); 8421 } else { 8422 if (newPackage) { 8423 mPendingBroadcasts.put(packageName, components); 8424 } 8425 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 8426 // Schedule a message 8427 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 8428 } 8429 } 8430 } 8431 8432 long callingId = Binder.clearCallingIdentity(); 8433 try { 8434 if (sendNow) { 8435 sendPackageChangedBroadcast(packageName, 8436 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 8437 } 8438 } finally { 8439 Binder.restoreCallingIdentity(callingId); 8440 } 8441 } 8442 8443 private void sendPackageChangedBroadcast(String packageName, 8444 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 8445 if (DEBUG_INSTALL) 8446 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 8447 + componentNames); 8448 Bundle extras = new Bundle(4); 8449 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 8450 String nameList[] = new String[componentNames.size()]; 8451 componentNames.toArray(nameList); 8452 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 8453 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 8454 extras.putInt(Intent.EXTRA_UID, packageUid); 8455 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 8456 UserHandle.getUserId(packageUid)); 8457 } 8458 8459 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 8460 if (!sUserManager.exists(userId)) return; 8461 final int uid = Binder.getCallingUid(); 8462 final int permission = mContext.checkCallingOrSelfPermission( 8463 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 8464 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 8465 checkValidCaller(uid, userId); 8466 // writer 8467 synchronized (mPackages) { 8468 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 8469 uid, userId)) { 8470 scheduleWritePackageRestrictionsLocked(userId); 8471 } 8472 } 8473 } 8474 8475 public String getInstallerPackageName(String packageName) { 8476 // reader 8477 synchronized (mPackages) { 8478 return mSettings.getInstallerPackageNameLPr(packageName); 8479 } 8480 } 8481 8482 @Override 8483 public int getApplicationEnabledSetting(String packageName, int userId) { 8484 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 8485 int uid = Binder.getCallingUid(); 8486 checkValidCaller(uid, userId); 8487 // reader 8488 synchronized (mPackages) { 8489 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 8490 } 8491 } 8492 8493 @Override 8494 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 8495 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 8496 int uid = Binder.getCallingUid(); 8497 checkValidCaller(uid, userId); 8498 // reader 8499 synchronized (mPackages) { 8500 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 8501 } 8502 } 8503 8504 public void enterSafeMode() { 8505 enforceSystemOrRoot("Only the system can request entering safe mode"); 8506 8507 if (!mSystemReady) { 8508 mSafeMode = true; 8509 } 8510 } 8511 8512 public void systemReady() { 8513 mSystemReady = true; 8514 8515 // Read the compatibilty setting when the system is ready. 8516 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt( 8517 mContext.getContentResolver(), 8518 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1; 8519 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 8520 if (DEBUG_SETTINGS) { 8521 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 8522 } 8523 } 8524 8525 public boolean isSafeMode() { 8526 return mSafeMode; 8527 } 8528 8529 public boolean hasSystemUidErrors() { 8530 return mHasSystemUidErrors; 8531 } 8532 8533 static String arrayToString(int[] array) { 8534 StringBuffer buf = new StringBuffer(128); 8535 buf.append('['); 8536 if (array != null) { 8537 for (int i=0; i<array.length; i++) { 8538 if (i > 0) buf.append(", "); 8539 buf.append(array[i]); 8540 } 8541 } 8542 buf.append(']'); 8543 return buf.toString(); 8544 } 8545 8546 static class DumpState { 8547 public static final int DUMP_LIBS = 1 << 0; 8548 8549 public static final int DUMP_FEATURES = 1 << 1; 8550 8551 public static final int DUMP_RESOLVERS = 1 << 2; 8552 8553 public static final int DUMP_PERMISSIONS = 1 << 3; 8554 8555 public static final int DUMP_PACKAGES = 1 << 4; 8556 8557 public static final int DUMP_SHARED_USERS = 1 << 5; 8558 8559 public static final int DUMP_MESSAGES = 1 << 6; 8560 8561 public static final int DUMP_PROVIDERS = 1 << 7; 8562 8563 public static final int DUMP_VERIFIERS = 1 << 8; 8564 8565 public static final int DUMP_PREFERRED = 1 << 9; 8566 8567 public static final int DUMP_PREFERRED_XML = 1 << 10; 8568 8569 public static final int OPTION_SHOW_FILTERS = 1 << 0; 8570 8571 private int mTypes; 8572 8573 private int mOptions; 8574 8575 private boolean mTitlePrinted; 8576 8577 private SharedUserSetting mSharedUser; 8578 8579 public boolean isDumping(int type) { 8580 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 8581 return true; 8582 } 8583 8584 return (mTypes & type) != 0; 8585 } 8586 8587 public void setDump(int type) { 8588 mTypes |= type; 8589 } 8590 8591 public boolean isOptionEnabled(int option) { 8592 return (mOptions & option) != 0; 8593 } 8594 8595 public void setOptionEnabled(int option) { 8596 mOptions |= option; 8597 } 8598 8599 public boolean onTitlePrinted() { 8600 final boolean printed = mTitlePrinted; 8601 mTitlePrinted = true; 8602 return printed; 8603 } 8604 8605 public boolean getTitlePrinted() { 8606 return mTitlePrinted; 8607 } 8608 8609 public void setTitlePrinted(boolean enabled) { 8610 mTitlePrinted = enabled; 8611 } 8612 8613 public SharedUserSetting getSharedUser() { 8614 return mSharedUser; 8615 } 8616 8617 public void setSharedUser(SharedUserSetting user) { 8618 mSharedUser = user; 8619 } 8620 } 8621 8622 @Override 8623 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 8624 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 8625 != PackageManager.PERMISSION_GRANTED) { 8626 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 8627 + Binder.getCallingPid() 8628 + ", uid=" + Binder.getCallingUid() 8629 + " without permission " 8630 + android.Manifest.permission.DUMP); 8631 return; 8632 } 8633 8634 DumpState dumpState = new DumpState(); 8635 8636 String packageName = null; 8637 8638 int opti = 0; 8639 while (opti < args.length) { 8640 String opt = args[opti]; 8641 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 8642 break; 8643 } 8644 opti++; 8645 if ("-a".equals(opt)) { 8646 // Right now we only know how to print all. 8647 } else if ("-h".equals(opt)) { 8648 pw.println("Package manager dump options:"); 8649 pw.println(" [-h] [-f] [cmd] ..."); 8650 pw.println(" -f: print details of intent filters"); 8651 pw.println(" -h: print this help"); 8652 pw.println(" cmd may be one of:"); 8653 pw.println(" l[ibraries]: list known shared libraries"); 8654 pw.println(" f[ibraries]: list device features"); 8655 pw.println(" r[esolvers]: dump intent resolvers"); 8656 pw.println(" perm[issions]: dump permissions"); 8657 pw.println(" pref[erred]: print preferred package settings"); 8658 pw.println(" preferred-xml: print preferred package settings as xml"); 8659 pw.println(" prov[iders]: dump content providers"); 8660 pw.println(" p[ackages]: dump installed packages"); 8661 pw.println(" s[hared-users]: dump shared user IDs"); 8662 pw.println(" m[essages]: print collected runtime messages"); 8663 pw.println(" v[erifiers]: print package verifier info"); 8664 pw.println(" <package.name>: info about given package"); 8665 return; 8666 } else if ("-f".equals(opt)) { 8667 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 8668 } else { 8669 pw.println("Unknown argument: " + opt + "; use -h for help"); 8670 } 8671 } 8672 8673 // Is the caller requesting to dump a particular piece of data? 8674 if (opti < args.length) { 8675 String cmd = args[opti]; 8676 opti++; 8677 // Is this a package name? 8678 if ("android".equals(cmd) || cmd.contains(".")) { 8679 packageName = cmd; 8680 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 8681 dumpState.setDump(DumpState.DUMP_LIBS); 8682 } else if ("f".equals(cmd) || "features".equals(cmd)) { 8683 dumpState.setDump(DumpState.DUMP_FEATURES); 8684 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 8685 dumpState.setDump(DumpState.DUMP_RESOLVERS); 8686 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 8687 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 8688 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 8689 dumpState.setDump(DumpState.DUMP_PREFERRED); 8690 } else if ("preferred-xml".equals(cmd)) { 8691 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 8692 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 8693 dumpState.setDump(DumpState.DUMP_PACKAGES); 8694 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 8695 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 8696 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 8697 dumpState.setDump(DumpState.DUMP_PROVIDERS); 8698 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 8699 dumpState.setDump(DumpState.DUMP_MESSAGES); 8700 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 8701 dumpState.setDump(DumpState.DUMP_VERIFIERS); 8702 } 8703 } 8704 8705 // reader 8706 synchronized (mPackages) { 8707 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 8708 if (dumpState.onTitlePrinted()) 8709 pw.println(" "); 8710 pw.println("Verifiers:"); 8711 pw.print(" Required: "); 8712 pw.print(mRequiredVerifierPackage); 8713 pw.print(" (uid="); 8714 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 8715 pw.println(")"); 8716 } 8717 8718 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 8719 if (dumpState.onTitlePrinted()) 8720 pw.println(" "); 8721 pw.println("Libraries:"); 8722 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 8723 while (it.hasNext()) { 8724 String name = it.next(); 8725 pw.print(" "); 8726 pw.print(name); 8727 pw.print(" -> "); 8728 pw.println(mSharedLibraries.get(name)); 8729 } 8730 } 8731 8732 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 8733 if (dumpState.onTitlePrinted()) 8734 pw.println(" "); 8735 pw.println("Features:"); 8736 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 8737 while (it.hasNext()) { 8738 String name = it.next(); 8739 pw.print(" "); 8740 pw.println(name); 8741 } 8742 } 8743 8744 if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 8745 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 8746 : "Activity Resolver Table:", " ", packageName, 8747 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 8748 dumpState.setTitlePrinted(true); 8749 } 8750 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 8751 : "Receiver Resolver Table:", " ", packageName, 8752 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 8753 dumpState.setTitlePrinted(true); 8754 } 8755 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 8756 : "Service Resolver Table:", " ", packageName, 8757 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 8758 dumpState.setTitlePrinted(true); 8759 } 8760 } 8761 8762 if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 8763 if (mSettings.mPreferredActivities.dump(pw, 8764 dumpState.getTitlePrinted() ? "\nPreferred Activities:" 8765 : "Preferred Activities:", " ", 8766 packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 8767 dumpState.setTitlePrinted(true); 8768 } 8769 } 8770 8771 if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 8772 pw.flush(); 8773 FileOutputStream fout = new FileOutputStream(fd); 8774 BufferedOutputStream str = new BufferedOutputStream(fout); 8775 XmlSerializer serializer = new FastXmlSerializer(); 8776 try { 8777 serializer.setOutput(str, "utf-8"); 8778 serializer.startDocument(null, true); 8779 serializer.setFeature( 8780 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 8781 mSettings.writePreferredActivitiesLPr(serializer); 8782 serializer.endDocument(); 8783 serializer.flush(); 8784 } catch (IllegalArgumentException e) { 8785 pw.println("Failed writing: " + e); 8786 } catch (IllegalStateException e) { 8787 pw.println("Failed writing: " + e); 8788 } catch (IOException e) { 8789 pw.println("Failed writing: " + e); 8790 } 8791 } 8792 8793 if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 8794 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 8795 } 8796 8797 if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 8798 boolean printedSomething = false; 8799 for (PackageParser.Provider p : mProvidersByComponent.values()) { 8800 if (packageName != null && !packageName.equals(p.info.packageName)) { 8801 continue; 8802 } 8803 if (!printedSomething) { 8804 if (dumpState.onTitlePrinted()) 8805 pw.println(" "); 8806 pw.println("Registered ContentProviders:"); 8807 printedSomething = true; 8808 } 8809 pw.print(" "); pw.print(p.getComponentShortName()); pw.println(":"); 8810 pw.print(" "); pw.println(p.toString()); 8811 } 8812 printedSomething = false; 8813 for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) { 8814 PackageParser.Provider p = entry.getValue(); 8815 if (packageName != null && !packageName.equals(p.info.packageName)) { 8816 continue; 8817 } 8818 if (!printedSomething) { 8819 if (dumpState.onTitlePrinted()) 8820 pw.println(" "); 8821 pw.println("ContentProvider Authorities:"); 8822 printedSomething = true; 8823 } 8824 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 8825 pw.print(" "); pw.println(p.toString()); 8826 if (p.info != null && p.info.applicationInfo != null) { 8827 final String appInfo = p.info.applicationInfo.toString(); 8828 pw.print(" applicationInfo="); pw.println(appInfo); 8829 } 8830 } 8831 } 8832 8833 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 8834 mSettings.dumpPackagesLPr(pw, packageName, dumpState); 8835 } 8836 8837 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 8838 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 8839 } 8840 8841 if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 8842 if (dumpState.onTitlePrinted()) 8843 pw.println(" "); 8844 mSettings.dumpReadMessagesLPr(pw, dumpState); 8845 8846 pw.println(" "); 8847 pw.println("Package warning messages:"); 8848 final File fname = getSettingsProblemFile(); 8849 FileInputStream in = null; 8850 try { 8851 in = new FileInputStream(fname); 8852 final int avail = in.available(); 8853 final byte[] data = new byte[avail]; 8854 in.read(data); 8855 pw.print(new String(data)); 8856 } catch (FileNotFoundException e) { 8857 } catch (IOException e) { 8858 } finally { 8859 if (in != null) { 8860 try { 8861 in.close(); 8862 } catch (IOException e) { 8863 } 8864 } 8865 } 8866 } 8867 } 8868 } 8869 8870 // ------- apps on sdcard specific code ------- 8871 static final boolean DEBUG_SD_INSTALL = false; 8872 8873 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 8874 8875 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 8876 8877 private boolean mMediaMounted = false; 8878 8879 private String getEncryptKey() { 8880 try { 8881 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 8882 SD_ENCRYPTION_KEYSTORE_NAME); 8883 if (sdEncKey == null) { 8884 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 8885 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 8886 if (sdEncKey == null) { 8887 Slog.e(TAG, "Failed to create encryption keys"); 8888 return null; 8889 } 8890 } 8891 return sdEncKey; 8892 } catch (NoSuchAlgorithmException nsae) { 8893 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 8894 return null; 8895 } catch (IOException ioe) { 8896 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 8897 return null; 8898 } 8899 8900 } 8901 8902 /* package */static String getTempContainerId() { 8903 int tmpIdx = 1; 8904 String list[] = PackageHelper.getSecureContainerList(); 8905 if (list != null) { 8906 for (final String name : list) { 8907 // Ignore null and non-temporary container entries 8908 if (name == null || !name.startsWith(mTempContainerPrefix)) { 8909 continue; 8910 } 8911 8912 String subStr = name.substring(mTempContainerPrefix.length()); 8913 try { 8914 int cid = Integer.parseInt(subStr); 8915 if (cid >= tmpIdx) { 8916 tmpIdx = cid + 1; 8917 } 8918 } catch (NumberFormatException e) { 8919 } 8920 } 8921 } 8922 return mTempContainerPrefix + tmpIdx; 8923 } 8924 8925 /* 8926 * Update media status on PackageManager. 8927 */ 8928 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 8929 int callingUid = Binder.getCallingUid(); 8930 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 8931 throw new SecurityException("Media status can only be updated by the system"); 8932 } 8933 // reader; this apparently protects mMediaMounted, but should probably 8934 // be a different lock in that case. 8935 synchronized (mPackages) { 8936 Log.i(TAG, "Updating external media status from " 8937 + (mMediaMounted ? "mounted" : "unmounted") + " to " 8938 + (mediaStatus ? "mounted" : "unmounted")); 8939 if (DEBUG_SD_INSTALL) 8940 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 8941 + ", mMediaMounted=" + mMediaMounted); 8942 if (mediaStatus == mMediaMounted) { 8943 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 8944 : 0, -1); 8945 mHandler.sendMessage(msg); 8946 return; 8947 } 8948 mMediaMounted = mediaStatus; 8949 } 8950 // Queue up an async operation since the package installation may take a 8951 // little while. 8952 mHandler.post(new Runnable() { 8953 public void run() { 8954 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 8955 } 8956 }); 8957 } 8958 8959 /** 8960 * Called by MountService when the initial ASECs to scan are available. 8961 * Should block until all the ASEC containers are finished being scanned. 8962 */ 8963 public void scanAvailableAsecs() { 8964 updateExternalMediaStatusInner(true, false, false); 8965 } 8966 8967 /* 8968 * Collect information of applications on external media, map them against 8969 * existing containers and update information based on current mount status. 8970 * Please note that we always have to report status if reportStatus has been 8971 * set to true especially when unloading packages. 8972 */ 8973 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 8974 boolean externalStorage) { 8975 // Collection of uids 8976 int uidArr[] = null; 8977 // Collection of stale containers 8978 HashSet<String> removeCids = new HashSet<String>(); 8979 // Collection of packages on external media with valid containers. 8980 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 8981 // Get list of secure containers. 8982 final String list[] = PackageHelper.getSecureContainerList(); 8983 if (list == null || list.length == 0) { 8984 Log.i(TAG, "No secure containers on sdcard"); 8985 } else { 8986 // Process list of secure containers and categorize them 8987 // as active or stale based on their package internal state. 8988 int uidList[] = new int[list.length]; 8989 int num = 0; 8990 // reader 8991 synchronized (mPackages) { 8992 for (String cid : list) { 8993 if (DEBUG_SD_INSTALL) 8994 Log.i(TAG, "Processing container " + cid); 8995 String pkgName = getAsecPackageName(cid); 8996 if (pkgName == null) { 8997 if (DEBUG_SD_INSTALL) 8998 Log.i(TAG, "Container : " + cid + " stale"); 8999 removeCids.add(cid); 9000 continue; 9001 } 9002 if (DEBUG_SD_INSTALL) 9003 Log.i(TAG, "Looking for pkg : " + pkgName); 9004 9005 final PackageSetting ps = mSettings.mPackages.get(pkgName); 9006 if (ps == null) { 9007 Log.i(TAG, "Deleting container with no matching settings " + cid); 9008 removeCids.add(cid); 9009 continue; 9010 } 9011 9012 /* 9013 * Skip packages that are not external if we're unmounting 9014 * external storage. 9015 */ 9016 if (externalStorage && !isMounted && !isExternal(ps)) { 9017 continue; 9018 } 9019 9020 final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps)); 9021 // The package status is changed only if the code path 9022 // matches between settings and the container id. 9023 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 9024 if (DEBUG_SD_INSTALL) { 9025 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 9026 + " at code path: " + ps.codePathString); 9027 } 9028 9029 // We do have a valid package installed on sdcard 9030 processCids.put(args, ps.codePathString); 9031 final int uid = ps.appId; 9032 if (uid != -1) { 9033 uidList[num++] = uid; 9034 } 9035 } else { 9036 Log.i(TAG, "Deleting stale container for " + cid); 9037 removeCids.add(cid); 9038 } 9039 } 9040 } 9041 9042 if (num > 0) { 9043 // Sort uid list 9044 Arrays.sort(uidList, 0, num); 9045 // Throw away duplicates 9046 uidArr = new int[num]; 9047 uidArr[0] = uidList[0]; 9048 int di = 0; 9049 for (int i = 1; i < num; i++) { 9050 if (uidList[i - 1] != uidList[i]) { 9051 uidArr[di++] = uidList[i]; 9052 } 9053 } 9054 } 9055 } 9056 // Process packages with valid entries. 9057 if (isMounted) { 9058 if (DEBUG_SD_INSTALL) 9059 Log.i(TAG, "Loading packages"); 9060 loadMediaPackages(processCids, uidArr, removeCids); 9061 startCleaningPackages(); 9062 } else { 9063 if (DEBUG_SD_INSTALL) 9064 Log.i(TAG, "Unloading packages"); 9065 unloadMediaPackages(processCids, uidArr, reportStatus); 9066 } 9067 } 9068 9069 private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList, 9070 int uidArr[], IIntentReceiver finishedReceiver) { 9071 int size = pkgList.size(); 9072 if (size > 0) { 9073 // Send broadcasts here 9074 Bundle extras = new Bundle(); 9075 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 9076 .toArray(new String[size])); 9077 if (uidArr != null) { 9078 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 9079 } 9080 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 9081 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 9082 sendPackageBroadcast(action, null, extras, null, finishedReceiver, UserHandle.USER_ALL); 9083 } 9084 } 9085 9086 /* 9087 * Look at potentially valid container ids from processCids If package 9088 * information doesn't match the one on record or package scanning fails, 9089 * the cid is added to list of removeCids. We currently don't delete stale 9090 * containers. 9091 */ 9092 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 9093 HashSet<String> removeCids) { 9094 ArrayList<String> pkgList = new ArrayList<String>(); 9095 Set<AsecInstallArgs> keys = processCids.keySet(); 9096 boolean doGc = false; 9097 for (AsecInstallArgs args : keys) { 9098 String codePath = processCids.get(args); 9099 if (DEBUG_SD_INSTALL) 9100 Log.i(TAG, "Loading container : " + args.cid); 9101 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9102 try { 9103 // Make sure there are no container errors first. 9104 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 9105 Slog.e(TAG, "Failed to mount cid : " + args.cid 9106 + " when installing from sdcard"); 9107 continue; 9108 } 9109 // Check code path here. 9110 if (codePath == null || !codePath.equals(args.getCodePath())) { 9111 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 9112 + " does not match one in settings " + codePath); 9113 continue; 9114 } 9115 // Parse package 9116 int parseFlags = mDefParseFlags; 9117 if (args.isExternal()) { 9118 parseFlags |= PackageParser.PARSE_ON_SDCARD; 9119 } 9120 if (args.isFwdLocked()) { 9121 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 9122 } 9123 9124 doGc = true; 9125 synchronized (mInstallLock) { 9126 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 9127 0, 0); 9128 // Scan the package 9129 if (pkg != null) { 9130 /* 9131 * TODO why is the lock being held? doPostInstall is 9132 * called in other places without the lock. This needs 9133 * to be straightened out. 9134 */ 9135 // writer 9136 synchronized (mPackages) { 9137 retCode = PackageManager.INSTALL_SUCCEEDED; 9138 pkgList.add(pkg.packageName); 9139 // Post process args 9140 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 9141 pkg.applicationInfo.uid); 9142 } 9143 } else { 9144 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 9145 } 9146 } 9147 9148 } finally { 9149 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 9150 // Don't destroy container here. Wait till gc clears things 9151 // up. 9152 removeCids.add(args.cid); 9153 } 9154 } 9155 } 9156 // writer 9157 synchronized (mPackages) { 9158 // If the platform SDK has changed since the last time we booted, 9159 // we need to re-grant app permission to catch any new ones that 9160 // appear. This is really a hack, and means that apps can in some 9161 // cases get permissions that the user didn't initially explicitly 9162 // allow... it would be nice to have some better way to handle 9163 // this situation. 9164 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 9165 if (regrantPermissions) 9166 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 9167 + mSdkVersion + "; regranting permissions for external storage"); 9168 mSettings.mExternalSdkPlatform = mSdkVersion; 9169 9170 // Make sure group IDs have been assigned, and any permission 9171 // changes in other apps are accounted for 9172 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 9173 | (regrantPermissions 9174 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 9175 : 0)); 9176 // can downgrade to reader 9177 // Persist settings 9178 mSettings.writeLPr(); 9179 } 9180 // Send a broadcast to let everyone know we are done processing 9181 if (pkgList.size() > 0) { 9182 sendResourcesChangedBroadcast(true, pkgList, uidArr, null); 9183 } 9184 // Force gc to avoid any stale parser references that we might have. 9185 if (doGc) { 9186 Runtime.getRuntime().gc(); 9187 } 9188 // List stale containers and destroy stale temporary containers. 9189 if (removeCids != null) { 9190 for (String cid : removeCids) { 9191 if (cid.startsWith(mTempContainerPrefix)) { 9192 Log.i(TAG, "Destroying stale temporary container " + cid); 9193 PackageHelper.destroySdDir(cid); 9194 } else { 9195 Log.w(TAG, "Container " + cid + " is stale"); 9196 } 9197 } 9198 } 9199 } 9200 9201 /* 9202 * Utility method to unload a list of specified containers 9203 */ 9204 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 9205 // Just unmount all valid containers. 9206 for (AsecInstallArgs arg : cidArgs) { 9207 synchronized (mInstallLock) { 9208 arg.doPostDeleteLI(false); 9209 } 9210 } 9211 } 9212 9213 /* 9214 * Unload packages mounted on external media. This involves deleting package 9215 * data from internal structures, sending broadcasts about diabled packages, 9216 * gc'ing to free up references, unmounting all secure containers 9217 * corresponding to packages on external media, and posting a 9218 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 9219 * that we always have to post this message if status has been requested no 9220 * matter what. 9221 */ 9222 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 9223 final boolean reportStatus) { 9224 if (DEBUG_SD_INSTALL) 9225 Log.i(TAG, "unloading media packages"); 9226 ArrayList<String> pkgList = new ArrayList<String>(); 9227 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 9228 final Set<AsecInstallArgs> keys = processCids.keySet(); 9229 for (AsecInstallArgs args : keys) { 9230 String pkgName = args.getPackageName(); 9231 if (DEBUG_SD_INSTALL) 9232 Log.i(TAG, "Trying to unload pkg : " + pkgName); 9233 // Delete package internally 9234 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 9235 synchronized (mInstallLock) { 9236 boolean res = deletePackageLI(pkgName, false, PackageManager.DONT_DELETE_DATA, 9237 outInfo, false); 9238 if (res) { 9239 pkgList.add(pkgName); 9240 } else { 9241 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 9242 failedList.add(args); 9243 } 9244 } 9245 } 9246 9247 // reader 9248 synchronized (mPackages) { 9249 // We didn't update the settings after removing each package; 9250 // write them now for all packages. 9251 mSettings.writeLPr(); 9252 } 9253 9254 // We have to absolutely send UPDATED_MEDIA_STATUS only 9255 // after confirming that all the receivers processed the ordered 9256 // broadcast when packages get disabled, force a gc to clean things up. 9257 // and unload all the containers. 9258 if (pkgList.size() > 0) { 9259 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() { 9260 public void performReceive(Intent intent, int resultCode, String data, 9261 Bundle extras, boolean ordered, boolean sticky) throws RemoteException { 9262 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 9263 reportStatus ? 1 : 0, 1, keys); 9264 mHandler.sendMessage(msg); 9265 } 9266 }); 9267 } else { 9268 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 9269 keys); 9270 mHandler.sendMessage(msg); 9271 } 9272 } 9273 9274 public void movePackage(final String packageName, final IPackageMoveObserver observer, 9275 final int flags) { 9276 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 9277 int returnCode = PackageManager.MOVE_SUCCEEDED; 9278 int currFlags = 0; 9279 int newFlags = 0; 9280 // reader 9281 synchronized (mPackages) { 9282 PackageParser.Package pkg = mPackages.get(packageName); 9283 if (pkg == null) { 9284 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 9285 } else { 9286 // Disable moving fwd locked apps and system packages 9287 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 9288 Slog.w(TAG, "Cannot move system application"); 9289 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 9290 } else if (pkg.mOperationPending) { 9291 Slog.w(TAG, "Attempt to move package which has pending operations"); 9292 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 9293 } else { 9294 // Find install location first 9295 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 9296 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 9297 Slog.w(TAG, "Ambigous flags specified for move location."); 9298 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 9299 } else { 9300 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 9301 : PackageManager.INSTALL_INTERNAL; 9302 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 9303 : PackageManager.INSTALL_INTERNAL; 9304 9305 if (newFlags == currFlags) { 9306 Slog.w(TAG, "No move required. Trying to move to same location"); 9307 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 9308 } else { 9309 if (isForwardLocked(pkg)) { 9310 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9311 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9312 } 9313 } 9314 } 9315 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9316 pkg.mOperationPending = true; 9317 } 9318 } 9319 } 9320 9321 /* 9322 * TODO this next block probably shouldn't be inside the lock. We 9323 * can't guarantee these won't change after this is fired off 9324 * anyway. 9325 */ 9326 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 9327 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1), 9328 returnCode); 9329 } else { 9330 Message msg = mHandler.obtainMessage(INIT_COPY); 9331 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 9332 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir); 9333 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 9334 pkg.applicationInfo.dataDir, pkg.applicationInfo.uid); 9335 msg.obj = mp; 9336 mHandler.sendMessage(msg); 9337 } 9338 } 9339 } 9340 9341 private void processPendingMove(final MoveParams mp, final int currentStatus) { 9342 // Queue up an async operation since the package deletion may take a 9343 // little while. 9344 mHandler.post(new Runnable() { 9345 public void run() { 9346 // TODO fix this; this does nothing. 9347 mHandler.removeCallbacks(this); 9348 int returnCode = currentStatus; 9349 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 9350 int uidArr[] = null; 9351 ArrayList<String> pkgList = null; 9352 synchronized (mPackages) { 9353 PackageParser.Package pkg = mPackages.get(mp.packageName); 9354 if (pkg == null) { 9355 Slog.w(TAG, " Package " + mp.packageName 9356 + " doesn't exist. Aborting move"); 9357 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 9358 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 9359 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 9360 + mp.srcArgs.getCodePath() + " to " 9361 + pkg.applicationInfo.sourceDir 9362 + " Aborting move and returning error"); 9363 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9364 } else { 9365 uidArr = new int[] { 9366 pkg.applicationInfo.uid 9367 }; 9368 pkgList = new ArrayList<String>(); 9369 pkgList.add(mp.packageName); 9370 } 9371 } 9372 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9373 // Send resources unavailable broadcast 9374 sendResourcesChangedBroadcast(false, pkgList, uidArr, null); 9375 // Update package code and resource paths 9376 synchronized (mInstallLock) { 9377 synchronized (mPackages) { 9378 PackageParser.Package pkg = mPackages.get(mp.packageName); 9379 // Recheck for package again. 9380 if (pkg == null) { 9381 Slog.w(TAG, " Package " + mp.packageName 9382 + " doesn't exist. Aborting move"); 9383 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 9384 } else if (!mp.srcArgs.getCodePath().equals( 9385 pkg.applicationInfo.sourceDir)) { 9386 Slog.w(TAG, "Package " + mp.packageName 9387 + " code path changed from " + mp.srcArgs.getCodePath() 9388 + " to " + pkg.applicationInfo.sourceDir 9389 + " Aborting move and returning error"); 9390 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9391 } else { 9392 final String oldCodePath = pkg.mPath; 9393 final String newCodePath = mp.targetArgs.getCodePath(); 9394 final String newResPath = mp.targetArgs.getResourcePath(); 9395 final String newNativePath = mp.targetArgs 9396 .getNativeLibraryPath(); 9397 9398 try { 9399 final File newNativeDir = new File(newNativePath); 9400 9401 final String libParentDir = newNativeDir.getParentFile() 9402 .getCanonicalPath(); 9403 if (newNativeDir.getParentFile().getCanonicalPath() 9404 .equals(pkg.applicationInfo.dataDir)) { 9405 if (mInstaller 9406 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) { 9407 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9408 } else { 9409 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 9410 new File(newCodePath), newNativeDir); 9411 } 9412 } else { 9413 if (mInstaller.linkNativeLibraryDirectory( 9414 pkg.applicationInfo.dataDir, newNativePath) < 0) { 9415 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9416 } 9417 } 9418 } catch (IOException e) { 9419 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 9420 } 9421 9422 9423 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9424 pkg.mPath = newCodePath; 9425 // Move dex files around 9426 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 9427 // Moving of dex files failed. Set 9428 // error code and abort move. 9429 pkg.mPath = pkg.mScanPath; 9430 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9431 } 9432 } 9433 9434 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9435 pkg.mScanPath = newCodePath; 9436 pkg.applicationInfo.sourceDir = newCodePath; 9437 pkg.applicationInfo.publicSourceDir = newResPath; 9438 pkg.applicationInfo.nativeLibraryDir = newNativePath; 9439 PackageSetting ps = (PackageSetting) pkg.mExtras; 9440 ps.codePath = new File(pkg.applicationInfo.sourceDir); 9441 ps.codePathString = ps.codePath.getPath(); 9442 ps.resourcePath = new File( 9443 pkg.applicationInfo.publicSourceDir); 9444 ps.resourcePathString = ps.resourcePath.getPath(); 9445 ps.nativeLibraryPathString = newNativePath; 9446 // Set the application info flag 9447 // correctly. 9448 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9449 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 9450 } else { 9451 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 9452 } 9453 ps.setFlags(pkg.applicationInfo.flags); 9454 mAppDirs.remove(oldCodePath); 9455 mAppDirs.put(newCodePath, pkg); 9456 // Persist settings 9457 mSettings.writeLPr(); 9458 } 9459 } 9460 } 9461 } 9462 // Send resources available broadcast 9463 sendResourcesChangedBroadcast(true, pkgList, uidArr, null); 9464 } 9465 } 9466 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 9467 // Clean up failed installation 9468 if (mp.targetArgs != null) { 9469 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 9470 -1); 9471 } 9472 } else { 9473 // Force a gc to clear things up. 9474 Runtime.getRuntime().gc(); 9475 // Delete older code 9476 synchronized (mInstallLock) { 9477 mp.srcArgs.doPostDeleteLI(true); 9478 } 9479 } 9480 9481 // Allow more operations on this file if we didn't fail because 9482 // an operation was already pending for this package. 9483 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 9484 synchronized (mPackages) { 9485 PackageParser.Package pkg = mPackages.get(mp.packageName); 9486 if (pkg != null) { 9487 pkg.mOperationPending = false; 9488 } 9489 } 9490 } 9491 9492 IPackageMoveObserver observer = mp.observer; 9493 if (observer != null) { 9494 try { 9495 observer.packageMoved(mp.packageName, returnCode); 9496 } catch (RemoteException e) { 9497 Log.i(TAG, "Observer no longer exists."); 9498 } 9499 } 9500 } 9501 }); 9502 } 9503 9504 public boolean setInstallLocation(int loc) { 9505 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 9506 null); 9507 if (getInstallLocation() == loc) { 9508 return true; 9509 } 9510 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 9511 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 9512 android.provider.Settings.System.putInt(mContext.getContentResolver(), 9513 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc); 9514 return true; 9515 } 9516 return false; 9517 } 9518 9519 public int getInstallLocation() { 9520 return android.provider.Settings.System.getInt(mContext.getContentResolver(), 9521 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, 9522 PackageHelper.APP_INSTALL_AUTO); 9523 } 9524 9525 /** Called by UserManagerService */ 9526 void cleanUpUser(int userHandle) { 9527 // Disable all the packages for the user first 9528 synchronized (mPackages) { 9529 Set<Entry<String, PackageSetting>> entries = mSettings.mPackages.entrySet(); 9530 for (Entry<String, PackageSetting> entry : entries) { 9531 entry.getValue().removeUser(userHandle); 9532 } 9533 if (mDirtyUsers.remove(userHandle)); 9534 mSettings.removeUserLPr(userHandle); 9535 } 9536 } 9537 9538 @Override 9539 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 9540 mContext.enforceCallingOrSelfPermission( 9541 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9542 "Only package verification agents can read the verifier device identity"); 9543 9544 synchronized (mPackages) { 9545 return mSettings.getVerifierDeviceIdentityLPw(); 9546 } 9547 } 9548 9549 @Override 9550 public void setPermissionEnforced(String permission, boolean enforced) { 9551 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 9552 if (READ_EXTERNAL_STORAGE.equals(permission)) { 9553 synchronized (mPackages) { 9554 if (mSettings.mReadExternalStorageEnforced == null 9555 || mSettings.mReadExternalStorageEnforced != enforced) { 9556 mSettings.mReadExternalStorageEnforced = enforced; 9557 mSettings.writeLPr(); 9558 9559 // kill any non-foreground processes so we restart them and 9560 // grant/revoke the GID. 9561 final IActivityManager am = ActivityManagerNative.getDefault(); 9562 if (am != null) { 9563 final long token = Binder.clearCallingIdentity(); 9564 try { 9565 am.killProcessesBelowForeground("setPermissionEnforcement"); 9566 } catch (RemoteException e) { 9567 } finally { 9568 Binder.restoreCallingIdentity(token); 9569 } 9570 } 9571 } 9572 } 9573 } else { 9574 throw new IllegalArgumentException("No selective enforcement for " + permission); 9575 } 9576 } 9577 9578 @Override 9579 public boolean isPermissionEnforced(String permission) { 9580 synchronized (mPackages) { 9581 return isPermissionEnforcedLocked(permission); 9582 } 9583 } 9584 9585 private boolean isPermissionEnforcedLocked(String permission) { 9586 if (READ_EXTERNAL_STORAGE.equals(permission)) { 9587 if (mSettings.mReadExternalStorageEnforced != null) { 9588 return mSettings.mReadExternalStorageEnforced; 9589 } else { 9590 // if user hasn't defined, fall back to secure default 9591 return Secure.getInt(mContext.getContentResolver(), 9592 Secure.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0) != 0; 9593 } 9594 } else { 9595 return true; 9596 } 9597 } 9598 9599 public boolean isStorageLow() { 9600 final long token = Binder.clearCallingIdentity(); 9601 try { 9602 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 9603 .getService(DeviceStorageMonitorService.SERVICE); 9604 return dsm.isMemoryLow(); 9605 } finally { 9606 Binder.restoreCallingIdentity(token); 9607 } 9608 } 9609} 9610