blob: 7f48970b445a4fb37ed4cf18d4d3d16c40594db3 [file] [log] [blame]
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -07001/*
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
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070019import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
20import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070021
Svetoslav805b63e2015-04-09 17:28:54 -070022import android.Manifest;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070023import android.app.ActivityManager;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +000024import android.app.AppGlobals;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070025import android.app.AppOpsManager;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +000026import android.app.Notification;
27import android.app.NotificationManager;
Jeff Sharkeya0907432014-08-15 10:23:11 -070028import android.app.PackageDeleteObserver;
29import android.app.PackageInstallObserver;
Rubin Xu8b17ad02019-03-07 17:42:37 +000030import android.app.admin.DevicePolicyEventLogger;
Benjamin Franzdabae882017-08-08 12:33:19 +010031import android.app.admin.DevicePolicyManagerInternal;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070032import android.content.Context;
Jeff Sharkeyf0600952014-08-07 17:31:53 -070033import android.content.Intent;
Jeff Sharkeya0907432014-08-15 10:23:11 -070034import android.content.IntentSender;
35import android.content.IntentSender.SendIntentException;
Philip P. Moltmannd9bb39a2017-09-05 12:41:15 -070036import android.content.pm.ApplicationInfo;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070037import android.content.pm.IPackageInstaller;
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -070038import android.content.pm.IPackageInstallerCallback;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070039import android.content.pm.IPackageInstallerSession;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +000040import android.content.pm.PackageInfo;
Jeff Sharkeyf0600952014-08-07 17:31:53 -070041import android.content.pm.PackageInstaller;
Jeff Sharkeya0907432014-08-15 10:23:11 -070042import android.content.pm.PackageInstaller.SessionInfo;
43import android.content.pm.PackageInstaller.SessionParams;
Jeff Sharkeyec9bad22014-09-05 09:45:20 -070044import android.content.pm.PackageManager;
Jeff Sharkey97d47ed2014-10-15 09:19:47 -070045import android.content.pm.ParceledListSlice;
Svet Ganov67882122016-12-11 16:36:34 -080046import android.content.pm.VersionedPackage;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070047import android.graphics.Bitmap;
Jeff Sharkeyf0600952014-08-07 17:31:53 -070048import android.net.Uri;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070049import android.os.Binder;
Philip P. Moltmannd9bb39a2017-09-05 12:41:15 -070050import android.os.Build;
Jeff Sharkeya0907432014-08-15 10:23:11 -070051import android.os.Bundle;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070052import android.os.Environment;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070053import android.os.Handler;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070054import android.os.HandlerThread;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070055import android.os.Looper;
56import android.os.Message;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070057import android.os.Process;
Jeff Sharkeya1031142014-07-12 18:09:46 -070058import android.os.RemoteCallbackList;
59import android.os.RemoteException;
Jeff Sharkeyec55ef02014-07-08 11:28:00 -070060import android.os.SELinux;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070061import android.os.UserManager;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -070062import android.os.storage.StorageManager;
Rubin Xu8b17ad02019-03-07 17:42:37 +000063import android.stats.devicepolicy.DevicePolicyEnums;
Jeff Sharkeyec55ef02014-07-08 11:28:00 -070064import android.system.ErrnoException;
65import android.system.Os;
Jeff Sharkeya0907432014-08-15 10:23:11 -070066import android.text.TextUtils;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070067import android.text.format.DateUtils;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070068import android.util.ArraySet;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070069import android.util.AtomicFile;
Jeff Sharkeya1031142014-07-12 18:09:46 -070070import android.util.ExceptionUtils;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070071import android.util.Slog;
72import android.util.SparseArray;
Jeff Sharkey742e7902014-08-16 19:09:13 -070073import android.util.SparseBooleanArray;
Narayan Kamatha22a7662017-06-12 13:34:29 +010074import android.util.SparseIntArray;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070075import android.util.Xml;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070076
Benjamin Franz39fb7fd2015-02-18 16:11:18 +000077import com.android.internal.R;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070078import com.android.internal.annotations.GuardedBy;
Jeff Sharkey742e7902014-08-16 19:09:13 -070079import com.android.internal.content.PackageHelper;
Chris Wren282cfef2017-03-27 15:01:44 -040080import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050081import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070082import com.android.internal.util.FastXmlSerializer;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +000083import com.android.internal.util.ImageUtils;
Jeff Sharkeya1031142014-07-12 18:09:46 -070084import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070085import com.android.server.IoThread;
Todd Kennedy0eb97382017-10-03 16:57:22 -070086import com.android.server.LocalServices;
Philip P. Moltmann48456672019-01-20 13:14:03 -080087import com.android.server.pm.permission.PermissionManagerServiceInternal;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070088
Philip P. Moltmann7460c592017-08-08 20:07:11 +000089import libcore.io.IoUtils;
90
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070091import org.xmlpull.v1.XmlPullParser;
92import org.xmlpull.v1.XmlPullParserException;
93import org.xmlpull.v1.XmlSerializer;
94
Philip P. Moltmann7460c592017-08-08 20:07:11 +000095import java.io.CharArrayWriter;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -070096import java.io.File;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070097import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700100import java.io.FilenameFilter;
101import java.io.IOException;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100102import java.nio.charset.StandardCharsets;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700103import java.security.SecureRandom;
Jeff Sharkeybb580672014-07-10 12:10:25 -0700104import java.util.ArrayList;
Jeff Sharkey54d42be2015-07-20 16:36:55 -0700105import java.util.Collections;
Jeff Sharkeybb580672014-07-10 12:10:25 -0700106import java.util.List;
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700107import java.util.Objects;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700108import java.util.Random;
Jon Miranda2b340a22019-01-25 14:03:49 -0800109import java.util.function.IntPredicate;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700110
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000111/** The service responsible for installing packages. */
112public class PackageInstallerService extends IPackageInstaller.Stub implements
113 PackageSessionProvider {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700114 private static final String TAG = "PackageInstaller";
Jeff Sharkeye9808042014-09-11 21:15:37 -0700115 private static final boolean LOGD = false;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700116
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700117 // TODO: remove outstanding sessions when installer package goes away
Jeff Sharkey6c833e02014-07-14 22:44:30 -0700118 // TODO: notify listeners in other users when package has been installed there
Jeff Sharkey742e7902014-08-16 19:09:13 -0700119 // TODO: purge expired sessions periodically in addition to at reboot
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700120
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700121 /** XML constants used in {@link #mSessionsFile} */
122 private static final String TAG_SESSIONS = "sessions";
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700123
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700124 /** Automatically destroy sessions older than this */
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700125 private static final long MAX_AGE_MILLIS = 3 * DateUtils.DAY_IN_MILLIS;
Gavin Corkeryd8311212019-02-22 17:52:30 +0000126 /** Automatically destroy staged sessions that have not changed state in this time */
127 private static final long MAX_TIME_SINCE_UPDATE_MILLIS = 7 * DateUtils.DAY_IN_MILLIS;
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700128 /** Upper bound on number of active sessions for a UID */
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700129 private static final long MAX_ACTIVE_SESSIONS = 1024;
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700130 /** Upper bound on number of historical sessions for a UID */
131 private static final long MAX_HISTORICAL_SESSIONS = 1048576;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700132
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700133 private final Context mContext;
134 private final PackageManagerService mPm;
Dario Freni83620602019-02-18 14:30:57 +0000135 private final ApexManager mApexManager;
Dario Frenibe98c3f2018-12-22 15:25:27 +0000136 private final StagingManager mStagingManager;
Philip P. Moltmann48456672019-01-20 13:14:03 -0800137 private final PermissionManagerServiceInternal mPermissionManager;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700138
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700139 private AppOpsManager mAppOps;
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700140
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700141 private final HandlerThread mInstallThread;
Jeff Sharkeycbf47912014-09-12 09:55:32 -0700142 private final Handler mInstallHandler;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700143
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700144 private final Callbacks mCallbacks;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700145
Dario Freni14f885b2019-02-25 12:48:47 +0000146 private volatile boolean mOkToSendBroadcasts = false;
Dario Freni9694b802019-01-27 23:26:06 +0000147
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700148 /**
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700149 * File storing persisted {@link #mSessions} metadata.
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700150 */
151 private final AtomicFile mSessionsFile;
152
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700153 /**
154 * Directory storing persisted {@link #mSessions} metadata which is too
155 * heavy to store directly in {@link #mSessionsFile}.
156 */
157 private final File mSessionsDir;
158
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700159 private final InternalCallback mInternalCallback = new InternalCallback();
160
161 /**
162 * Used for generating session IDs. Since this is created at boot time,
163 * normal random might be predictable.
164 */
165 private final Random mRandom = new SecureRandom();
166
Todd Kennedy28c4e802016-07-13 13:20:30 -0700167 /** All sessions allocated */
168 @GuardedBy("mSessions")
169 private final SparseBooleanArray mAllocatedSessions = new SparseBooleanArray();
170
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700171 @GuardedBy("mSessions")
172 private final SparseArray<PackageInstallerSession> mSessions = new SparseArray<>();
173
Jeff Sharkey9a445772014-07-16 11:32:08 -0700174 /** Historical sessions kept around for debugging purposes */
175 @GuardedBy("mSessions")
Narayan Kamatha22a7662017-06-12 13:34:29 +0100176 private final List<String> mHistoricalSessions = new ArrayList<>();
177
178 @GuardedBy("mSessions")
179 private final SparseIntArray mHistoricalSessionsByInstaller = new SparseIntArray();
Jeff Sharkey9a445772014-07-16 11:32:08 -0700180
Jeff Sharkey742e7902014-08-16 19:09:13 -0700181 /** Sessions allocated to legacy users */
182 @GuardedBy("mSessions")
183 private final SparseBooleanArray mLegacySessions = new SparseBooleanArray();
184
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700185 private static final FilenameFilter sStageFilter = new FilenameFilter() {
186 @Override
187 public boolean accept(File dir, String name) {
Jeff Sharkey742e7902014-08-16 19:09:13 -0700188 return isStageName(name);
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700189 }
190 };
191
Dario Freni2e8dffc2019-02-06 14:55:16 +0000192 public PackageInstallerService(Context context, PackageManagerService pm, ApexManager am) {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700193 mContext = context;
194 mPm = pm;
Philip P. Moltmann48456672019-01-20 13:14:03 -0800195 mPermissionManager = LocalServices.getService(PermissionManagerServiceInternal.class);
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700196
197 mInstallThread = new HandlerThread(TAG);
198 mInstallThread.start();
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700199
Jeff Sharkeycbf47912014-09-12 09:55:32 -0700200 mInstallHandler = new Handler(mInstallThread.getLooper());
201
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700202 mCallbacks = new Callbacks(mInstallThread.getLooper());
203
204 mSessionsFile = new AtomicFile(
Dianne Hackborne17b4452018-01-10 13:15:40 -0800205 new File(Environment.getDataSystemDirectory(), "install_sessions.xml"),
206 "package-session");
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700207 mSessionsDir = new File(Environment.getDataSystemDirectory(), "install_sessions");
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700208 mSessionsDir.mkdirs();
Dario Frenibe98c3f2018-12-22 15:25:27 +0000209
Dario Freni83620602019-02-18 14:30:57 +0000210 mApexManager = am;
Nikita Ioffe39a6a5b2019-02-26 15:36:39 +0000211
Nikita Ioffe1a7965e2019-03-12 22:32:41 +0000212 mStagingManager = new StagingManager(this, am, context);
Tony Mak606f8e72017-02-15 18:40:03 +0000213 }
214
Dario Freni14f885b2019-02-25 12:48:47 +0000215 boolean okToSendBroadcasts() {
216 return mOkToSendBroadcasts;
Dario Freni4b572c02019-01-29 09:40:31 +0000217 }
218
Tony Mak606f8e72017-02-15 18:40:03 +0000219 public void systemReady() {
220 mAppOps = mContext.getSystemService(AppOpsManager.class);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700221
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700222 synchronized (mSessions) {
223 readSessionsLocked();
224
Dario Frenia8f4b132018-12-30 00:36:49 +0000225 reconcileStagesLocked(StorageManager.UUID_PRIVATE_INTERNAL);
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700226
Jeff Sharkey54d42be2015-07-20 16:36:55 -0700227 final ArraySet<File> unclaimedIcons = newArraySet(
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700228 mSessionsDir.listFiles());
Jeff Sharkey742e7902014-08-16 19:09:13 -0700229
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700230 // Ignore stages and icons claimed by active sessions
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700231 for (int i = 0; i < mSessions.size(); i++) {
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700232 final PackageInstallerSession session = mSessions.valueAt(i);
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700233 unclaimedIcons.remove(buildAppIconFile(session.sessionId));
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700234 }
Jeff Sharkey742e7902014-08-16 19:09:13 -0700235
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700236 // Clean up orphaned icons
237 for (File icon : unclaimedIcons) {
238 Slog.w(TAG, "Deleting orphan icon " + icon);
239 icon.delete();
240 }
Dario Freni0180d0b2019-01-11 21:08:13 +0000241
242 // Invalid sessions might have been marked while parsing. Re-write the database with
243 // the updated information.
244 writeSessionsLocked();
245
Dario Freni4b572c02019-01-29 09:40:31 +0000246 }
247 }
248
249 void restoreAndApplyStagedSessionIfNeeded() {
250 List<PackageInstallerSession> stagedSessionsToRestore = new ArrayList<>();
251 synchronized (mSessions) {
Dario Freni0180d0b2019-01-11 21:08:13 +0000252 for (int i = 0; i < mSessions.size(); i++) {
253 final PackageInstallerSession session = mSessions.valueAt(i);
254 if (session.isStaged()) {
Dario Freni4b572c02019-01-29 09:40:31 +0000255 stagedSessionsToRestore.add(session);
Dario Freni0180d0b2019-01-11 21:08:13 +0000256 }
257 }
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700258 }
Dario Freni4b572c02019-01-29 09:40:31 +0000259 // Don't hold mSessions lock when calling restoreSession, since it might trigger an APK
260 // atomic install which needs to query sessions, which requires lock on mSessions.
261 for (PackageInstallerSession session : stagedSessionsToRestore) {
262 mStagingManager.restoreSession(session);
263 }
Dario Freni14f885b2019-02-25 12:48:47 +0000264 // Broadcasts are not sent while we restore sessions on boot, since no processes would be
265 // ready to listen to them. From now on, we greedily assume that broadcasts requests are
266 // safe to send out. The worst that can happen is that a broadcast is attempted before
267 // ActivityManagerService completes its own systemReady(), in which case it will be rejected
268 // with an otherwise harmless exception.
269 // A more appropriate way to do this would be to wait until the correct boot phase is
270 // reached, but since we are not a SystemService we can't override onBootPhase.
271 // Waiting on the BOOT_COMPLETED broadcast can take several minutes, so that's not a viable
272 // way either.
273 mOkToSendBroadcasts = true;
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700274 }
275
Andreas Gampea36dc622018-02-05 17:19:22 -0800276 @GuardedBy("mSessions")
Dario Frenia8f4b132018-12-30 00:36:49 +0000277 private void reconcileStagesLocked(String volumeUuid) {
278 final File stagingDir = getTmpSessionDir(volumeUuid);
Jeff Sharkey54d42be2015-07-20 16:36:55 -0700279 final ArraySet<File> unclaimedStages = newArraySet(
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700280 stagingDir.listFiles(sStageFilter));
281
282 // Ignore stages claimed by active sessions
283 for (int i = 0; i < mSessions.size(); i++) {
284 final PackageInstallerSession session = mSessions.valueAt(i);
285 unclaimedStages.remove(session.stageDir);
286 }
287
288 // Clean up orphaned staging directories
289 for (File stage : unclaimedStages) {
290 Slog.w(TAG, "Deleting orphan stage " + stage);
291 synchronized (mPm.mInstallLock) {
Jeff Sharkeyfdeeeea2016-01-11 17:34:24 -0700292 mPm.removeCodePathLI(stage);
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700293 }
294 }
295 }
296
297 public void onPrivateVolumeMounted(String volumeUuid) {
298 synchronized (mSessions) {
Dario Frenia8f4b132018-12-30 00:36:49 +0000299 reconcileStagesLocked(volumeUuid);
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700300 }
301 }
302
Jeff Sharkey742e7902014-08-16 19:09:13 -0700303 public static boolean isStageName(String name) {
304 final boolean isFile = name.startsWith("vmdl") && name.endsWith(".tmp");
305 final boolean isContainer = name.startsWith("smdl") && name.endsWith(".tmp");
306 final boolean isLegacyContainer = name.startsWith("smdl2tmp");
307 return isFile || isContainer || isLegacyContainer;
Jeff Sharkey7328a1b2014-08-07 14:01:43 -0700308 }
309
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700310 @Deprecated
Todd Kennedy2699f062015-11-20 13:07:17 -0800311 public File allocateStageDirLegacy(String volumeUuid, boolean isEphemeral) throws IOException {
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700312 synchronized (mSessions) {
313 try {
314 final int sessionId = allocateSessionIdLocked();
Jeff Sharkey742e7902014-08-16 19:09:13 -0700315 mLegacySessions.put(sessionId, true);
Dario Frenia8f4b132018-12-30 00:36:49 +0000316 final File sessionStageDir = buildTmpSessionDir(sessionId, volumeUuid);
317 prepareStageDir(sessionStageDir);
318 return sessionStageDir;
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700319 } catch (IllegalStateException e) {
320 throw new IOException(e);
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700321 }
322 }
323 }
324
Jeff Sharkey742e7902014-08-16 19:09:13 -0700325 @Deprecated
326 public String allocateExternalStageCidLegacy() {
327 synchronized (mSessions) {
328 final int sessionId = allocateSessionIdLocked();
329 mLegacySessions.put(sessionId, true);
330 return "smdl" + sessionId + ".tmp";
331 }
332 }
333
Andreas Gampea36dc622018-02-05 17:19:22 -0800334 @GuardedBy("mSessions")
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700335 private void readSessionsLocked() {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700336 if (LOGD) Slog.v(TAG, "readSessionsLocked()");
337
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700338 mSessions.clear();
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700339
340 FileInputStream fis = null;
341 try {
342 fis = mSessionsFile.openRead();
343 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100344 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700345
346 int type;
347 while ((type = in.next()) != END_DOCUMENT) {
348 if (type == START_TAG) {
349 final String tag = in.getName();
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000350 if (PackageInstallerSession.TAG_SESSION.equals(tag)) {
Philip P. Moltmann37dd1ba2017-09-08 09:46:22 -0700351 final PackageInstallerSession session;
352 try {
353 session = PackageInstallerSession.readFromXml(in, mInternalCallback,
Dario Frenibe98c3f2018-12-22 15:25:27 +0000354 mContext, mPm, mInstallThread.getLooper(), mStagingManager,
355 mSessionsDir, this);
Philip P. Moltmann37dd1ba2017-09-08 09:46:22 -0700356 } catch (Exception e) {
357 Slog.e(TAG, "Could not read session", e);
358 continue;
359 }
360
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700361 final long age = System.currentTimeMillis() - session.createdMillis;
Gavin Corkeryd8311212019-02-22 17:52:30 +0000362 final long timeSinceUpdate =
Gavin Corkery13f81612019-03-20 18:22:58 +0000363 System.currentTimeMillis() - session.getUpdatedMillis();
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700364 final boolean valid;
Gavin Corkeryd8311212019-02-22 17:52:30 +0000365 if (session.isStaged()) {
366 if (timeSinceUpdate >= MAX_TIME_SINCE_UPDATE_MILLIS
367 && session.isStagedAndInTerminalState()) {
368 valid = false;
369 } else {
370 valid = true;
371 }
372 } else if (age >= MAX_AGE_MILLIS) {
373 Slog.w(TAG, "Abandoning old session created at "
374 + session.createdMillis);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700375 valid = false;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700376 } else {
377 valid = true;
378 }
379
380 if (valid) {
381 mSessions.put(session.sessionId, session);
382 } else {
383 // Since this is early during boot we don't send
384 // any observer events about the session, but we
385 // keep details around for dumpsys.
Narayan Kamatha22a7662017-06-12 13:34:29 +0100386 addHistoricalSessionLocked(session);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700387 }
Todd Kennedy28c4e802016-07-13 13:20:30 -0700388 mAllocatedSessions.put(session.sessionId, true);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700389 }
390 }
391 }
392 } catch (FileNotFoundException e) {
393 // Missing sessions are okay, probably first boot
Svet Ganov7121e182015-07-13 22:38:12 -0700394 } catch (IOException | XmlPullParserException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -0700395 Slog.wtf(TAG, "Failed reading install sessions", e);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700396 } finally {
397 IoUtils.closeQuietly(fis);
398 }
shafik43f1af92019-03-14 15:14:00 +0000399 // After all of the sessions were loaded, they are ready to be sealed and validated
400 for (int i = 0; i < mSessions.size(); ++i) {
401 PackageInstallerSession session = mSessions.valueAt(i);
402 session.sealAndValidateIfNecessary();
403 }
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700404 }
405
Andreas Gampea36dc622018-02-05 17:19:22 -0800406 @GuardedBy("mSessions")
Narayan Kamatha22a7662017-06-12 13:34:29 +0100407 private void addHistoricalSessionLocked(PackageInstallerSession session) {
408 CharArrayWriter writer = new CharArrayWriter();
409 IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
410 session.dump(pw);
411 mHistoricalSessions.add(writer.toString());
412
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000413 int installerUid = session.getInstallerUid();
Narayan Kamatha22a7662017-06-12 13:34:29 +0100414 // Increment the number of sessions by this installerUid.
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000415 mHistoricalSessionsByInstaller.put(installerUid,
416 mHistoricalSessionsByInstaller.get(installerUid) + 1);
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700417 }
418
Andreas Gampea36dc622018-02-05 17:19:22 -0800419 @GuardedBy("mSessions")
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700420 private void writeSessionsLocked() {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700421 if (LOGD) Slog.v(TAG, "writeSessionsLocked()");
422
423 FileOutputStream fos = null;
424 try {
425 fos = mSessionsFile.startWrite();
426
427 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100428 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700429 out.startDocument(null, true);
430 out.startTag(null, TAG_SESSIONS);
431 final int size = mSessions.size();
432 for (int i = 0; i < size; i++) {
433 final PackageInstallerSession session = mSessions.valueAt(i);
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000434 session.write(out, mSessionsDir);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700435 }
436 out.endTag(null, TAG_SESSIONS);
437 out.endDocument();
438
439 mSessionsFile.finishWrite(fos);
440 } catch (IOException e) {
441 if (fos != null) {
442 mSessionsFile.failWrite(fos);
443 }
444 }
445 }
446
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700447 private File buildAppIconFile(int sessionId) {
448 return new File(mSessionsDir, "app_icon." + sessionId + ".png");
449 }
450
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700451 private void writeSessionsAsync() {
452 IoThread.getHandler().post(new Runnable() {
453 @Override
454 public void run() {
455 synchronized (mSessions) {
456 writeSessionsLocked();
457 }
458 }
459 });
460 }
461
462 @Override
Jeff Sharkeya0907432014-08-15 10:23:11 -0700463 public int createSession(SessionParams params, String installerPackageName, int userId) {
Jeff Sharkey742e7902014-08-16 19:09:13 -0700464 try {
465 return createSessionInternal(params, installerPackageName, userId);
466 } catch (IOException e) {
467 throw ExceptionUtils.wrap(e);
468 }
469 }
470
471 private int createSessionInternal(SessionParams params, String installerPackageName, int userId)
472 throws IOException {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700473 final int callingUid = Binder.getCallingUid();
Todd Kennedy0eb97382017-10-03 16:57:22 -0700474 mPermissionManager.enforceCrossUserPermission(
475 callingUid, userId, true, true, "createSession");
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700476
Jeff Sharkeye9808042014-09-11 21:15:37 -0700477 if (mPm.isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700478 throw new SecurityException("User restriction prevents installing");
479 }
480
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700481 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
Jeff Sharkeye9808042014-09-11 21:15:37 -0700482 params.installFlags |= PackageManager.INSTALL_FROM_ADB;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700483
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700484 } else {
Philip P. Moltmann79c238a2017-12-13 15:59:07 -0800485 // Only apps with INSTALL_PACKAGES are allowed to set an installer that is not the
486 // caller.
487 if (mContext.checkCallingOrSelfPermission(Manifest.permission.INSTALL_PACKAGES) !=
488 PackageManager.PERMISSION_GRANTED) {
489 mAppOps.checkPackage(callingUid, installerPackageName);
490 }
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700491
Jeff Sharkeye9808042014-09-11 21:15:37 -0700492 params.installFlags &= ~PackageManager.INSTALL_FROM_ADB;
493 params.installFlags &= ~PackageManager.INSTALL_ALL_USERS;
494 params.installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
Todd Kennedy78a72502017-07-19 12:49:30 -0700495 if ((params.installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0
496 && !mPm.isCallerVerifier(callingUid)) {
497 params.installFlags &= ~PackageManager.INSTALL_VIRTUAL_PRELOAD;
498 }
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700499 }
500
Nikita Ioffe1962cb12019-03-27 22:59:28 +0000501 if (Build.IS_DEBUGGABLE || isDowngradeAllowedForCaller(callingUid)) {
Nikita Ioffeb1d60f12019-03-06 18:56:49 +0000502 params.installFlags |= PackageManager.INSTALL_ALLOW_DOWNGRADE;
Nikita Ioffea1111ff2019-03-04 12:26:14 +0000503 } else {
Nikita Ioffeb1d60f12019-03-06 18:56:49 +0000504 params.installFlags &= ~PackageManager.INSTALL_ALLOW_DOWNGRADE;
Nikita Ioffe1962cb12019-03-27 22:59:28 +0000505 params.installFlags &= ~PackageManager.INSTALL_REQUEST_DOWNGRADE;
Nikita Ioffea1111ff2019-03-04 12:26:14 +0000506 }
507
Nikita Ioffe4501c112019-02-22 11:51:09 +0000508 boolean isApex = (params.installFlags & PackageManager.INSTALL_APEX) != 0;
509 if (params.isStaged || isApex) {
Dario Freni77786d92019-02-08 17:26:05 +0000510 mContext.enforceCallingOrSelfPermission(Manifest.permission.INSTALL_PACKAGES, TAG);
511 }
512
Nikita Ioffe4501c112019-02-22 11:51:09 +0000513 if (isApex) {
Dario Freni83620602019-02-18 14:30:57 +0000514 if (!mApexManager.isApexSupported()) {
515 throw new IllegalArgumentException(
516 "This device doesn't support the installation of APEX files");
517 }
518 if (!params.isStaged) {
519 throw new IllegalArgumentException(
520 "APEX files can only be installed as part of a staged session.");
521 }
522 }
523
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000524 if (!params.isMultiPackage) {
525 // Only system components can circumvent runtime permissions when installing.
526 if ((params.installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
527 && mContext.checkCallingOrSelfPermission(Manifest.permission
528 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
529 throw new SecurityException("You need the "
530 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
531 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700532 }
533
Svet Ganovd8eb8b22019-04-05 18:52:08 -0700534 // Only system components can circumvent restricted whitelisting when installing.
535 if ((params.installFlags
536 & PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS) != 0
537 && mContext.checkCallingOrSelfPermission(Manifest.permission
538 .WHITELIST_RESTRICTED_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
539 throw new SecurityException("You need the "
540 + "android.permission.WHITELIST_RESTRICTED_PERMISSIONS permission to"
541 + " use the PackageManager.INSTALL_WHITELIST_RESTRICTED_PERMISSIONS flag");
542 }
543
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000544 // Defensively resize giant app icons
545 if (params.appIcon != null) {
546 final ActivityManager am = (ActivityManager) mContext.getSystemService(
547 Context.ACTIVITY_SERVICE);
548 final int iconSize = am.getLauncherLargeIconSize();
549 if ((params.appIcon.getWidth() > iconSize * 2)
550 || (params.appIcon.getHeight() > iconSize * 2)) {
551 params.appIcon = Bitmap.createScaledBitmap(params.appIcon, iconSize, iconSize,
552 true);
553 }
554 }
Jeff Sharkeyab234092015-06-09 21:42:22 -0700555
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000556 switch (params.mode) {
557 case SessionParams.MODE_FULL_INSTALL:
558 case SessionParams.MODE_INHERIT_EXISTING:
559 break;
560 default:
561 throw new IllegalArgumentException("Invalid install mode: " + params.mode);
562 }
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700563
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000564 // If caller requested explicit location, sanity check it, otherwise
565 // resolve the best internal or adopted location.
566 if ((params.installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
567 if (!PackageHelper.fitsOnInternal(mContext, params)) {
568 throw new IOException("No suitable internal storage available");
569 }
Patrick Baumannff10c9c2018-12-11 15:17:38 -0800570 } else if ((params.installFlags & PackageManager.INSTALL_FORCE_VOLUME_UUID) != 0) {
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000571 // For now, installs to adopted media are treated as internal from
572 // an install flag point-of-view.
Patrick Baumannfc2851e2018-11-13 15:23:22 -0800573 params.installFlags |= PackageManager.INSTALL_INTERNAL;
Patrick Baumannff10c9c2018-12-11 15:17:38 -0800574 } else {
575 params.installFlags |= PackageManager.INSTALL_INTERNAL;
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000576
577 // Resolve best location for install, based on combination of
578 // requested install flags, delta size, and manifest settings.
579 final long ident = Binder.clearCallingIdentity();
580 try {
581 params.volumeUuid = PackageHelper.resolveInstallVolume(mContext, params);
582 } finally {
583 Binder.restoreCallingIdentity(ident);
584 }
Robin Leee812d902014-08-21 16:51:18 +0100585 }
Jeff Sharkeya1031142014-07-12 18:09:46 -0700586 }
587
588 final int sessionId;
589 final PackageInstallerSession session;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700590 synchronized (mSessions) {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700591 // Sanity check that installer isn't going crazy
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700592 final int activeCount = getSessionCount(mSessions, callingUid);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700593 if (activeCount >= MAX_ACTIVE_SESSIONS) {
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700594 throw new IllegalStateException(
595 "Too many active sessions for UID " + callingUid);
596 }
Narayan Kamatha22a7662017-06-12 13:34:29 +0100597 final int historicalCount = mHistoricalSessionsByInstaller.get(callingUid);
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700598 if (historicalCount >= MAX_HISTORICAL_SESSIONS) {
599 throw new IllegalStateException(
600 "Too many historical sessions for UID " + callingUid);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700601 }
602
Jeff Sharkeya1031142014-07-12 18:09:46 -0700603 sessionId = allocateSessionIdLocked();
Todd Kennedy04918fe2016-07-12 14:07:40 -0700604 }
Jeff Sharkeya1031142014-07-12 18:09:46 -0700605
Todd Kennedy04918fe2016-07-12 14:07:40 -0700606 final long createdMillis = System.currentTimeMillis();
607 // We're staging to exactly one location
608 File stageDir = null;
609 String stageCid = null;
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000610 if (!params.isMultiPackage) {
611 if ((params.installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
Dario Frenia8f4b132018-12-30 00:36:49 +0000612 stageDir = buildSessionDir(sessionId, params);
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000613 } else {
614 stageCid = buildExternalStageCid(sessionId);
615 }
Todd Kennedy04918fe2016-07-12 14:07:40 -0700616 }
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000617 session = new PackageInstallerSession(mInternalCallback, mContext, mPm, this,
Dario Frenibe98c3f2018-12-22 15:25:27 +0000618 mInstallThread.getLooper(), mStagingManager, sessionId, userId,
619 installerPackageName, callingUid, params, createdMillis, stageDir, stageCid, false,
Dario Freni47799f42019-03-13 18:06:24 +0000620 false, false, null, SessionInfo.INVALID_ID, false, false, false,
Dario Frenib6d28962019-01-31 15:52:24 +0000621 SessionInfo.STAGED_SESSION_NO_ERROR, "");
Todd Kennedy04918fe2016-07-12 14:07:40 -0700622
623 synchronized (mSessions) {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700624 mSessions.put(sessionId, session);
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700625 }
Dario Freniaac4ba42018-12-06 15:47:16 +0000626 if (params.isStaged) {
Dario Frenibe98c3f2018-12-22 15:25:27 +0000627 mStagingManager.createSession(session);
Dario Freniaac4ba42018-12-06 15:47:16 +0000628 }
Jeff Sharkeya1031142014-07-12 18:09:46 -0700629
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700630 mCallbacks.notifySessionCreated(session.sessionId, session.userId);
Jeff Sharkeya1031142014-07-12 18:09:46 -0700631 writeSessionsAsync();
632 return sessionId;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700633 }
634
Nikita Ioffe1962cb12019-03-27 22:59:28 +0000635 private boolean isDowngradeAllowedForCaller(int callingUid) {
636 return callingUid == Process.SYSTEM_UID || callingUid == Process.ROOT_UID
637 || callingUid == Process.SHELL_UID;
638 }
639
Jeff Sharkey381d94b2014-08-24 14:45:56 -0700640 @Override
Jeff Sharkeyec9bad22014-09-05 09:45:20 -0700641 public void updateSessionAppIcon(int sessionId, Bitmap appIcon) {
642 synchronized (mSessions) {
643 final PackageInstallerSession session = mSessions.get(sessionId);
644 if (session == null || !isCallingUidOwner(session)) {
645 throw new SecurityException("Caller has no access to session " + sessionId);
646 }
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700647
648 // Defensively resize giant app icons
649 if (appIcon != null) {
650 final ActivityManager am = (ActivityManager) mContext.getSystemService(
651 Context.ACTIVITY_SERVICE);
652 final int iconSize = am.getLauncherLargeIconSize();
653 if ((appIcon.getWidth() > iconSize * 2)
654 || (appIcon.getHeight() > iconSize * 2)) {
655 appIcon = Bitmap.createScaledBitmap(appIcon, iconSize, iconSize, true);
656 }
657 }
658
Jeff Sharkeyec9bad22014-09-05 09:45:20 -0700659 session.params.appIcon = appIcon;
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700660 session.params.appIconLastModified = -1;
661
Jeff Sharkeyec9bad22014-09-05 09:45:20 -0700662 mInternalCallback.onSessionBadgingChanged(session);
663 }
664 }
665
666 @Override
667 public void updateSessionAppLabel(int sessionId, String appLabel) {
668 synchronized (mSessions) {
669 final PackageInstallerSession session = mSessions.get(sessionId);
670 if (session == null || !isCallingUidOwner(session)) {
671 throw new SecurityException("Caller has no access to session " + sessionId);
672 }
673 session.params.appLabel = appLabel;
674 mInternalCallback.onSessionBadgingChanged(session);
675 }
676 }
677
678 @Override
Jeff Sharkey381d94b2014-08-24 14:45:56 -0700679 public void abandonSession(int sessionId) {
680 synchronized (mSessions) {
681 final PackageInstallerSession session = mSessions.get(sessionId);
682 if (session == null || !isCallingUidOwner(session)) {
683 throw new SecurityException("Caller has no access to session " + sessionId);
684 }
685 session.abandon();
686 }
687 }
688
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700689 @Override
690 public IPackageInstallerSession openSession(int sessionId) {
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700691 try {
692 return openSessionInternal(sessionId);
693 } catch (IOException e) {
694 throw ExceptionUtils.wrap(e);
695 }
696 }
697
698 private IPackageInstallerSession openSessionInternal(int sessionId) throws IOException {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700699 synchronized (mSessions) {
700 final PackageInstallerSession session = mSessions.get(sessionId);
Jeff Sharkey381d94b2014-08-24 14:45:56 -0700701 if (session == null || !isCallingUidOwner(session)) {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700702 throw new SecurityException("Caller has no access to session " + sessionId);
703 }
Jeff Sharkey742e7902014-08-16 19:09:13 -0700704 session.open();
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700705 return session;
706 }
707 }
708
Andreas Gampea36dc622018-02-05 17:19:22 -0800709 @GuardedBy("mSessions")
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700710 private int allocateSessionIdLocked() {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700711 int n = 0;
712 int sessionId;
713 do {
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700714 sessionId = mRandom.nextInt(Integer.MAX_VALUE - 1) + 1;
Todd Kennedy28c4e802016-07-13 13:20:30 -0700715 if (!mAllocatedSessions.get(sessionId, false)) {
716 mAllocatedSessions.put(sessionId, true);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700717 return sessionId;
718 }
719 } while (n++ < 32);
720
721 throw new IllegalStateException("Failed to allocate session ID");
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700722 }
723
Dario Frenia8f4b132018-12-30 00:36:49 +0000724 private File getTmpSessionDir(String volumeUuid) {
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700725 return Environment.getDataAppDirectory(volumeUuid);
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700726 }
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700727
Dario Frenia8f4b132018-12-30 00:36:49 +0000728 private File buildTmpSessionDir(int sessionId, String volumeUuid) {
729 final File sessionStagingDir = getTmpSessionDir(volumeUuid);
730 return new File(sessionStagingDir, "vmdl" + sessionId + ".tmp");
731 }
732
733 private File buildSessionDir(int sessionId, SessionParams params) {
734 if (params.isStaged) {
735 final File sessionStagingDir = Environment.getDataStagingDirectory(params.volumeUuid);
736 return new File(sessionStagingDir, "session_" + sessionId);
737 }
738 return buildTmpSessionDir(sessionId, params.volumeUuid);
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700739 }
740
741 static void prepareStageDir(File stageDir) throws IOException {
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700742 if (stageDir.exists()) {
743 throw new IOException("Session dir already exists: " + stageDir);
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700744 }
745
746 try {
Dario Frenid8bf22e2018-08-31 14:18:04 +0100747 Os.mkdir(stageDir.getAbsolutePath(), 0775);
748 Os.chmod(stageDir.getAbsolutePath(), 0775);
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700749 } catch (ErrnoException e) {
750 // This purposefully throws if directory already exists
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700751 throw new IOException("Failed to prepare session dir: " + stageDir, e);
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700752 }
753
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700754 if (!SELinux.restorecon(stageDir)) {
755 throw new IOException("Failed to restorecon session dir: " + stageDir);
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700756 }
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700757 }
758
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700759 private String buildExternalStageCid(int sessionId) {
760 return "smdl" + sessionId + ".tmp";
761 }
Jeff Sharkey742e7902014-08-16 19:09:13 -0700762
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700763 @Override
Jeff Sharkeya0907432014-08-15 10:23:11 -0700764 public SessionInfo getSessionInfo(int sessionId) {
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700765 synchronized (mSessions) {
766 final PackageInstallerSession session = mSessions.get(sessionId);
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700767 return session != null ? session.generateInfo() : null;
768 }
769 }
770
771 @Override
Dario Freniaac4ba42018-12-06 15:47:16 +0000772 public ParceledListSlice<SessionInfo> getStagedSessions() {
Dario Frenibe98c3f2018-12-22 15:25:27 +0000773 return mStagingManager.getSessions();
Dario Freniaac4ba42018-12-06 15:47:16 +0000774 }
775
776 @Override
Jeff Sharkey97d47ed2014-10-15 09:19:47 -0700777 public ParceledListSlice<SessionInfo> getAllSessions(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -0700778 mPermissionManager.enforceCrossUserPermission(
779 Binder.getCallingUid(), userId, true, false, "getAllSessions");
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700780
Jeff Sharkeya0907432014-08-15 10:23:11 -0700781 final List<SessionInfo> result = new ArrayList<>();
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700782 synchronized (mSessions) {
783 for (int i = 0; i < mSessions.size(); i++) {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700784 final PackageInstallerSession session = mSessions.valueAt(i);
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000785 if (session.userId == userId && !session.hasParentSessionId()) {
Jeff Sharkeyda1247a2017-06-08 14:13:29 -0600786 result.add(session.generateInfo(false));
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700787 }
788 }
789 }
Jeff Sharkey97d47ed2014-10-15 09:19:47 -0700790 return new ParceledListSlice<>(result);
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700791 }
792
793 @Override
Jeff Sharkey97d47ed2014-10-15 09:19:47 -0700794 public ParceledListSlice<SessionInfo> getMySessions(String installerPackageName, int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -0700795 mPermissionManager.enforceCrossUserPermission(
796 Binder.getCallingUid(), userId, true, false, "getMySessions");
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700797 mAppOps.checkPackage(Binder.getCallingUid(), installerPackageName);
798
Jeff Sharkeya0907432014-08-15 10:23:11 -0700799 final List<SessionInfo> result = new ArrayList<>();
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700800 synchronized (mSessions) {
801 for (int i = 0; i < mSessions.size(); i++) {
802 final PackageInstallerSession session = mSessions.valueAt(i);
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000803
804 SessionInfo info = session.generateInfo(false);
805 if (Objects.equals(info.getInstallerPackageName(), installerPackageName)
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000806 && session.userId == userId && !session.hasParentSessionId()) {
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000807 result.add(info);
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700808 }
809 }
810 }
Jeff Sharkey97d47ed2014-10-15 09:19:47 -0700811 return new ParceledListSlice<>(result);
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700812 }
813
814 @Override
Svet Ganov67882122016-12-11 16:36:34 -0800815 public void uninstall(VersionedPackage versionedPackage, String callerPackageName, int flags,
816 IntentSender statusReceiver, int userId) throws RemoteException {
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000817 final int callingUid = Binder.getCallingUid();
Todd Kennedy0eb97382017-10-03 16:57:22 -0700818 mPermissionManager.enforceCrossUserPermission(callingUid, userId, true, true, "uninstall");
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000819 if ((callingUid != Process.SHELL_UID) && (callingUid != Process.ROOT_UID)) {
820 mAppOps.checkPackage(callingUid, callerPackageName);
821 }
822
Benjamin Franzdabae882017-08-08 12:33:19 +0100823 // Check whether the caller is device owner or affiliated profile owner, in which case we do
824 // it silently.
Benjamin Franzdabae882017-08-08 12:33:19 +0100825 DevicePolicyManagerInternal dpmi =
826 LocalServices.getService(DevicePolicyManagerInternal.class);
Rubin Xufd4a3b42018-12-05 16:03:27 +0000827 final boolean canSilentlyInstallPackage =
828 dpmi != null && dpmi.canSilentlyInstallPackage(callerPackageName, callingUid);
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700829
Jeff Sharkeya0907432014-08-15 10:23:11 -0700830 final PackageDeleteObserverAdapter adapter = new PackageDeleteObserverAdapter(mContext,
Benjamin Franzdabae882017-08-08 12:33:19 +0100831 statusReceiver, versionedPackage.getPackageName(),
Rubin Xucb924152019-03-28 12:11:17 +0000832 canSilentlyInstallPackage, userId);
Sudheer Shanka72de4dd2016-07-22 15:46:37 -0700833 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DELETE_PACKAGES)
834 == PackageManager.PERMISSION_GRANTED) {
Jeff Sharkeyf0600952014-08-07 17:31:53 -0700835 // Sweet, call straight through!
Svet Ganov67882122016-12-11 16:36:34 -0800836 mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags);
Rubin Xufd4a3b42018-12-05 16:03:27 +0000837 } else if (canSilentlyInstallPackage) {
Benjamin Franzdabae882017-08-08 12:33:19 +0100838 // Allow the device owner and affiliated profile owner to silently delete packages
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000839 // Need to clear the calling identity to get DELETE_PACKAGES permission
840 long ident = Binder.clearCallingIdentity();
841 try {
Svet Ganov67882122016-12-11 16:36:34 -0800842 mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags);
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000843 } finally {
844 Binder.restoreCallingIdentity(ident);
845 }
Rubin Xu8b17ad02019-03-07 17:42:37 +0000846 DevicePolicyEventLogger
847 .createEvent(DevicePolicyEnums.UNINSTALL_PACKAGE)
848 .setAdmin(callerPackageName)
849 .write();
Jeff Sharkeyf0600952014-08-07 17:31:53 -0700850 } else {
Philip P. Moltmannd9bb39a2017-09-05 12:41:15 -0700851 ApplicationInfo appInfo = mPm.getApplicationInfo(callerPackageName, 0, userId);
852 if (appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
853 mContext.enforceCallingOrSelfPermission(Manifest.permission.REQUEST_DELETE_PACKAGES,
854 null);
855 }
856
Jeff Sharkeyf0600952014-08-07 17:31:53 -0700857 // Take a short detour to confirm with user
858 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
Svet Ganov67882122016-12-11 16:36:34 -0800859 intent.setData(Uri.fromParts("package", versionedPackage.getPackageName(), null));
Jeff Sharkeya0907432014-08-15 10:23:11 -0700860 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, adapter.getBinder().asBinder());
861 adapter.onUserActionRequired(intent);
Jeff Sharkeyf0600952014-08-07 17:31:53 -0700862 }
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700863 }
864
865 @Override
Chandan Nathe8e463b2019-01-28 15:23:38 +0000866 public void installExistingPackage(String packageName, int installFlags, int installReason,
867 IntentSender statusReceiver, int userId) {
868 mPm.installExistingPackageAsUser(packageName, userId, installFlags, installReason,
869 statusReceiver);
870 }
871
872 @Override
Jeff Sharkey7328a1b2014-08-07 14:01:43 -0700873 public void setPermissionsResult(int sessionId, boolean accepted) {
874 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, TAG);
875
876 synchronized (mSessions) {
Svet Ganov3baa8762016-04-08 09:22:54 -0700877 PackageInstallerSession session = mSessions.get(sessionId);
878 if (session != null) {
879 session.setPermissionsResult(accepted);
880 }
Jeff Sharkey7328a1b2014-08-07 14:01:43 -0700881 }
882 }
883
884 @Override
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700885 public void registerCallback(IPackageInstallerCallback callback, int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -0700886 mPermissionManager.enforceCrossUserPermission(
887 Binder.getCallingUid(), userId, true, false, "registerCallback");
Jon Miranda2b340a22019-01-25 14:03:49 -0800888 registerCallback(callback, eventUserId -> userId == eventUserId);
889 }
890
891 /**
892 * Assume permissions already checked and caller's identity cleared
893 */
894 public void registerCallback(IPackageInstallerCallback callback, IntPredicate userCheck) {
895 mCallbacks.register(callback, userCheck);
Jeff Sharkeybb580672014-07-10 12:10:25 -0700896 }
897
898 @Override
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700899 public void unregisterCallback(IPackageInstallerCallback callback) {
900 mCallbacks.unregister(callback);
Jeff Sharkeya1031142014-07-12 18:09:46 -0700901 }
902
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000903 @Override
904 public PackageInstallerSession getSession(int sessionId) {
905 synchronized (mSessions) {
906 return mSessions.get(sessionId);
907 }
908 }
909
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700910 private static int getSessionCount(SparseArray<PackageInstallerSession> sessions,
911 int installerUid) {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700912 int count = 0;
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700913 final int size = sessions.size();
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700914 for (int i = 0; i < size; i++) {
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700915 final PackageInstallerSession session = sessions.valueAt(i);
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000916 if (session.getInstallerUid() == installerUid) {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700917 count++;
918 }
919 }
920 return count;
921 }
922
923 private boolean isCallingUidOwner(PackageInstallerSession session) {
924 final int callingUid = Binder.getCallingUid();
925 if (callingUid == Process.ROOT_UID) {
926 return true;
927 } else {
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000928 return (session != null) && (callingUid == session.getInstallerUid());
Jeff Sharkeya1031142014-07-12 18:09:46 -0700929 }
930 }
931
Jeff Sharkeya0907432014-08-15 10:23:11 -0700932 static class PackageDeleteObserverAdapter extends PackageDeleteObserver {
933 private final Context mContext;
934 private final IntentSender mTarget;
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700935 private final String mPackageName;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000936 private final Notification mNotification;
Jeff Sharkeya0907432014-08-15 10:23:11 -0700937
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700938 public PackageDeleteObserverAdapter(Context context, IntentSender target,
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000939 String packageName, boolean showNotification, int userId) {
Jeff Sharkeya0907432014-08-15 10:23:11 -0700940 mContext = context;
941 mTarget = target;
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700942 mPackageName = packageName;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000943 if (showNotification) {
944 mNotification = buildSuccessNotification(mContext,
945 mContext.getResources().getString(R.string.package_deleted_device_owner),
946 packageName,
947 userId);
948 } else {
949 mNotification = null;
950 }
Jeff Sharkeya0907432014-08-15 10:23:11 -0700951 }
952
953 @Override
954 public void onUserActionRequired(Intent intent) {
955 final Intent fillIn = new Intent();
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700956 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, mPackageName);
Jeff Sharkeya0907432014-08-15 10:23:11 -0700957 fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
Jeff Sharkey742e7902014-08-16 19:09:13 -0700958 PackageInstaller.STATUS_PENDING_USER_ACTION);
Jeff Sharkeya0907432014-08-15 10:23:11 -0700959 fillIn.putExtra(Intent.EXTRA_INTENT, intent);
960 try {
961 mTarget.sendIntent(mContext, 0, fillIn, null, null);
962 } catch (SendIntentException ignored) {
963 }
964 }
965
966 @Override
967 public void onPackageDeleted(String basePackageName, int returnCode, String msg) {
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000968 if (PackageManager.DELETE_SUCCEEDED == returnCode && mNotification != null) {
969 NotificationManager notificationManager = (NotificationManager)
970 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Chris Wren282cfef2017-03-27 15:01:44 -0400971 notificationManager.notify(basePackageName,
972 SystemMessage.NOTE_PACKAGE_STATE,
973 mNotification);
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000974 }
Jeff Sharkeya0907432014-08-15 10:23:11 -0700975 final Intent fillIn = new Intent();
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700976 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, mPackageName);
Jeff Sharkeya0907432014-08-15 10:23:11 -0700977 fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
978 PackageManager.deleteStatusToPublicStatus(returnCode));
979 fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE,
980 PackageManager.deleteStatusToString(returnCode, msg));
981 fillIn.putExtra(PackageInstaller.EXTRA_LEGACY_STATUS, returnCode);
982 try {
983 mTarget.sendIntent(mContext, 0, fillIn, null, null);
984 } catch (SendIntentException ignored) {
985 }
986 }
987 }
988
989 static class PackageInstallObserverAdapter extends PackageInstallObserver {
990 private final Context mContext;
991 private final IntentSender mTarget;
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700992 private final int mSessionId;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000993 private final boolean mShowNotification;
994 private final int mUserId;
Jeff Sharkeya0907432014-08-15 10:23:11 -0700995
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000996 public PackageInstallObserverAdapter(Context context, IntentSender target, int sessionId,
997 boolean showNotification, int userId) {
Jeff Sharkeya0907432014-08-15 10:23:11 -0700998 mContext = context;
999 mTarget = target;
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -07001000 mSessionId = sessionId;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001001 mShowNotification = showNotification;
1002 mUserId = userId;
Jeff Sharkeya0907432014-08-15 10:23:11 -07001003 }
1004
1005 @Override
1006 public void onUserActionRequired(Intent intent) {
1007 final Intent fillIn = new Intent();
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -07001008 fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId);
Jeff Sharkeya0907432014-08-15 10:23:11 -07001009 fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
Jeff Sharkey742e7902014-08-16 19:09:13 -07001010 PackageInstaller.STATUS_PENDING_USER_ACTION);
Jeff Sharkeya0907432014-08-15 10:23:11 -07001011 fillIn.putExtra(Intent.EXTRA_INTENT, intent);
1012 try {
1013 mTarget.sendIntent(mContext, 0, fillIn, null, null);
1014 } catch (SendIntentException ignored) {
1015 }
1016 }
1017
1018 @Override
1019 public void onPackageInstalled(String basePackageName, int returnCode, String msg,
1020 Bundle extras) {
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001021 if (PackageManager.INSTALL_SUCCEEDED == returnCode && mShowNotification) {
Benjamin Franz2e3e9432015-04-17 15:28:17 +01001022 boolean update = (extras != null) && extras.getBoolean(Intent.EXTRA_REPLACING);
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001023 Notification notification = buildSuccessNotification(mContext,
Benjamin Franz2e3e9432015-04-17 15:28:17 +01001024 mContext.getResources()
1025 .getString(update ? R.string.package_updated_device_owner :
1026 R.string.package_installed_device_owner),
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001027 basePackageName,
1028 mUserId);
1029 if (notification != null) {
1030 NotificationManager notificationManager = (NotificationManager)
1031 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Chris Wren282cfef2017-03-27 15:01:44 -04001032 notificationManager.notify(basePackageName,
1033 SystemMessage.NOTE_PACKAGE_STATE,
1034 notification);
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001035 }
1036 }
Jeff Sharkeya0907432014-08-15 10:23:11 -07001037 final Intent fillIn = new Intent();
Benjamin Franz2e3e9432015-04-17 15:28:17 +01001038 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, basePackageName);
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -07001039 fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId);
Jeff Sharkeya0907432014-08-15 10:23:11 -07001040 fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
1041 PackageManager.installStatusToPublicStatus(returnCode));
1042 fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE,
1043 PackageManager.installStatusToString(returnCode, msg));
1044 fillIn.putExtra(PackageInstaller.EXTRA_LEGACY_STATUS, returnCode);
1045 if (extras != null) {
1046 final String existing = extras.getString(
1047 PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE);
1048 if (!TextUtils.isEmpty(existing)) {
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07001049 fillIn.putExtra(PackageInstaller.EXTRA_OTHER_PACKAGE_NAME, existing);
Jeff Sharkeya0907432014-08-15 10:23:11 -07001050 }
1051 }
1052 try {
1053 mTarget.sendIntent(mContext, 0, fillIn, null, null);
1054 } catch (SendIntentException ignored) {
1055 }
1056 }
1057 }
1058
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001059 /**
1060 * Build a notification for package installation / deletion by device owners that is shown if
1061 * the operation succeeds.
1062 */
1063 private static Notification buildSuccessNotification(Context context, String contentText,
1064 String basePackageName, int userId) {
1065 PackageInfo packageInfo = null;
1066 try {
1067 packageInfo = AppGlobals.getPackageManager().getPackageInfo(
Svet Ganova5c867c2017-05-15 01:17:05 -07001068 basePackageName, PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001069 } catch (RemoteException ignored) {
1070 }
1071 if (packageInfo == null || packageInfo.applicationInfo == null) {
1072 Slog.w(TAG, "Notification not built for package: " + basePackageName);
1073 return null;
1074 }
1075 PackageManager pm = context.getPackageManager();
1076 Bitmap packageIcon = ImageUtils.buildScaledBitmap(
1077 packageInfo.applicationInfo.loadIcon(pm),
1078 context.getResources().getDimensionPixelSize(
1079 android.R.dimen.notification_large_icon_width),
1080 context.getResources().getDimensionPixelSize(
1081 android.R.dimen.notification_large_icon_height));
1082 CharSequence packageLabel = packageInfo.applicationInfo.loadLabel(pm);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001083 return new Notification.Builder(context, SystemNotificationChannels.DEVICE_ADMIN)
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001084 .setSmallIcon(R.drawable.ic_check_circle_24px)
1085 .setColor(context.getResources().getColor(
1086 R.color.system_notification_accent_color))
1087 .setContentTitle(packageLabel)
1088 .setContentText(contentText)
Benjamin Franz2e3e9432015-04-17 15:28:17 +01001089 .setStyle(new Notification.BigTextStyle().bigText(contentText))
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001090 .setLargeIcon(packageIcon)
1091 .build();
1092 }
1093
Jeff Sharkey54d42be2015-07-20 16:36:55 -07001094 public static <E> ArraySet<E> newArraySet(E... elements) {
1095 final ArraySet<E> set = new ArraySet<E>();
1096 if (elements != null) {
1097 set.ensureCapacity(elements.length);
1098 Collections.addAll(set, elements);
1099 }
1100 return set;
1101 }
1102
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001103 private static class Callbacks extends Handler {
1104 private static final int MSG_SESSION_CREATED = 1;
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001105 private static final int MSG_SESSION_BADGING_CHANGED = 2;
Jeff Sharkeybc7bce32014-09-05 15:53:05 -07001106 private static final int MSG_SESSION_ACTIVE_CHANGED = 3;
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001107 private static final int MSG_SESSION_PROGRESS_CHANGED = 4;
Jeff Sharkeybc7bce32014-09-05 15:53:05 -07001108 private static final int MSG_SESSION_FINISHED = 5;
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -07001109
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001110 private final RemoteCallbackList<IPackageInstallerCallback>
1111 mCallbacks = new RemoteCallbackList<>();
Jeff Sharkeya1031142014-07-12 18:09:46 -07001112
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001113 public Callbacks(Looper looper) {
1114 super(looper);
1115 }
1116
Jon Miranda2b340a22019-01-25 14:03:49 -08001117 public void register(IPackageInstallerCallback callback, IntPredicate userCheck) {
1118 mCallbacks.register(callback, userCheck);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001119 }
1120
1121 public void unregister(IPackageInstallerCallback callback) {
1122 mCallbacks.unregister(callback);
1123 }
1124
1125 @Override
1126 public void handleMessage(Message msg) {
1127 final int userId = msg.arg2;
1128 final int n = mCallbacks.beginBroadcast();
1129 for (int i = 0; i < n; i++) {
1130 final IPackageInstallerCallback callback = mCallbacks.getBroadcastItem(i);
Jon Miranda2b340a22019-01-25 14:03:49 -08001131 final IntPredicate userCheck = (IntPredicate) mCallbacks.getBroadcastCookie(i);
1132 if (userCheck.test(userId)) {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001133 try {
1134 invokeCallback(callback, msg);
1135 } catch (RemoteException ignored) {
1136 }
Jeff Sharkeya1031142014-07-12 18:09:46 -07001137 }
1138 }
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001139 mCallbacks.finishBroadcast();
Jeff Sharkeya1031142014-07-12 18:09:46 -07001140 }
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001141
1142 private void invokeCallback(IPackageInstallerCallback callback, Message msg)
1143 throws RemoteException {
1144 final int sessionId = msg.arg1;
1145 switch (msg.what) {
1146 case MSG_SESSION_CREATED:
1147 callback.onSessionCreated(sessionId);
1148 break;
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001149 case MSG_SESSION_BADGING_CHANGED:
1150 callback.onSessionBadgingChanged(sessionId);
1151 break;
Jeff Sharkeybc7bce32014-09-05 15:53:05 -07001152 case MSG_SESSION_ACTIVE_CHANGED:
1153 callback.onSessionActiveChanged(sessionId, (boolean) msg.obj);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001154 break;
1155 case MSG_SESSION_PROGRESS_CHANGED:
1156 callback.onSessionProgressChanged(sessionId, (float) msg.obj);
1157 break;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001158 case MSG_SESSION_FINISHED:
1159 callback.onSessionFinished(sessionId, (boolean) msg.obj);
1160 break;
1161 }
1162 }
1163
1164 private void notifySessionCreated(int sessionId, int userId) {
1165 obtainMessage(MSG_SESSION_CREATED, sessionId, userId).sendToTarget();
1166 }
1167
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001168 private void notifySessionBadgingChanged(int sessionId, int userId) {
1169 obtainMessage(MSG_SESSION_BADGING_CHANGED, sessionId, userId).sendToTarget();
1170 }
1171
Jeff Sharkeybc7bce32014-09-05 15:53:05 -07001172 private void notifySessionActiveChanged(int sessionId, int userId, boolean active) {
1173 obtainMessage(MSG_SESSION_ACTIVE_CHANGED, sessionId, userId, active).sendToTarget();
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001174 }
1175
1176 private void notifySessionProgressChanged(int sessionId, int userId, float progress) {
1177 obtainMessage(MSG_SESSION_PROGRESS_CHANGED, sessionId, userId, progress).sendToTarget();
1178 }
1179
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001180 public void notifySessionFinished(int sessionId, int userId, boolean success) {
1181 obtainMessage(MSG_SESSION_FINISHED, sessionId, userId, success).sendToTarget();
1182 }
Jeff Sharkeya1031142014-07-12 18:09:46 -07001183 }
1184
1185 void dump(IndentingPrintWriter pw) {
Jeff Sharkeya1031142014-07-12 18:09:46 -07001186 synchronized (mSessions) {
Jeff Sharkey9a445772014-07-16 11:32:08 -07001187 pw.println("Active install sessions:");
1188 pw.increaseIndent();
1189 int N = mSessions.size();
Jeff Sharkeya1031142014-07-12 18:09:46 -07001190 for (int i = 0; i < N; i++) {
1191 final PackageInstallerSession session = mSessions.valueAt(i);
1192 session.dump(pw);
1193 pw.println();
1194 }
Jeff Sharkey9a445772014-07-16 11:32:08 -07001195 pw.println();
1196 pw.decreaseIndent();
1197
1198 pw.println("Historical install sessions:");
1199 pw.increaseIndent();
1200 N = mHistoricalSessions.size();
1201 for (int i = 0; i < N; i++) {
Narayan Kamatha22a7662017-06-12 13:34:29 +01001202 pw.print(mHistoricalSessions.get(i));
Jeff Sharkey9a445772014-07-16 11:32:08 -07001203 pw.println();
1204 }
1205 pw.println();
1206 pw.decreaseIndent();
Jeff Sharkey742e7902014-08-16 19:09:13 -07001207
1208 pw.println("Legacy install sessions:");
1209 pw.increaseIndent();
1210 pw.println(mLegacySessions.toString());
1211 pw.decreaseIndent();
Jeff Sharkeya1031142014-07-12 18:09:46 -07001212 }
Jeff Sharkeybb580672014-07-10 12:10:25 -07001213 }
1214
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001215 class InternalCallback {
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001216 public void onSessionBadgingChanged(PackageInstallerSession session) {
1217 mCallbacks.notifySessionBadgingChanged(session.sessionId, session.userId);
1218 writeSessionsAsync();
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001219 }
1220
Jeff Sharkeybc7bce32014-09-05 15:53:05 -07001221 public void onSessionActiveChanged(PackageInstallerSession session, boolean active) {
1222 mCallbacks.notifySessionActiveChanged(session.sessionId, session.userId, active);
Jeff Sharkey742e7902014-08-16 19:09:13 -07001223 }
1224
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001225 public void onSessionProgressChanged(PackageInstallerSession session, float progress) {
1226 mCallbacks.notifySessionProgressChanged(session.sessionId, session.userId, progress);
1227 }
1228
Dario Freni0180d0b2019-01-11 21:08:13 +00001229 public void onStagedSessionChanged(PackageInstallerSession session) {
Gavin Corkeryd8311212019-02-22 17:52:30 +00001230 session.markUpdated();
Dario Freni0180d0b2019-01-11 21:08:13 +00001231 writeSessionsAsync();
Dario Freni14f885b2019-02-25 12:48:47 +00001232 if (mOkToSendBroadcasts) {
Dario Freni9694b802019-01-27 23:26:06 +00001233 mPm.sendSessionUpdatedBroadcast(session.generateInfo(false),
1234 session.userId);
1235 }
Dario Freni0180d0b2019-01-11 21:08:13 +00001236 }
1237
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001238 public void onSessionFinished(final PackageInstallerSession session, boolean success) {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001239 mCallbacks.notifySessionFinished(session.sessionId, session.userId, success);
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001240
1241 mInstallHandler.post(new Runnable() {
1242 @Override
1243 public void run() {
Dario Freniaac4ba42018-12-06 15:47:16 +00001244 if (session.isStaged()) {
Dario Freniaac4ba42018-12-06 15:47:16 +00001245 if (!success) {
Dario Frenibe98c3f2018-12-22 15:25:27 +00001246 mStagingManager.abortSession(session);
Dario Freniaac4ba42018-12-06 15:47:16 +00001247 }
1248 }
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001249 synchronized (mSessions) {
Dario Freni8e7d0ec2019-01-10 15:21:40 +00001250 if (!session.isStaged() || !success) {
1251 mSessions.remove(session.sessionId);
1252 }
Narayan Kamatha22a7662017-06-12 13:34:29 +01001253 addHistoricalSessionLocked(session);
Jeff Sharkey02bd7842014-10-06 15:14:27 -07001254
1255 final File appIconFile = buildAppIconFile(session.sessionId);
1256 if (appIconFile.exists()) {
1257 appIconFile.delete();
1258 }
1259
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001260 writeSessionsLocked();
1261 }
1262 }
1263 });
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -07001264 }
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -07001265
Jeff Sharkey77d218e2014-09-06 12:20:37 -07001266 public void onSessionPrepared(PackageInstallerSession session) {
1267 // We prepared the destination to write into; we want to persist
1268 // this, but it's not critical enough to block for.
1269 writeSessionsAsync();
1270 }
1271
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001272 public void onSessionSealedBlocking(PackageInstallerSession session) {
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -07001273 // It's very important that we block until we've recorded the
1274 // session as being sealed, since we never want to allow mutation
1275 // after sealing.
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001276 synchronized (mSessions) {
1277 writeSessionsLocked();
1278 }
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -07001279 }
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -07001280 }
1281}