PackageInstallerService.java revision 6788212d17f54475ca9c3dd689a863e031db868f
1/* 2 * Copyright (C) 2014 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 com.android.internal.util.XmlUtils.readBitmapAttribute; 20import static com.android.internal.util.XmlUtils.readBooleanAttribute; 21import static com.android.internal.util.XmlUtils.readIntAttribute; 22import static com.android.internal.util.XmlUtils.readLongAttribute; 23import static com.android.internal.util.XmlUtils.readStringAttribute; 24import static com.android.internal.util.XmlUtils.readUriAttribute; 25import static com.android.internal.util.XmlUtils.writeBooleanAttribute; 26import static com.android.internal.util.XmlUtils.writeIntAttribute; 27import static com.android.internal.util.XmlUtils.writeLongAttribute; 28import static com.android.internal.util.XmlUtils.writeStringAttribute; 29import static com.android.internal.util.XmlUtils.writeUriAttribute; 30import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; 31import static org.xmlpull.v1.XmlPullParser.START_TAG; 32 33import android.Manifest; 34import android.app.ActivityManager; 35import android.app.AppGlobals; 36import android.app.AppOpsManager; 37import android.app.Notification; 38import android.app.NotificationManager; 39import android.app.PackageDeleteObserver; 40import android.app.PackageInstallObserver; 41import android.app.admin.DevicePolicyManager; 42import android.content.Context; 43import android.content.Intent; 44import android.content.IntentSender; 45import android.content.IntentSender.SendIntentException; 46import android.content.pm.IPackageInstaller; 47import android.content.pm.IPackageInstallerCallback; 48import android.content.pm.IPackageInstallerSession; 49import android.content.pm.PackageInfo; 50import android.content.pm.PackageInstaller; 51import android.content.pm.PackageInstaller.SessionInfo; 52import android.content.pm.PackageInstaller.SessionParams; 53import android.content.pm.PackageManager; 54import android.content.pm.ParceledListSlice; 55import android.content.pm.VersionedPackage; 56import android.graphics.Bitmap; 57import android.graphics.Bitmap.CompressFormat; 58import android.graphics.BitmapFactory; 59import android.net.Uri; 60import android.os.Binder; 61import android.os.Bundle; 62import android.os.Environment; 63import android.os.Handler; 64import android.os.HandlerThread; 65import android.os.Looper; 66import android.os.Message; 67import android.os.Process; 68import android.os.RemoteCallbackList; 69import android.os.RemoteException; 70import android.os.SELinux; 71import android.os.UserHandle; 72import android.os.UserManager; 73import android.os.storage.StorageManager; 74import android.system.ErrnoException; 75import android.system.Os; 76import android.text.TextUtils; 77import android.text.format.DateUtils; 78import android.util.ArraySet; 79import android.util.AtomicFile; 80import android.util.ExceptionUtils; 81import android.util.Slog; 82import android.util.SparseArray; 83import android.util.SparseBooleanArray; 84import android.util.Xml; 85 86import libcore.io.IoUtils; 87 88import com.android.internal.R; 89import com.android.internal.annotations.GuardedBy; 90import com.android.internal.content.PackageHelper; 91import com.android.internal.util.FastXmlSerializer; 92import com.android.internal.util.ImageUtils; 93import com.android.internal.util.IndentingPrintWriter; 94import com.android.server.IoThread; 95 96import org.xmlpull.v1.XmlPullParser; 97import org.xmlpull.v1.XmlPullParserException; 98import org.xmlpull.v1.XmlSerializer; 99 100import java.io.File; 101import java.io.FileInputStream; 102import java.io.FileNotFoundException; 103import java.io.FileOutputStream; 104import java.io.FilenameFilter; 105import java.io.IOException; 106import java.nio.charset.StandardCharsets; 107import java.security.SecureRandom; 108import java.util.ArrayList; 109import java.util.Collections; 110import java.util.List; 111import java.util.Objects; 112import java.util.Random; 113 114public class PackageInstallerService extends IPackageInstaller.Stub { 115 private static final String TAG = "PackageInstaller"; 116 private static final boolean LOGD = false; 117 118 // TODO: remove outstanding sessions when installer package goes away 119 // TODO: notify listeners in other users when package has been installed there 120 // TODO: purge expired sessions periodically in addition to at reboot 121 122 /** XML constants used in {@link #mSessionsFile} */ 123 private static final String TAG_SESSIONS = "sessions"; 124 private static final String TAG_SESSION = "session"; 125 private static final String TAG_GRANTED_RUNTIME_PERMISSION = "granted-runtime-permission"; 126 private static final String ATTR_SESSION_ID = "sessionId"; 127 private static final String ATTR_USER_ID = "userId"; 128 private static final String ATTR_INSTALLER_PACKAGE_NAME = "installerPackageName"; 129 private static final String ATTR_INSTALLER_UID = "installerUid"; 130 private static final String ATTR_CREATED_MILLIS = "createdMillis"; 131 private static final String ATTR_SESSION_STAGE_DIR = "sessionStageDir"; 132 private static final String ATTR_SESSION_STAGE_CID = "sessionStageCid"; 133 private static final String ATTR_PREPARED = "prepared"; 134 private static final String ATTR_SEALED = "sealed"; 135 private static final String ATTR_MODE = "mode"; 136 private static final String ATTR_INSTALL_FLAGS = "installFlags"; 137 private static final String ATTR_INSTALL_LOCATION = "installLocation"; 138 private static final String ATTR_SIZE_BYTES = "sizeBytes"; 139 private static final String ATTR_APP_PACKAGE_NAME = "appPackageName"; 140 @Deprecated 141 private static final String ATTR_APP_ICON = "appIcon"; 142 private static final String ATTR_APP_LABEL = "appLabel"; 143 private static final String ATTR_ORIGINATING_URI = "originatingUri"; 144 private static final String ATTR_ORIGINATING_UID = "originatingUid"; 145 private static final String ATTR_REFERRER_URI = "referrerUri"; 146 private static final String ATTR_ABI_OVERRIDE = "abiOverride"; 147 private static final String ATTR_VOLUME_UUID = "volumeUuid"; 148 private static final String ATTR_NAME = "name"; 149 private static final String ATTR_INSTALL_REASON = "installRason"; 150 151 /** Automatically destroy sessions older than this */ 152 private static final long MAX_AGE_MILLIS = 3 * DateUtils.DAY_IN_MILLIS; 153 /** Upper bound on number of active sessions for a UID */ 154 private static final long MAX_ACTIVE_SESSIONS = 1024; 155 /** Upper bound on number of historical sessions for a UID */ 156 private static final long MAX_HISTORICAL_SESSIONS = 1048576; 157 158 private final Context mContext; 159 private final PackageManagerService mPm; 160 161 private AppOpsManager mAppOps; 162 163 private final HandlerThread mInstallThread; 164 private final Handler mInstallHandler; 165 166 private final Callbacks mCallbacks; 167 168 /** 169 * File storing persisted {@link #mSessions} metadata. 170 */ 171 private final AtomicFile mSessionsFile; 172 173 /** 174 * Directory storing persisted {@link #mSessions} metadata which is too 175 * heavy to store directly in {@link #mSessionsFile}. 176 */ 177 private final File mSessionsDir; 178 179 private final InternalCallback mInternalCallback = new InternalCallback(); 180 181 /** 182 * Used for generating session IDs. Since this is created at boot time, 183 * normal random might be predictable. 184 */ 185 private final Random mRandom = new SecureRandom(); 186 187 /** All sessions allocated */ 188 @GuardedBy("mSessions") 189 private final SparseBooleanArray mAllocatedSessions = new SparseBooleanArray(); 190 191 @GuardedBy("mSessions") 192 private final SparseArray<PackageInstallerSession> mSessions = new SparseArray<>(); 193 194 /** Historical sessions kept around for debugging purposes */ 195 @GuardedBy("mSessions") 196 private final SparseArray<PackageInstallerSession> mHistoricalSessions = new SparseArray<>(); 197 198 /** Sessions allocated to legacy users */ 199 @GuardedBy("mSessions") 200 private final SparseBooleanArray mLegacySessions = new SparseBooleanArray(); 201 202 private static final FilenameFilter sStageFilter = new FilenameFilter() { 203 @Override 204 public boolean accept(File dir, String name) { 205 return isStageName(name); 206 } 207 }; 208 209 public PackageInstallerService(Context context, PackageManagerService pm) { 210 mContext = context; 211 mPm = pm; 212 213 mInstallThread = new HandlerThread(TAG); 214 mInstallThread.start(); 215 216 mInstallHandler = new Handler(mInstallThread.getLooper()); 217 218 mCallbacks = new Callbacks(mInstallThread.getLooper()); 219 220 mSessionsFile = new AtomicFile( 221 new File(Environment.getDataSystemDirectory(), "install_sessions.xml")); 222 mSessionsDir = new File(Environment.getDataSystemDirectory(), "install_sessions"); 223 mSessionsDir.mkdirs(); 224 225 synchronized (mSessions) { 226 readSessionsLocked(); 227 228 reconcileStagesLocked(StorageManager.UUID_PRIVATE_INTERNAL, false /*isEphemeral*/); 229 reconcileStagesLocked(StorageManager.UUID_PRIVATE_INTERNAL, true /*isEphemeral*/); 230 231 final ArraySet<File> unclaimedIcons = newArraySet( 232 mSessionsDir.listFiles()); 233 234 // Ignore stages and icons claimed by active sessions 235 for (int i = 0; i < mSessions.size(); i++) { 236 final PackageInstallerSession session = mSessions.valueAt(i); 237 unclaimedIcons.remove(buildAppIconFile(session.sessionId)); 238 } 239 240 // Clean up orphaned icons 241 for (File icon : unclaimedIcons) { 242 Slog.w(TAG, "Deleting orphan icon " + icon); 243 icon.delete(); 244 } 245 } 246 } 247 248 public void systemReady() { 249 mAppOps = mContext.getSystemService(AppOpsManager.class); 250 } 251 252 private void reconcileStagesLocked(String volumeUuid, boolean isEphemeral) { 253 final File stagingDir = buildStagingDir(volumeUuid, isEphemeral); 254 final ArraySet<File> unclaimedStages = newArraySet( 255 stagingDir.listFiles(sStageFilter)); 256 257 // Ignore stages claimed by active sessions 258 for (int i = 0; i < mSessions.size(); i++) { 259 final PackageInstallerSession session = mSessions.valueAt(i); 260 unclaimedStages.remove(session.stageDir); 261 } 262 263 // Clean up orphaned staging directories 264 for (File stage : unclaimedStages) { 265 Slog.w(TAG, "Deleting orphan stage " + stage); 266 synchronized (mPm.mInstallLock) { 267 mPm.removeCodePathLI(stage); 268 } 269 } 270 } 271 272 public void onPrivateVolumeMounted(String volumeUuid) { 273 synchronized (mSessions) { 274 reconcileStagesLocked(volumeUuid, false /*isEphemeral*/); 275 } 276 } 277 278 public void onSecureContainersAvailable() { 279 synchronized (mSessions) { 280 final ArraySet<String> unclaimed = new ArraySet<>(); 281 for (String cid : PackageHelper.getSecureContainerList()) { 282 if (isStageName(cid)) { 283 unclaimed.add(cid); 284 } 285 } 286 287 // Ignore stages claimed by active sessions 288 for (int i = 0; i < mSessions.size(); i++) { 289 final PackageInstallerSession session = mSessions.valueAt(i); 290 final String cid = session.stageCid; 291 292 if (unclaimed.remove(cid)) { 293 // Claimed by active session, mount it 294 PackageHelper.mountSdDir(cid, PackageManagerService.getEncryptKey(), 295 Process.SYSTEM_UID); 296 } 297 } 298 299 // Clean up orphaned staging containers 300 for (String cid : unclaimed) { 301 Slog.w(TAG, "Deleting orphan container " + cid); 302 PackageHelper.destroySdDir(cid); 303 } 304 } 305 } 306 307 public static boolean isStageName(String name) { 308 final boolean isFile = name.startsWith("vmdl") && name.endsWith(".tmp"); 309 final boolean isContainer = name.startsWith("smdl") && name.endsWith(".tmp"); 310 final boolean isLegacyContainer = name.startsWith("smdl2tmp"); 311 return isFile || isContainer || isLegacyContainer; 312 } 313 314 @Deprecated 315 public File allocateStageDirLegacy(String volumeUuid, boolean isEphemeral) throws IOException { 316 synchronized (mSessions) { 317 try { 318 final int sessionId = allocateSessionIdLocked(); 319 mLegacySessions.put(sessionId, true); 320 final File stageDir = buildStageDir(volumeUuid, sessionId, isEphemeral); 321 prepareStageDir(stageDir); 322 return stageDir; 323 } catch (IllegalStateException e) { 324 throw new IOException(e); 325 } 326 } 327 } 328 329 @Deprecated 330 public String allocateExternalStageCidLegacy() { 331 synchronized (mSessions) { 332 final int sessionId = allocateSessionIdLocked(); 333 mLegacySessions.put(sessionId, true); 334 return "smdl" + sessionId + ".tmp"; 335 } 336 } 337 338 private void readSessionsLocked() { 339 if (LOGD) Slog.v(TAG, "readSessionsLocked()"); 340 341 mSessions.clear(); 342 343 FileInputStream fis = null; 344 try { 345 fis = mSessionsFile.openRead(); 346 final XmlPullParser in = Xml.newPullParser(); 347 in.setInput(fis, StandardCharsets.UTF_8.name()); 348 349 int type; 350 while ((type = in.next()) != END_DOCUMENT) { 351 if (type == START_TAG) { 352 final String tag = in.getName(); 353 if (TAG_SESSION.equals(tag)) { 354 final PackageInstallerSession session = readSessionLocked(in); 355 final long age = System.currentTimeMillis() - session.createdMillis; 356 357 final boolean valid; 358 if (age >= MAX_AGE_MILLIS) { 359 Slog.w(TAG, "Abandoning old session first created at " 360 + session.createdMillis); 361 valid = false; 362 } else { 363 valid = true; 364 } 365 366 if (valid) { 367 mSessions.put(session.sessionId, session); 368 } else { 369 // Since this is early during boot we don't send 370 // any observer events about the session, but we 371 // keep details around for dumpsys. 372 mHistoricalSessions.put(session.sessionId, session); 373 } 374 mAllocatedSessions.put(session.sessionId, true); 375 } 376 } 377 } 378 } catch (FileNotFoundException e) { 379 // Missing sessions are okay, probably first boot 380 } catch (IOException | XmlPullParserException e) { 381 Slog.wtf(TAG, "Failed reading install sessions", e); 382 } finally { 383 IoUtils.closeQuietly(fis); 384 } 385 } 386 387 private PackageInstallerSession readSessionLocked(XmlPullParser in) throws IOException, 388 XmlPullParserException { 389 final int sessionId = readIntAttribute(in, ATTR_SESSION_ID); 390 final int userId = readIntAttribute(in, ATTR_USER_ID); 391 final String installerPackageName = readStringAttribute(in, ATTR_INSTALLER_PACKAGE_NAME); 392 final int installerUid = readIntAttribute(in, ATTR_INSTALLER_UID, mPm.getPackageUid( 393 installerPackageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, userId)); 394 final long createdMillis = readLongAttribute(in, ATTR_CREATED_MILLIS); 395 final String stageDirRaw = readStringAttribute(in, ATTR_SESSION_STAGE_DIR); 396 final File stageDir = (stageDirRaw != null) ? new File(stageDirRaw) : null; 397 final String stageCid = readStringAttribute(in, ATTR_SESSION_STAGE_CID); 398 final boolean prepared = readBooleanAttribute(in, ATTR_PREPARED, true); 399 final boolean sealed = readBooleanAttribute(in, ATTR_SEALED); 400 401 final SessionParams params = new SessionParams( 402 SessionParams.MODE_INVALID); 403 params.mode = readIntAttribute(in, ATTR_MODE); 404 params.installFlags = readIntAttribute(in, ATTR_INSTALL_FLAGS); 405 params.installLocation = readIntAttribute(in, ATTR_INSTALL_LOCATION); 406 params.sizeBytes = readLongAttribute(in, ATTR_SIZE_BYTES); 407 params.appPackageName = readStringAttribute(in, ATTR_APP_PACKAGE_NAME); 408 params.appIcon = readBitmapAttribute(in, ATTR_APP_ICON); 409 params.appLabel = readStringAttribute(in, ATTR_APP_LABEL); 410 params.originatingUri = readUriAttribute(in, ATTR_ORIGINATING_URI); 411 params.originatingUid = 412 readIntAttribute(in, ATTR_ORIGINATING_UID, SessionParams.UID_UNKNOWN); 413 params.referrerUri = readUriAttribute(in, ATTR_REFERRER_URI); 414 params.abiOverride = readStringAttribute(in, ATTR_ABI_OVERRIDE); 415 params.volumeUuid = readStringAttribute(in, ATTR_VOLUME_UUID); 416 params.grantedRuntimePermissions = readGrantedRuntimePermissions(in); 417 params.installReason = readIntAttribute(in, ATTR_INSTALL_REASON); 418 419 final File appIconFile = buildAppIconFile(sessionId); 420 if (appIconFile.exists()) { 421 params.appIcon = BitmapFactory.decodeFile(appIconFile.getAbsolutePath()); 422 params.appIconLastModified = appIconFile.lastModified(); 423 } 424 425 return new PackageInstallerSession(mInternalCallback, mContext, mPm, 426 mInstallThread.getLooper(), sessionId, userId, installerPackageName, installerUid, 427 params, createdMillis, stageDir, stageCid, prepared, sealed); 428 } 429 430 private void writeSessionsLocked() { 431 if (LOGD) Slog.v(TAG, "writeSessionsLocked()"); 432 433 FileOutputStream fos = null; 434 try { 435 fos = mSessionsFile.startWrite(); 436 437 XmlSerializer out = new FastXmlSerializer(); 438 out.setOutput(fos, StandardCharsets.UTF_8.name()); 439 out.startDocument(null, true); 440 out.startTag(null, TAG_SESSIONS); 441 final int size = mSessions.size(); 442 for (int i = 0; i < size; i++) { 443 final PackageInstallerSession session = mSessions.valueAt(i); 444 writeSessionLocked(out, session); 445 } 446 out.endTag(null, TAG_SESSIONS); 447 out.endDocument(); 448 449 mSessionsFile.finishWrite(fos); 450 } catch (IOException e) { 451 if (fos != null) { 452 mSessionsFile.failWrite(fos); 453 } 454 } 455 } 456 457 private void writeSessionLocked(XmlSerializer out, PackageInstallerSession session) 458 throws IOException { 459 final SessionParams params = session.params; 460 461 out.startTag(null, TAG_SESSION); 462 463 writeIntAttribute(out, ATTR_SESSION_ID, session.sessionId); 464 writeIntAttribute(out, ATTR_USER_ID, session.userId); 465 writeStringAttribute(out, ATTR_INSTALLER_PACKAGE_NAME, 466 session.installerPackageName); 467 writeIntAttribute(out, ATTR_INSTALLER_UID, session.installerUid); 468 writeLongAttribute(out, ATTR_CREATED_MILLIS, session.createdMillis); 469 if (session.stageDir != null) { 470 writeStringAttribute(out, ATTR_SESSION_STAGE_DIR, 471 session.stageDir.getAbsolutePath()); 472 } 473 if (session.stageCid != null) { 474 writeStringAttribute(out, ATTR_SESSION_STAGE_CID, session.stageCid); 475 } 476 writeBooleanAttribute(out, ATTR_PREPARED, session.isPrepared()); 477 writeBooleanAttribute(out, ATTR_SEALED, session.isSealed()); 478 479 writeIntAttribute(out, ATTR_MODE, params.mode); 480 writeIntAttribute(out, ATTR_INSTALL_FLAGS, params.installFlags); 481 writeIntAttribute(out, ATTR_INSTALL_LOCATION, params.installLocation); 482 writeLongAttribute(out, ATTR_SIZE_BYTES, params.sizeBytes); 483 writeStringAttribute(out, ATTR_APP_PACKAGE_NAME, params.appPackageName); 484 writeStringAttribute(out, ATTR_APP_LABEL, params.appLabel); 485 writeUriAttribute(out, ATTR_ORIGINATING_URI, params.originatingUri); 486 writeIntAttribute(out, ATTR_ORIGINATING_UID, params.originatingUid); 487 writeUriAttribute(out, ATTR_REFERRER_URI, params.referrerUri); 488 writeStringAttribute(out, ATTR_ABI_OVERRIDE, params.abiOverride); 489 writeStringAttribute(out, ATTR_VOLUME_UUID, params.volumeUuid); 490 writeIntAttribute(out, ATTR_INSTALL_REASON, params.installReason); 491 492 // Persist app icon if changed since last written 493 final File appIconFile = buildAppIconFile(session.sessionId); 494 if (params.appIcon == null && appIconFile.exists()) { 495 appIconFile.delete(); 496 } else if (params.appIcon != null 497 && appIconFile.lastModified() != params.appIconLastModified) { 498 if (LOGD) Slog.w(TAG, "Writing changed icon " + appIconFile); 499 FileOutputStream os = null; 500 try { 501 os = new FileOutputStream(appIconFile); 502 params.appIcon.compress(CompressFormat.PNG, 90, os); 503 } catch (IOException e) { 504 Slog.w(TAG, "Failed to write icon " + appIconFile + ": " + e.getMessage()); 505 } finally { 506 IoUtils.closeQuietly(os); 507 } 508 509 params.appIconLastModified = appIconFile.lastModified(); 510 } 511 512 writeGrantedRuntimePermissions(out, params.grantedRuntimePermissions); 513 514 out.endTag(null, TAG_SESSION); 515 } 516 517 private static void writeGrantedRuntimePermissions(XmlSerializer out, 518 String[] grantedRuntimePermissions) throws IOException { 519 if (grantedRuntimePermissions != null) { 520 for (String permission : grantedRuntimePermissions) { 521 out.startTag(null, TAG_GRANTED_RUNTIME_PERMISSION); 522 writeStringAttribute(out, ATTR_NAME, permission); 523 out.endTag(null, TAG_GRANTED_RUNTIME_PERMISSION); 524 } 525 } 526 } 527 528 private static String[] readGrantedRuntimePermissions(XmlPullParser in) 529 throws IOException, XmlPullParserException { 530 List<String> permissions = null; 531 532 final int outerDepth = in.getDepth(); 533 int type; 534 while ((type = in.next()) != XmlPullParser.END_DOCUMENT 535 && (type != XmlPullParser.END_TAG || in.getDepth() > outerDepth)) { 536 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 537 continue; 538 } 539 if (TAG_GRANTED_RUNTIME_PERMISSION.equals(in.getName())) { 540 String permission = readStringAttribute(in, ATTR_NAME); 541 if (permissions == null) { 542 permissions = new ArrayList<>(); 543 } 544 permissions.add(permission); 545 } 546 } 547 548 if (permissions == null) { 549 return null; 550 } 551 552 String[] permissionsArray = new String[permissions.size()]; 553 permissions.toArray(permissionsArray); 554 return permissionsArray; 555 } 556 557 private File buildAppIconFile(int sessionId) { 558 return new File(mSessionsDir, "app_icon." + sessionId + ".png"); 559 } 560 561 private void writeSessionsAsync() { 562 IoThread.getHandler().post(new Runnable() { 563 @Override 564 public void run() { 565 synchronized (mSessions) { 566 writeSessionsLocked(); 567 } 568 } 569 }); 570 } 571 572 @Override 573 public int createSession(SessionParams params, String installerPackageName, int userId) { 574 try { 575 return createSessionInternal(params, installerPackageName, userId); 576 } catch (IOException e) { 577 throw ExceptionUtils.wrap(e); 578 } 579 } 580 581 private int createSessionInternal(SessionParams params, String installerPackageName, int userId) 582 throws IOException { 583 final int callingUid = Binder.getCallingUid(); 584 mPm.enforceCrossUserPermission(callingUid, userId, true, true, "createSession"); 585 586 if (mPm.isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 587 throw new SecurityException("User restriction prevents installing"); 588 } 589 590 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 591 params.installFlags |= PackageManager.INSTALL_FROM_ADB; 592 593 } else { 594 mAppOps.checkPackage(callingUid, installerPackageName); 595 596 params.installFlags &= ~PackageManager.INSTALL_FROM_ADB; 597 params.installFlags &= ~PackageManager.INSTALL_ALL_USERS; 598 params.installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 599 } 600 601 // Only system components can circumvent runtime permissions when installing. 602 if ((params.installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 603 && mContext.checkCallingOrSelfPermission(Manifest.permission 604 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 605 throw new SecurityException("You need the " 606 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 607 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 608 } 609 610 // Defensively resize giant app icons 611 if (params.appIcon != null) { 612 final ActivityManager am = (ActivityManager) mContext.getSystemService( 613 Context.ACTIVITY_SERVICE); 614 final int iconSize = am.getLauncherLargeIconSize(); 615 if ((params.appIcon.getWidth() > iconSize * 2) 616 || (params.appIcon.getHeight() > iconSize * 2)) { 617 params.appIcon = Bitmap.createScaledBitmap(params.appIcon, iconSize, iconSize, 618 true); 619 } 620 } 621 622 switch (params.mode) { 623 case SessionParams.MODE_FULL_INSTALL: 624 case SessionParams.MODE_INHERIT_EXISTING: 625 break; 626 default: 627 throw new IllegalArgumentException("Invalid install mode: " + params.mode); 628 } 629 630 // If caller requested explicit location, sanity check it, otherwise 631 // resolve the best internal or adopted location. 632 if ((params.installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 633 if (!PackageHelper.fitsOnInternal(mContext, params.sizeBytes)) { 634 throw new IOException("No suitable internal storage available"); 635 } 636 637 } else if ((params.installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 638 if (!PackageHelper.fitsOnExternal(mContext, params.sizeBytes)) { 639 throw new IOException("No suitable external storage available"); 640 } 641 642 } else if ((params.installFlags & PackageManager.INSTALL_FORCE_VOLUME_UUID) != 0) { 643 // For now, installs to adopted media are treated as internal from 644 // an install flag point-of-view. 645 params.setInstallFlagsInternal(); 646 647 } else { 648 // For now, installs to adopted media are treated as internal from 649 // an install flag point-of-view. 650 params.setInstallFlagsInternal(); 651 652 // Resolve best location for install, based on combination of 653 // requested install flags, delta size, and manifest settings. 654 final long ident = Binder.clearCallingIdentity(); 655 try { 656 params.volumeUuid = PackageHelper.resolveInstallVolume(mContext, 657 params.appPackageName, params.installLocation, params.sizeBytes); 658 } finally { 659 Binder.restoreCallingIdentity(ident); 660 } 661 } 662 663 final int sessionId; 664 final PackageInstallerSession session; 665 synchronized (mSessions) { 666 // Sanity check that installer isn't going crazy 667 final int activeCount = getSessionCount(mSessions, callingUid); 668 if (activeCount >= MAX_ACTIVE_SESSIONS) { 669 throw new IllegalStateException( 670 "Too many active sessions for UID " + callingUid); 671 } 672 final int historicalCount = getSessionCount(mHistoricalSessions, callingUid); 673 if (historicalCount >= MAX_HISTORICAL_SESSIONS) { 674 throw new IllegalStateException( 675 "Too many historical sessions for UID " + callingUid); 676 } 677 678 sessionId = allocateSessionIdLocked(); 679 } 680 681 final long createdMillis = System.currentTimeMillis(); 682 // We're staging to exactly one location 683 File stageDir = null; 684 String stageCid = null; 685 if ((params.installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 686 final boolean isEphemeral = 687 (params.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 688 stageDir = buildStageDir(params.volumeUuid, sessionId, isEphemeral); 689 } else { 690 stageCid = buildExternalStageCid(sessionId); 691 } 692 693 session = new PackageInstallerSession(mInternalCallback, mContext, mPm, 694 mInstallThread.getLooper(), sessionId, userId, installerPackageName, callingUid, 695 params, createdMillis, stageDir, stageCid, false, false); 696 697 synchronized (mSessions) { 698 mSessions.put(sessionId, session); 699 } 700 701 mCallbacks.notifySessionCreated(session.sessionId, session.userId); 702 writeSessionsAsync(); 703 return sessionId; 704 } 705 706 @Override 707 public void updateSessionAppIcon(int sessionId, Bitmap appIcon) { 708 synchronized (mSessions) { 709 final PackageInstallerSession session = mSessions.get(sessionId); 710 if (session == null || !isCallingUidOwner(session)) { 711 throw new SecurityException("Caller has no access to session " + sessionId); 712 } 713 714 // Defensively resize giant app icons 715 if (appIcon != null) { 716 final ActivityManager am = (ActivityManager) mContext.getSystemService( 717 Context.ACTIVITY_SERVICE); 718 final int iconSize = am.getLauncherLargeIconSize(); 719 if ((appIcon.getWidth() > iconSize * 2) 720 || (appIcon.getHeight() > iconSize * 2)) { 721 appIcon = Bitmap.createScaledBitmap(appIcon, iconSize, iconSize, true); 722 } 723 } 724 725 session.params.appIcon = appIcon; 726 session.params.appIconLastModified = -1; 727 728 mInternalCallback.onSessionBadgingChanged(session); 729 } 730 } 731 732 @Override 733 public void updateSessionAppLabel(int sessionId, String appLabel) { 734 synchronized (mSessions) { 735 final PackageInstallerSession session = mSessions.get(sessionId); 736 if (session == null || !isCallingUidOwner(session)) { 737 throw new SecurityException("Caller has no access to session " + sessionId); 738 } 739 session.params.appLabel = appLabel; 740 mInternalCallback.onSessionBadgingChanged(session); 741 } 742 } 743 744 @Override 745 public void abandonSession(int sessionId) { 746 synchronized (mSessions) { 747 final PackageInstallerSession session = mSessions.get(sessionId); 748 if (session == null || !isCallingUidOwner(session)) { 749 throw new SecurityException("Caller has no access to session " + sessionId); 750 } 751 session.abandon(); 752 } 753 } 754 755 @Override 756 public IPackageInstallerSession openSession(int sessionId) { 757 try { 758 return openSessionInternal(sessionId); 759 } catch (IOException e) { 760 throw ExceptionUtils.wrap(e); 761 } 762 } 763 764 private IPackageInstallerSession openSessionInternal(int sessionId) throws IOException { 765 synchronized (mSessions) { 766 final PackageInstallerSession session = mSessions.get(sessionId); 767 if (session == null || !isCallingUidOwner(session)) { 768 throw new SecurityException("Caller has no access to session " + sessionId); 769 } 770 session.open(); 771 return session; 772 } 773 } 774 775 private int allocateSessionIdLocked() { 776 int n = 0; 777 int sessionId; 778 do { 779 sessionId = mRandom.nextInt(Integer.MAX_VALUE - 1) + 1; 780 if (!mAllocatedSessions.get(sessionId, false)) { 781 mAllocatedSessions.put(sessionId, true); 782 return sessionId; 783 } 784 } while (n++ < 32); 785 786 throw new IllegalStateException("Failed to allocate session ID"); 787 } 788 789 private File buildStagingDir(String volumeUuid, boolean isEphemeral) { 790 if (isEphemeral) { 791 return Environment.getDataAppEphemeralDirectory(volumeUuid); 792 } 793 return Environment.getDataAppDirectory(volumeUuid); 794 } 795 796 private File buildStageDir(String volumeUuid, int sessionId, boolean isEphemeral) { 797 final File stagingDir = buildStagingDir(volumeUuid, isEphemeral); 798 return new File(stagingDir, "vmdl" + sessionId + ".tmp"); 799 } 800 801 static void prepareStageDir(File stageDir) throws IOException { 802 if (stageDir.exists()) { 803 throw new IOException("Session dir already exists: " + stageDir); 804 } 805 806 try { 807 Os.mkdir(stageDir.getAbsolutePath(), 0755); 808 Os.chmod(stageDir.getAbsolutePath(), 0755); 809 } catch (ErrnoException e) { 810 // This purposefully throws if directory already exists 811 throw new IOException("Failed to prepare session dir: " + stageDir, e); 812 } 813 814 if (!SELinux.restorecon(stageDir)) { 815 throw new IOException("Failed to restorecon session dir: " + stageDir); 816 } 817 } 818 819 private String buildExternalStageCid(int sessionId) { 820 return "smdl" + sessionId + ".tmp"; 821 } 822 823 static void prepareExternalStageCid(String stageCid, long sizeBytes) throws IOException { 824 if (PackageHelper.createSdDir(sizeBytes, stageCid, PackageManagerService.getEncryptKey(), 825 Process.SYSTEM_UID, true) == null) { 826 throw new IOException("Failed to create session cid: " + stageCid); 827 } 828 } 829 830 @Override 831 public SessionInfo getSessionInfo(int sessionId) { 832 synchronized (mSessions) { 833 final PackageInstallerSession session = mSessions.get(sessionId); 834 return session != null ? session.generateInfo() : null; 835 } 836 } 837 838 @Override 839 public ParceledListSlice<SessionInfo> getAllSessions(int userId) { 840 mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "getAllSessions"); 841 842 final List<SessionInfo> result = new ArrayList<>(); 843 synchronized (mSessions) { 844 for (int i = 0; i < mSessions.size(); i++) { 845 final PackageInstallerSession session = mSessions.valueAt(i); 846 if (session.userId == userId) { 847 result.add(session.generateInfo()); 848 } 849 } 850 } 851 return new ParceledListSlice<>(result); 852 } 853 854 @Override 855 public ParceledListSlice<SessionInfo> getMySessions(String installerPackageName, int userId) { 856 mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "getMySessions"); 857 mAppOps.checkPackage(Binder.getCallingUid(), installerPackageName); 858 859 final List<SessionInfo> result = new ArrayList<>(); 860 synchronized (mSessions) { 861 for (int i = 0; i < mSessions.size(); i++) { 862 final PackageInstallerSession session = mSessions.valueAt(i); 863 if (Objects.equals(session.installerPackageName, installerPackageName) 864 && session.userId == userId) { 865 result.add(session.generateInfo()); 866 } 867 } 868 } 869 return new ParceledListSlice<>(result); 870 } 871 872 @Override 873 public void uninstall(VersionedPackage versionedPackage, String callerPackageName, int flags, 874 IntentSender statusReceiver, int userId) throws RemoteException { 875 final int callingUid = Binder.getCallingUid(); 876 mPm.enforceCrossUserPermission(callingUid, userId, true, true, "uninstall"); 877 if ((callingUid != Process.SHELL_UID) && (callingUid != Process.ROOT_UID)) { 878 mAppOps.checkPackage(callingUid, callerPackageName); 879 } 880 881 // Check whether the caller is device owner, in which case we do it silently. 882 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService( 883 Context.DEVICE_POLICY_SERVICE); 884 boolean isDeviceOwner = (dpm != null) && dpm.isDeviceOwnerAppOnCallingUser( 885 callerPackageName); 886 887 final PackageDeleteObserverAdapter adapter = new PackageDeleteObserverAdapter(mContext, 888 statusReceiver, versionedPackage.getPackageName(), isDeviceOwner, userId); 889 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DELETE_PACKAGES) 890 == PackageManager.PERMISSION_GRANTED) { 891 // Sweet, call straight through! 892 mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags); 893 } else if (isDeviceOwner) { 894 // Allow the DeviceOwner to silently delete packages 895 // Need to clear the calling identity to get DELETE_PACKAGES permission 896 long ident = Binder.clearCallingIdentity(); 897 try { 898 mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags); 899 } finally { 900 Binder.restoreCallingIdentity(ident); 901 } 902 } else { 903 // Take a short detour to confirm with user 904 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 905 intent.setData(Uri.fromParts("package", versionedPackage.getPackageName(), null)); 906 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, adapter.getBinder().asBinder()); 907 adapter.onUserActionRequired(intent); 908 } 909 } 910 911 @Override 912 public void setPermissionsResult(int sessionId, boolean accepted) { 913 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, TAG); 914 915 synchronized (mSessions) { 916 PackageInstallerSession session = mSessions.get(sessionId); 917 if (session != null) { 918 session.setPermissionsResult(accepted); 919 } 920 } 921 } 922 923 @Override 924 public void registerCallback(IPackageInstallerCallback callback, int userId) { 925 mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "registerCallback"); 926 mCallbacks.register(callback, userId); 927 } 928 929 @Override 930 public void unregisterCallback(IPackageInstallerCallback callback) { 931 mCallbacks.unregister(callback); 932 } 933 934 private static int getSessionCount(SparseArray<PackageInstallerSession> sessions, 935 int installerUid) { 936 int count = 0; 937 final int size = sessions.size(); 938 for (int i = 0; i < size; i++) { 939 final PackageInstallerSession session = sessions.valueAt(i); 940 if (session.installerUid == installerUid) { 941 count++; 942 } 943 } 944 return count; 945 } 946 947 private boolean isCallingUidOwner(PackageInstallerSession session) { 948 final int callingUid = Binder.getCallingUid(); 949 if (callingUid == Process.ROOT_UID) { 950 return true; 951 } else { 952 return (session != null) && (callingUid == session.installerUid); 953 } 954 } 955 956 static class PackageDeleteObserverAdapter extends PackageDeleteObserver { 957 private final Context mContext; 958 private final IntentSender mTarget; 959 private final String mPackageName; 960 private final Notification mNotification; 961 962 public PackageDeleteObserverAdapter(Context context, IntentSender target, 963 String packageName, boolean showNotification, int userId) { 964 mContext = context; 965 mTarget = target; 966 mPackageName = packageName; 967 if (showNotification) { 968 mNotification = buildSuccessNotification(mContext, 969 mContext.getResources().getString(R.string.package_deleted_device_owner), 970 packageName, 971 userId); 972 } else { 973 mNotification = null; 974 } 975 } 976 977 @Override 978 public void onUserActionRequired(Intent intent) { 979 final Intent fillIn = new Intent(); 980 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, mPackageName); 981 fillIn.putExtra(PackageInstaller.EXTRA_STATUS, 982 PackageInstaller.STATUS_PENDING_USER_ACTION); 983 fillIn.putExtra(Intent.EXTRA_INTENT, intent); 984 try { 985 mTarget.sendIntent(mContext, 0, fillIn, null, null); 986 } catch (SendIntentException ignored) { 987 } 988 } 989 990 @Override 991 public void onPackageDeleted(String basePackageName, int returnCode, String msg) { 992 if (PackageManager.DELETE_SUCCEEDED == returnCode && mNotification != null) { 993 NotificationManager notificationManager = (NotificationManager) 994 mContext.getSystemService(Context.NOTIFICATION_SERVICE); 995 notificationManager.notify(basePackageName, 0, mNotification); 996 } 997 final Intent fillIn = new Intent(); 998 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, mPackageName); 999 fillIn.putExtra(PackageInstaller.EXTRA_STATUS, 1000 PackageManager.deleteStatusToPublicStatus(returnCode)); 1001 fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE, 1002 PackageManager.deleteStatusToString(returnCode, msg)); 1003 fillIn.putExtra(PackageInstaller.EXTRA_LEGACY_STATUS, returnCode); 1004 try { 1005 mTarget.sendIntent(mContext, 0, fillIn, null, null); 1006 } catch (SendIntentException ignored) { 1007 } 1008 } 1009 } 1010 1011 static class PackageInstallObserverAdapter extends PackageInstallObserver { 1012 private final Context mContext; 1013 private final IntentSender mTarget; 1014 private final int mSessionId; 1015 private final boolean mShowNotification; 1016 private final int mUserId; 1017 1018 public PackageInstallObserverAdapter(Context context, IntentSender target, int sessionId, 1019 boolean showNotification, int userId) { 1020 mContext = context; 1021 mTarget = target; 1022 mSessionId = sessionId; 1023 mShowNotification = showNotification; 1024 mUserId = userId; 1025 } 1026 1027 @Override 1028 public void onUserActionRequired(Intent intent) { 1029 final Intent fillIn = new Intent(); 1030 fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId); 1031 fillIn.putExtra(PackageInstaller.EXTRA_STATUS, 1032 PackageInstaller.STATUS_PENDING_USER_ACTION); 1033 fillIn.putExtra(Intent.EXTRA_INTENT, intent); 1034 try { 1035 mTarget.sendIntent(mContext, 0, fillIn, null, null); 1036 } catch (SendIntentException ignored) { 1037 } 1038 } 1039 1040 @Override 1041 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 1042 Bundle extras) { 1043 if (PackageManager.INSTALL_SUCCEEDED == returnCode && mShowNotification) { 1044 boolean update = (extras != null) && extras.getBoolean(Intent.EXTRA_REPLACING); 1045 Notification notification = buildSuccessNotification(mContext, 1046 mContext.getResources() 1047 .getString(update ? R.string.package_updated_device_owner : 1048 R.string.package_installed_device_owner), 1049 basePackageName, 1050 mUserId); 1051 if (notification != null) { 1052 NotificationManager notificationManager = (NotificationManager) 1053 mContext.getSystemService(Context.NOTIFICATION_SERVICE); 1054 notificationManager.notify(basePackageName, 0, notification); 1055 } 1056 } 1057 final Intent fillIn = new Intent(); 1058 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, basePackageName); 1059 fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId); 1060 fillIn.putExtra(PackageInstaller.EXTRA_STATUS, 1061 PackageManager.installStatusToPublicStatus(returnCode)); 1062 fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE, 1063 PackageManager.installStatusToString(returnCode, msg)); 1064 fillIn.putExtra(PackageInstaller.EXTRA_LEGACY_STATUS, returnCode); 1065 if (extras != null) { 1066 final String existing = extras.getString( 1067 PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE); 1068 if (!TextUtils.isEmpty(existing)) { 1069 fillIn.putExtra(PackageInstaller.EXTRA_OTHER_PACKAGE_NAME, existing); 1070 } 1071 } 1072 try { 1073 mTarget.sendIntent(mContext, 0, fillIn, null, null); 1074 } catch (SendIntentException ignored) { 1075 } 1076 } 1077 } 1078 1079 /** 1080 * Build a notification for package installation / deletion by device owners that is shown if 1081 * the operation succeeds. 1082 */ 1083 private static Notification buildSuccessNotification(Context context, String contentText, 1084 String basePackageName, int userId) { 1085 PackageInfo packageInfo = null; 1086 try { 1087 packageInfo = AppGlobals.getPackageManager().getPackageInfo( 1088 basePackageName, 0, userId); 1089 } catch (RemoteException ignored) { 1090 } 1091 if (packageInfo == null || packageInfo.applicationInfo == null) { 1092 Slog.w(TAG, "Notification not built for package: " + basePackageName); 1093 return null; 1094 } 1095 PackageManager pm = context.getPackageManager(); 1096 Bitmap packageIcon = ImageUtils.buildScaledBitmap( 1097 packageInfo.applicationInfo.loadIcon(pm), 1098 context.getResources().getDimensionPixelSize( 1099 android.R.dimen.notification_large_icon_width), 1100 context.getResources().getDimensionPixelSize( 1101 android.R.dimen.notification_large_icon_height)); 1102 CharSequence packageLabel = packageInfo.applicationInfo.loadLabel(pm); 1103 return new Notification.Builder(context) 1104 .setSmallIcon(R.drawable.ic_check_circle_24px) 1105 .setColor(context.getResources().getColor( 1106 R.color.system_notification_accent_color)) 1107 .setContentTitle(packageLabel) 1108 .setContentText(contentText) 1109 .setStyle(new Notification.BigTextStyle().bigText(contentText)) 1110 .setLargeIcon(packageIcon) 1111 .build(); 1112 } 1113 1114 public static <E> ArraySet<E> newArraySet(E... elements) { 1115 final ArraySet<E> set = new ArraySet<E>(); 1116 if (elements != null) { 1117 set.ensureCapacity(elements.length); 1118 Collections.addAll(set, elements); 1119 } 1120 return set; 1121 } 1122 1123 private static class Callbacks extends Handler { 1124 private static final int MSG_SESSION_CREATED = 1; 1125 private static final int MSG_SESSION_BADGING_CHANGED = 2; 1126 private static final int MSG_SESSION_ACTIVE_CHANGED = 3; 1127 private static final int MSG_SESSION_PROGRESS_CHANGED = 4; 1128 private static final int MSG_SESSION_FINISHED = 5; 1129 1130 private final RemoteCallbackList<IPackageInstallerCallback> 1131 mCallbacks = new RemoteCallbackList<>(); 1132 1133 public Callbacks(Looper looper) { 1134 super(looper); 1135 } 1136 1137 public void register(IPackageInstallerCallback callback, int userId) { 1138 mCallbacks.register(callback, new UserHandle(userId)); 1139 } 1140 1141 public void unregister(IPackageInstallerCallback callback) { 1142 mCallbacks.unregister(callback); 1143 } 1144 1145 @Override 1146 public void handleMessage(Message msg) { 1147 final int userId = msg.arg2; 1148 final int n = mCallbacks.beginBroadcast(); 1149 for (int i = 0; i < n; i++) { 1150 final IPackageInstallerCallback callback = mCallbacks.getBroadcastItem(i); 1151 final UserHandle user = (UserHandle) mCallbacks.getBroadcastCookie(i); 1152 // TODO: dispatch notifications for slave profiles 1153 if (userId == user.getIdentifier()) { 1154 try { 1155 invokeCallback(callback, msg); 1156 } catch (RemoteException ignored) { 1157 } 1158 } 1159 } 1160 mCallbacks.finishBroadcast(); 1161 } 1162 1163 private void invokeCallback(IPackageInstallerCallback callback, Message msg) 1164 throws RemoteException { 1165 final int sessionId = msg.arg1; 1166 switch (msg.what) { 1167 case MSG_SESSION_CREATED: 1168 callback.onSessionCreated(sessionId); 1169 break; 1170 case MSG_SESSION_BADGING_CHANGED: 1171 callback.onSessionBadgingChanged(sessionId); 1172 break; 1173 case MSG_SESSION_ACTIVE_CHANGED: 1174 callback.onSessionActiveChanged(sessionId, (boolean) msg.obj); 1175 break; 1176 case MSG_SESSION_PROGRESS_CHANGED: 1177 callback.onSessionProgressChanged(sessionId, (float) msg.obj); 1178 break; 1179 case MSG_SESSION_FINISHED: 1180 callback.onSessionFinished(sessionId, (boolean) msg.obj); 1181 break; 1182 } 1183 } 1184 1185 private void notifySessionCreated(int sessionId, int userId) { 1186 obtainMessage(MSG_SESSION_CREATED, sessionId, userId).sendToTarget(); 1187 } 1188 1189 private void notifySessionBadgingChanged(int sessionId, int userId) { 1190 obtainMessage(MSG_SESSION_BADGING_CHANGED, sessionId, userId).sendToTarget(); 1191 } 1192 1193 private void notifySessionActiveChanged(int sessionId, int userId, boolean active) { 1194 obtainMessage(MSG_SESSION_ACTIVE_CHANGED, sessionId, userId, active).sendToTarget(); 1195 } 1196 1197 private void notifySessionProgressChanged(int sessionId, int userId, float progress) { 1198 obtainMessage(MSG_SESSION_PROGRESS_CHANGED, sessionId, userId, progress).sendToTarget(); 1199 } 1200 1201 public void notifySessionFinished(int sessionId, int userId, boolean success) { 1202 obtainMessage(MSG_SESSION_FINISHED, sessionId, userId, success).sendToTarget(); 1203 } 1204 } 1205 1206 void dump(IndentingPrintWriter pw) { 1207 synchronized (mSessions) { 1208 pw.println("Active install sessions:"); 1209 pw.increaseIndent(); 1210 int N = mSessions.size(); 1211 for (int i = 0; i < N; i++) { 1212 final PackageInstallerSession session = mSessions.valueAt(i); 1213 session.dump(pw); 1214 pw.println(); 1215 } 1216 pw.println(); 1217 pw.decreaseIndent(); 1218 1219 pw.println("Historical install sessions:"); 1220 pw.increaseIndent(); 1221 N = mHistoricalSessions.size(); 1222 for (int i = 0; i < N; i++) { 1223 final PackageInstallerSession session = mHistoricalSessions.valueAt(i); 1224 session.dump(pw); 1225 pw.println(); 1226 } 1227 pw.println(); 1228 pw.decreaseIndent(); 1229 1230 pw.println("Legacy install sessions:"); 1231 pw.increaseIndent(); 1232 pw.println(mLegacySessions.toString()); 1233 pw.decreaseIndent(); 1234 } 1235 } 1236 1237 class InternalCallback { 1238 public void onSessionBadgingChanged(PackageInstallerSession session) { 1239 mCallbacks.notifySessionBadgingChanged(session.sessionId, session.userId); 1240 writeSessionsAsync(); 1241 } 1242 1243 public void onSessionActiveChanged(PackageInstallerSession session, boolean active) { 1244 mCallbacks.notifySessionActiveChanged(session.sessionId, session.userId, active); 1245 } 1246 1247 public void onSessionProgressChanged(PackageInstallerSession session, float progress) { 1248 mCallbacks.notifySessionProgressChanged(session.sessionId, session.userId, progress); 1249 } 1250 1251 public void onSessionFinished(final PackageInstallerSession session, boolean success) { 1252 mCallbacks.notifySessionFinished(session.sessionId, session.userId, success); 1253 1254 mInstallHandler.post(new Runnable() { 1255 @Override 1256 public void run() { 1257 synchronized (mSessions) { 1258 mSessions.remove(session.sessionId); 1259 mHistoricalSessions.put(session.sessionId, session); 1260 1261 final File appIconFile = buildAppIconFile(session.sessionId); 1262 if (appIconFile.exists()) { 1263 appIconFile.delete(); 1264 } 1265 1266 writeSessionsLocked(); 1267 } 1268 } 1269 }); 1270 } 1271 1272 public void onSessionPrepared(PackageInstallerSession session) { 1273 // We prepared the destination to write into; we want to persist 1274 // this, but it's not critical enough to block for. 1275 writeSessionsAsync(); 1276 } 1277 1278 public void onSessionSealedBlocking(PackageInstallerSession session) { 1279 // It's very important that we block until we've recorded the 1280 // session as being sealed, since we never want to allow mutation 1281 // after sealing. 1282 synchronized (mSessions) { 1283 writeSessionsLocked(); 1284 } 1285 } 1286 } 1287} 1288