PackageInstallerService.java revision 4eb7cea562cd117e598a327ab4d93142589c1ae6
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 /*isInstant*/); 229 reconcileStagesLocked(StorageManager.UUID_PRIVATE_INTERNAL, true /*isInstant*/); 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 /*isInstant*/); 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 isInstant = 687 (params.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 688 stageDir = buildStageDir(params.volumeUuid, sessionId, isInstant); 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 return Environment.getDataAppDirectory(volumeUuid); 791 } 792 793 private File buildStageDir(String volumeUuid, int sessionId, boolean isEphemeral) { 794 final File stagingDir = buildStagingDir(volumeUuid, isEphemeral); 795 return new File(stagingDir, "vmdl" + sessionId + ".tmp"); 796 } 797 798 static void prepareStageDir(File stageDir) throws IOException { 799 if (stageDir.exists()) { 800 throw new IOException("Session dir already exists: " + stageDir); 801 } 802 803 try { 804 Os.mkdir(stageDir.getAbsolutePath(), 0755); 805 Os.chmod(stageDir.getAbsolutePath(), 0755); 806 } catch (ErrnoException e) { 807 // This purposefully throws if directory already exists 808 throw new IOException("Failed to prepare session dir: " + stageDir, e); 809 } 810 811 if (!SELinux.restorecon(stageDir)) { 812 throw new IOException("Failed to restorecon session dir: " + stageDir); 813 } 814 } 815 816 private String buildExternalStageCid(int sessionId) { 817 return "smdl" + sessionId + ".tmp"; 818 } 819 820 static void prepareExternalStageCid(String stageCid, long sizeBytes) throws IOException { 821 if (PackageHelper.createSdDir(sizeBytes, stageCid, PackageManagerService.getEncryptKey(), 822 Process.SYSTEM_UID, true) == null) { 823 throw new IOException("Failed to create session cid: " + stageCid); 824 } 825 } 826 827 @Override 828 public SessionInfo getSessionInfo(int sessionId) { 829 synchronized (mSessions) { 830 final PackageInstallerSession session = mSessions.get(sessionId); 831 return session != null ? session.generateInfo() : null; 832 } 833 } 834 835 @Override 836 public ParceledListSlice<SessionInfo> getAllSessions(int userId) { 837 mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "getAllSessions"); 838 839 final List<SessionInfo> result = new ArrayList<>(); 840 synchronized (mSessions) { 841 for (int i = 0; i < mSessions.size(); i++) { 842 final PackageInstallerSession session = mSessions.valueAt(i); 843 if (session.userId == userId) { 844 result.add(session.generateInfo()); 845 } 846 } 847 } 848 return new ParceledListSlice<>(result); 849 } 850 851 @Override 852 public ParceledListSlice<SessionInfo> getMySessions(String installerPackageName, int userId) { 853 mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "getMySessions"); 854 mAppOps.checkPackage(Binder.getCallingUid(), installerPackageName); 855 856 final List<SessionInfo> result = new ArrayList<>(); 857 synchronized (mSessions) { 858 for (int i = 0; i < mSessions.size(); i++) { 859 final PackageInstallerSession session = mSessions.valueAt(i); 860 if (Objects.equals(session.installerPackageName, installerPackageName) 861 && session.userId == userId) { 862 result.add(session.generateInfo()); 863 } 864 } 865 } 866 return new ParceledListSlice<>(result); 867 } 868 869 @Override 870 public void uninstall(VersionedPackage versionedPackage, String callerPackageName, int flags, 871 IntentSender statusReceiver, int userId) throws RemoteException { 872 final int callingUid = Binder.getCallingUid(); 873 mPm.enforceCrossUserPermission(callingUid, userId, true, true, "uninstall"); 874 if ((callingUid != Process.SHELL_UID) && (callingUid != Process.ROOT_UID)) { 875 mAppOps.checkPackage(callingUid, callerPackageName); 876 } 877 878 // Check whether the caller is device owner, in which case we do it silently. 879 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService( 880 Context.DEVICE_POLICY_SERVICE); 881 boolean isDeviceOwner = (dpm != null) && dpm.isDeviceOwnerAppOnCallingUser( 882 callerPackageName); 883 884 final PackageDeleteObserverAdapter adapter = new PackageDeleteObserverAdapter(mContext, 885 statusReceiver, versionedPackage.getPackageName(), isDeviceOwner, userId); 886 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DELETE_PACKAGES) 887 == PackageManager.PERMISSION_GRANTED) { 888 // Sweet, call straight through! 889 mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags); 890 } else if (isDeviceOwner) { 891 // Allow the DeviceOwner to silently delete packages 892 // Need to clear the calling identity to get DELETE_PACKAGES permission 893 long ident = Binder.clearCallingIdentity(); 894 try { 895 mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags); 896 } finally { 897 Binder.restoreCallingIdentity(ident); 898 } 899 } else { 900 // Take a short detour to confirm with user 901 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 902 intent.setData(Uri.fromParts("package", versionedPackage.getPackageName(), null)); 903 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, adapter.getBinder().asBinder()); 904 adapter.onUserActionRequired(intent); 905 } 906 } 907 908 @Override 909 public void setPermissionsResult(int sessionId, boolean accepted) { 910 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, TAG); 911 912 synchronized (mSessions) { 913 PackageInstallerSession session = mSessions.get(sessionId); 914 if (session != null) { 915 session.setPermissionsResult(accepted); 916 } 917 } 918 } 919 920 @Override 921 public void registerCallback(IPackageInstallerCallback callback, int userId) { 922 mPm.enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "registerCallback"); 923 mCallbacks.register(callback, userId); 924 } 925 926 @Override 927 public void unregisterCallback(IPackageInstallerCallback callback) { 928 mCallbacks.unregister(callback); 929 } 930 931 private static int getSessionCount(SparseArray<PackageInstallerSession> sessions, 932 int installerUid) { 933 int count = 0; 934 final int size = sessions.size(); 935 for (int i = 0; i < size; i++) { 936 final PackageInstallerSession session = sessions.valueAt(i); 937 if (session.installerUid == installerUid) { 938 count++; 939 } 940 } 941 return count; 942 } 943 944 private boolean isCallingUidOwner(PackageInstallerSession session) { 945 final int callingUid = Binder.getCallingUid(); 946 if (callingUid == Process.ROOT_UID) { 947 return true; 948 } else { 949 return (session != null) && (callingUid == session.installerUid); 950 } 951 } 952 953 static class PackageDeleteObserverAdapter extends PackageDeleteObserver { 954 private final Context mContext; 955 private final IntentSender mTarget; 956 private final String mPackageName; 957 private final Notification mNotification; 958 959 public PackageDeleteObserverAdapter(Context context, IntentSender target, 960 String packageName, boolean showNotification, int userId) { 961 mContext = context; 962 mTarget = target; 963 mPackageName = packageName; 964 if (showNotification) { 965 mNotification = buildSuccessNotification(mContext, 966 mContext.getResources().getString(R.string.package_deleted_device_owner), 967 packageName, 968 userId); 969 } else { 970 mNotification = null; 971 } 972 } 973 974 @Override 975 public void onUserActionRequired(Intent intent) { 976 final Intent fillIn = new Intent(); 977 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, mPackageName); 978 fillIn.putExtra(PackageInstaller.EXTRA_STATUS, 979 PackageInstaller.STATUS_PENDING_USER_ACTION); 980 fillIn.putExtra(Intent.EXTRA_INTENT, intent); 981 try { 982 mTarget.sendIntent(mContext, 0, fillIn, null, null); 983 } catch (SendIntentException ignored) { 984 } 985 } 986 987 @Override 988 public void onPackageDeleted(String basePackageName, int returnCode, String msg) { 989 if (PackageManager.DELETE_SUCCEEDED == returnCode && mNotification != null) { 990 NotificationManager notificationManager = (NotificationManager) 991 mContext.getSystemService(Context.NOTIFICATION_SERVICE); 992 notificationManager.notify(basePackageName, 0, mNotification); 993 } 994 final Intent fillIn = new Intent(); 995 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, mPackageName); 996 fillIn.putExtra(PackageInstaller.EXTRA_STATUS, 997 PackageManager.deleteStatusToPublicStatus(returnCode)); 998 fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE, 999 PackageManager.deleteStatusToString(returnCode, msg)); 1000 fillIn.putExtra(PackageInstaller.EXTRA_LEGACY_STATUS, returnCode); 1001 try { 1002 mTarget.sendIntent(mContext, 0, fillIn, null, null); 1003 } catch (SendIntentException ignored) { 1004 } 1005 } 1006 } 1007 1008 static class PackageInstallObserverAdapter extends PackageInstallObserver { 1009 private final Context mContext; 1010 private final IntentSender mTarget; 1011 private final int mSessionId; 1012 private final boolean mShowNotification; 1013 private final int mUserId; 1014 1015 public PackageInstallObserverAdapter(Context context, IntentSender target, int sessionId, 1016 boolean showNotification, int userId) { 1017 mContext = context; 1018 mTarget = target; 1019 mSessionId = sessionId; 1020 mShowNotification = showNotification; 1021 mUserId = userId; 1022 } 1023 1024 @Override 1025 public void onUserActionRequired(Intent intent) { 1026 final Intent fillIn = new Intent(); 1027 fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId); 1028 fillIn.putExtra(PackageInstaller.EXTRA_STATUS, 1029 PackageInstaller.STATUS_PENDING_USER_ACTION); 1030 fillIn.putExtra(Intent.EXTRA_INTENT, intent); 1031 try { 1032 mTarget.sendIntent(mContext, 0, fillIn, null, null); 1033 } catch (SendIntentException ignored) { 1034 } 1035 } 1036 1037 @Override 1038 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 1039 Bundle extras) { 1040 if (PackageManager.INSTALL_SUCCEEDED == returnCode && mShowNotification) { 1041 boolean update = (extras != null) && extras.getBoolean(Intent.EXTRA_REPLACING); 1042 Notification notification = buildSuccessNotification(mContext, 1043 mContext.getResources() 1044 .getString(update ? R.string.package_updated_device_owner : 1045 R.string.package_installed_device_owner), 1046 basePackageName, 1047 mUserId); 1048 if (notification != null) { 1049 NotificationManager notificationManager = (NotificationManager) 1050 mContext.getSystemService(Context.NOTIFICATION_SERVICE); 1051 notificationManager.notify(basePackageName, 0, notification); 1052 } 1053 } 1054 final Intent fillIn = new Intent(); 1055 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, basePackageName); 1056 fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId); 1057 fillIn.putExtra(PackageInstaller.EXTRA_STATUS, 1058 PackageManager.installStatusToPublicStatus(returnCode)); 1059 fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE, 1060 PackageManager.installStatusToString(returnCode, msg)); 1061 fillIn.putExtra(PackageInstaller.EXTRA_LEGACY_STATUS, returnCode); 1062 if (extras != null) { 1063 final String existing = extras.getString( 1064 PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE); 1065 if (!TextUtils.isEmpty(existing)) { 1066 fillIn.putExtra(PackageInstaller.EXTRA_OTHER_PACKAGE_NAME, existing); 1067 } 1068 } 1069 try { 1070 mTarget.sendIntent(mContext, 0, fillIn, null, null); 1071 } catch (SendIntentException ignored) { 1072 } 1073 } 1074 } 1075 1076 /** 1077 * Build a notification for package installation / deletion by device owners that is shown if 1078 * the operation succeeds. 1079 */ 1080 private static Notification buildSuccessNotification(Context context, String contentText, 1081 String basePackageName, int userId) { 1082 PackageInfo packageInfo = null; 1083 try { 1084 packageInfo = AppGlobals.getPackageManager().getPackageInfo( 1085 basePackageName, 0, userId); 1086 } catch (RemoteException ignored) { 1087 } 1088 if (packageInfo == null || packageInfo.applicationInfo == null) { 1089 Slog.w(TAG, "Notification not built for package: " + basePackageName); 1090 return null; 1091 } 1092 PackageManager pm = context.getPackageManager(); 1093 Bitmap packageIcon = ImageUtils.buildScaledBitmap( 1094 packageInfo.applicationInfo.loadIcon(pm), 1095 context.getResources().getDimensionPixelSize( 1096 android.R.dimen.notification_large_icon_width), 1097 context.getResources().getDimensionPixelSize( 1098 android.R.dimen.notification_large_icon_height)); 1099 CharSequence packageLabel = packageInfo.applicationInfo.loadLabel(pm); 1100 return new Notification.Builder(context) 1101 .setSmallIcon(R.drawable.ic_check_circle_24px) 1102 .setColor(context.getResources().getColor( 1103 R.color.system_notification_accent_color)) 1104 .setContentTitle(packageLabel) 1105 .setContentText(contentText) 1106 .setStyle(new Notification.BigTextStyle().bigText(contentText)) 1107 .setLargeIcon(packageIcon) 1108 .build(); 1109 } 1110 1111 public static <E> ArraySet<E> newArraySet(E... elements) { 1112 final ArraySet<E> set = new ArraySet<E>(); 1113 if (elements != null) { 1114 set.ensureCapacity(elements.length); 1115 Collections.addAll(set, elements); 1116 } 1117 return set; 1118 } 1119 1120 private static class Callbacks extends Handler { 1121 private static final int MSG_SESSION_CREATED = 1; 1122 private static final int MSG_SESSION_BADGING_CHANGED = 2; 1123 private static final int MSG_SESSION_ACTIVE_CHANGED = 3; 1124 private static final int MSG_SESSION_PROGRESS_CHANGED = 4; 1125 private static final int MSG_SESSION_FINISHED = 5; 1126 1127 private final RemoteCallbackList<IPackageInstallerCallback> 1128 mCallbacks = new RemoteCallbackList<>(); 1129 1130 public Callbacks(Looper looper) { 1131 super(looper); 1132 } 1133 1134 public void register(IPackageInstallerCallback callback, int userId) { 1135 mCallbacks.register(callback, new UserHandle(userId)); 1136 } 1137 1138 public void unregister(IPackageInstallerCallback callback) { 1139 mCallbacks.unregister(callback); 1140 } 1141 1142 @Override 1143 public void handleMessage(Message msg) { 1144 final int userId = msg.arg2; 1145 final int n = mCallbacks.beginBroadcast(); 1146 for (int i = 0; i < n; i++) { 1147 final IPackageInstallerCallback callback = mCallbacks.getBroadcastItem(i); 1148 final UserHandle user = (UserHandle) mCallbacks.getBroadcastCookie(i); 1149 // TODO: dispatch notifications for slave profiles 1150 if (userId == user.getIdentifier()) { 1151 try { 1152 invokeCallback(callback, msg); 1153 } catch (RemoteException ignored) { 1154 } 1155 } 1156 } 1157 mCallbacks.finishBroadcast(); 1158 } 1159 1160 private void invokeCallback(IPackageInstallerCallback callback, Message msg) 1161 throws RemoteException { 1162 final int sessionId = msg.arg1; 1163 switch (msg.what) { 1164 case MSG_SESSION_CREATED: 1165 callback.onSessionCreated(sessionId); 1166 break; 1167 case MSG_SESSION_BADGING_CHANGED: 1168 callback.onSessionBadgingChanged(sessionId); 1169 break; 1170 case MSG_SESSION_ACTIVE_CHANGED: 1171 callback.onSessionActiveChanged(sessionId, (boolean) msg.obj); 1172 break; 1173 case MSG_SESSION_PROGRESS_CHANGED: 1174 callback.onSessionProgressChanged(sessionId, (float) msg.obj); 1175 break; 1176 case MSG_SESSION_FINISHED: 1177 callback.onSessionFinished(sessionId, (boolean) msg.obj); 1178 break; 1179 } 1180 } 1181 1182 private void notifySessionCreated(int sessionId, int userId) { 1183 obtainMessage(MSG_SESSION_CREATED, sessionId, userId).sendToTarget(); 1184 } 1185 1186 private void notifySessionBadgingChanged(int sessionId, int userId) { 1187 obtainMessage(MSG_SESSION_BADGING_CHANGED, sessionId, userId).sendToTarget(); 1188 } 1189 1190 private void notifySessionActiveChanged(int sessionId, int userId, boolean active) { 1191 obtainMessage(MSG_SESSION_ACTIVE_CHANGED, sessionId, userId, active).sendToTarget(); 1192 } 1193 1194 private void notifySessionProgressChanged(int sessionId, int userId, float progress) { 1195 obtainMessage(MSG_SESSION_PROGRESS_CHANGED, sessionId, userId, progress).sendToTarget(); 1196 } 1197 1198 public void notifySessionFinished(int sessionId, int userId, boolean success) { 1199 obtainMessage(MSG_SESSION_FINISHED, sessionId, userId, success).sendToTarget(); 1200 } 1201 } 1202 1203 void dump(IndentingPrintWriter pw) { 1204 synchronized (mSessions) { 1205 pw.println("Active install sessions:"); 1206 pw.increaseIndent(); 1207 int N = mSessions.size(); 1208 for (int i = 0; i < N; i++) { 1209 final PackageInstallerSession session = mSessions.valueAt(i); 1210 session.dump(pw); 1211 pw.println(); 1212 } 1213 pw.println(); 1214 pw.decreaseIndent(); 1215 1216 pw.println("Historical install sessions:"); 1217 pw.increaseIndent(); 1218 N = mHistoricalSessions.size(); 1219 for (int i = 0; i < N; i++) { 1220 final PackageInstallerSession session = mHistoricalSessions.valueAt(i); 1221 session.dump(pw); 1222 pw.println(); 1223 } 1224 pw.println(); 1225 pw.decreaseIndent(); 1226 1227 pw.println("Legacy install sessions:"); 1228 pw.increaseIndent(); 1229 pw.println(mLegacySessions.toString()); 1230 pw.decreaseIndent(); 1231 } 1232 } 1233 1234 class InternalCallback { 1235 public void onSessionBadgingChanged(PackageInstallerSession session) { 1236 mCallbacks.notifySessionBadgingChanged(session.sessionId, session.userId); 1237 writeSessionsAsync(); 1238 } 1239 1240 public void onSessionActiveChanged(PackageInstallerSession session, boolean active) { 1241 mCallbacks.notifySessionActiveChanged(session.sessionId, session.userId, active); 1242 } 1243 1244 public void onSessionProgressChanged(PackageInstallerSession session, float progress) { 1245 mCallbacks.notifySessionProgressChanged(session.sessionId, session.userId, progress); 1246 } 1247 1248 public void onSessionFinished(final PackageInstallerSession session, boolean success) { 1249 mCallbacks.notifySessionFinished(session.sessionId, session.userId, success); 1250 1251 mInstallHandler.post(new Runnable() { 1252 @Override 1253 public void run() { 1254 synchronized (mSessions) { 1255 mSessions.remove(session.sessionId); 1256 mHistoricalSessions.put(session.sessionId, session); 1257 1258 final File appIconFile = buildAppIconFile(session.sessionId); 1259 if (appIconFile.exists()) { 1260 appIconFile.delete(); 1261 } 1262 1263 writeSessionsLocked(); 1264 } 1265 } 1266 }); 1267 } 1268 1269 public void onSessionPrepared(PackageInstallerSession session) { 1270 // We prepared the destination to write into; we want to persist 1271 // this, but it's not critical enough to block for. 1272 writeSessionsAsync(); 1273 } 1274 1275 public void onSessionSealedBlocking(PackageInstallerSession session) { 1276 // It's very important that we block until we've recorded the 1277 // session as being sealed, since we never want to allow mutation 1278 // after sealing. 1279 synchronized (mSessions) { 1280 writeSessionsLocked(); 1281 } 1282 } 1283 } 1284} 1285