blob: 0032e9a8ea519d792157768f33f1f10e57a9f043 [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()) {
Dario Freni7f5a6952019-05-10 19:40:50 +0100366 if (timeSinceUpdate >= MAX_TIME_SINCE_UPDATE_MILLIS
367 && session.isStagedAndInTerminalState()) {
Gavin Corkeryd8311212019-02-22 17:52:30 +0000368 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
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000534 // Defensively resize giant app icons
535 if (params.appIcon != null) {
536 final ActivityManager am = (ActivityManager) mContext.getSystemService(
537 Context.ACTIVITY_SERVICE);
538 final int iconSize = am.getLauncherLargeIconSize();
539 if ((params.appIcon.getWidth() > iconSize * 2)
540 || (params.appIcon.getHeight() > iconSize * 2)) {
541 params.appIcon = Bitmap.createScaledBitmap(params.appIcon, iconSize, iconSize,
542 true);
543 }
544 }
Jeff Sharkeyab234092015-06-09 21:42:22 -0700545
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000546 switch (params.mode) {
547 case SessionParams.MODE_FULL_INSTALL:
548 case SessionParams.MODE_INHERIT_EXISTING:
549 break;
550 default:
551 throw new IllegalArgumentException("Invalid install mode: " + params.mode);
552 }
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700553
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000554 // If caller requested explicit location, sanity check it, otherwise
555 // resolve the best internal or adopted location.
556 if ((params.installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
557 if (!PackageHelper.fitsOnInternal(mContext, params)) {
558 throw new IOException("No suitable internal storage available");
559 }
Patrick Baumannff10c9c2018-12-11 15:17:38 -0800560 } else if ((params.installFlags & PackageManager.INSTALL_FORCE_VOLUME_UUID) != 0) {
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000561 // For now, installs to adopted media are treated as internal from
562 // an install flag point-of-view.
Patrick Baumannfc2851e2018-11-13 15:23:22 -0800563 params.installFlags |= PackageManager.INSTALL_INTERNAL;
Patrick Baumannff10c9c2018-12-11 15:17:38 -0800564 } else {
565 params.installFlags |= PackageManager.INSTALL_INTERNAL;
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000566
567 // Resolve best location for install, based on combination of
568 // requested install flags, delta size, and manifest settings.
569 final long ident = Binder.clearCallingIdentity();
570 try {
571 params.volumeUuid = PackageHelper.resolveInstallVolume(mContext, params);
572 } finally {
573 Binder.restoreCallingIdentity(ident);
574 }
Robin Leee812d902014-08-21 16:51:18 +0100575 }
Jeff Sharkeya1031142014-07-12 18:09:46 -0700576 }
577
578 final int sessionId;
579 final PackageInstallerSession session;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700580 synchronized (mSessions) {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700581 // Sanity check that installer isn't going crazy
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700582 final int activeCount = getSessionCount(mSessions, callingUid);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700583 if (activeCount >= MAX_ACTIVE_SESSIONS) {
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700584 throw new IllegalStateException(
585 "Too many active sessions for UID " + callingUid);
586 }
Narayan Kamatha22a7662017-06-12 13:34:29 +0100587 final int historicalCount = mHistoricalSessionsByInstaller.get(callingUid);
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700588 if (historicalCount >= MAX_HISTORICAL_SESSIONS) {
589 throw new IllegalStateException(
590 "Too many historical sessions for UID " + callingUid);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700591 }
592
Jeff Sharkeya1031142014-07-12 18:09:46 -0700593 sessionId = allocateSessionIdLocked();
Todd Kennedy04918fe2016-07-12 14:07:40 -0700594 }
Jeff Sharkeya1031142014-07-12 18:09:46 -0700595
Todd Kennedy04918fe2016-07-12 14:07:40 -0700596 final long createdMillis = System.currentTimeMillis();
597 // We're staging to exactly one location
598 File stageDir = null;
599 String stageCid = null;
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000600 if (!params.isMultiPackage) {
601 if ((params.installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
Dario Frenia8f4b132018-12-30 00:36:49 +0000602 stageDir = buildSessionDir(sessionId, params);
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000603 } else {
604 stageCid = buildExternalStageCid(sessionId);
605 }
Todd Kennedy04918fe2016-07-12 14:07:40 -0700606 }
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000607 session = new PackageInstallerSession(mInternalCallback, mContext, mPm, this,
Dario Frenibe98c3f2018-12-22 15:25:27 +0000608 mInstallThread.getLooper(), mStagingManager, sessionId, userId,
609 installerPackageName, callingUid, params, createdMillis, stageDir, stageCid, false,
Dario Freni47799f42019-03-13 18:06:24 +0000610 false, false, null, SessionInfo.INVALID_ID, false, false, false,
Dario Frenib6d28962019-01-31 15:52:24 +0000611 SessionInfo.STAGED_SESSION_NO_ERROR, "");
Todd Kennedy04918fe2016-07-12 14:07:40 -0700612
613 synchronized (mSessions) {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700614 mSessions.put(sessionId, session);
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700615 }
Dario Freniaac4ba42018-12-06 15:47:16 +0000616 if (params.isStaged) {
Dario Frenibe98c3f2018-12-22 15:25:27 +0000617 mStagingManager.createSession(session);
Dario Freniaac4ba42018-12-06 15:47:16 +0000618 }
Jeff Sharkeya1031142014-07-12 18:09:46 -0700619
Richard Uhler1c9c5d22019-06-05 13:04:32 +0100620 if ((session.params.installFlags & PackageManager.INSTALL_DRY_RUN) == 0) {
621 mCallbacks.notifySessionCreated(session.sessionId, session.userId);
622 }
Jeff Sharkeya1031142014-07-12 18:09:46 -0700623 writeSessionsAsync();
624 return sessionId;
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700625 }
626
Nikita Ioffe1962cb12019-03-27 22:59:28 +0000627 private boolean isDowngradeAllowedForCaller(int callingUid) {
628 return callingUid == Process.SYSTEM_UID || callingUid == Process.ROOT_UID
629 || callingUid == Process.SHELL_UID;
630 }
631
Jeff Sharkey381d94b2014-08-24 14:45:56 -0700632 @Override
Jeff Sharkeyec9bad22014-09-05 09:45:20 -0700633 public void updateSessionAppIcon(int sessionId, Bitmap appIcon) {
634 synchronized (mSessions) {
635 final PackageInstallerSession session = mSessions.get(sessionId);
636 if (session == null || !isCallingUidOwner(session)) {
637 throw new SecurityException("Caller has no access to session " + sessionId);
638 }
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700639
640 // Defensively resize giant app icons
641 if (appIcon != null) {
642 final ActivityManager am = (ActivityManager) mContext.getSystemService(
643 Context.ACTIVITY_SERVICE);
644 final int iconSize = am.getLauncherLargeIconSize();
645 if ((appIcon.getWidth() > iconSize * 2)
646 || (appIcon.getHeight() > iconSize * 2)) {
647 appIcon = Bitmap.createScaledBitmap(appIcon, iconSize, iconSize, true);
648 }
649 }
650
Jeff Sharkeyec9bad22014-09-05 09:45:20 -0700651 session.params.appIcon = appIcon;
Jeff Sharkey02bd7842014-10-06 15:14:27 -0700652 session.params.appIconLastModified = -1;
653
Jeff Sharkeyec9bad22014-09-05 09:45:20 -0700654 mInternalCallback.onSessionBadgingChanged(session);
655 }
656 }
657
658 @Override
659 public void updateSessionAppLabel(int sessionId, String appLabel) {
660 synchronized (mSessions) {
661 final PackageInstallerSession session = mSessions.get(sessionId);
662 if (session == null || !isCallingUidOwner(session)) {
663 throw new SecurityException("Caller has no access to session " + sessionId);
664 }
665 session.params.appLabel = appLabel;
666 mInternalCallback.onSessionBadgingChanged(session);
667 }
668 }
669
670 @Override
Jeff Sharkey381d94b2014-08-24 14:45:56 -0700671 public void abandonSession(int sessionId) {
672 synchronized (mSessions) {
673 final PackageInstallerSession session = mSessions.get(sessionId);
674 if (session == null || !isCallingUidOwner(session)) {
675 throw new SecurityException("Caller has no access to session " + sessionId);
676 }
677 session.abandon();
678 }
679 }
680
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700681 @Override
682 public IPackageInstallerSession openSession(int sessionId) {
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700683 try {
684 return openSessionInternal(sessionId);
685 } catch (IOException e) {
686 throw ExceptionUtils.wrap(e);
687 }
688 }
689
690 private IPackageInstallerSession openSessionInternal(int sessionId) throws IOException {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700691 synchronized (mSessions) {
692 final PackageInstallerSession session = mSessions.get(sessionId);
Jeff Sharkey381d94b2014-08-24 14:45:56 -0700693 if (session == null || !isCallingUidOwner(session)) {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700694 throw new SecurityException("Caller has no access to session " + sessionId);
695 }
Jeff Sharkey742e7902014-08-16 19:09:13 -0700696 session.open();
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700697 return session;
698 }
699 }
700
Andreas Gampea36dc622018-02-05 17:19:22 -0800701 @GuardedBy("mSessions")
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700702 private int allocateSessionIdLocked() {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700703 int n = 0;
704 int sessionId;
705 do {
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700706 sessionId = mRandom.nextInt(Integer.MAX_VALUE - 1) + 1;
Todd Kennedy28c4e802016-07-13 13:20:30 -0700707 if (!mAllocatedSessions.get(sessionId, false)) {
708 mAllocatedSessions.put(sessionId, true);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700709 return sessionId;
710 }
711 } while (n++ < 32);
712
713 throw new IllegalStateException("Failed to allocate session ID");
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700714 }
715
Dario Frenia8f4b132018-12-30 00:36:49 +0000716 private File getTmpSessionDir(String volumeUuid) {
Jeff Sharkey6dce4962015-07-03 18:08:41 -0700717 return Environment.getDataAppDirectory(volumeUuid);
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700718 }
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700719
Dario Frenia8f4b132018-12-30 00:36:49 +0000720 private File buildTmpSessionDir(int sessionId, String volumeUuid) {
721 final File sessionStagingDir = getTmpSessionDir(volumeUuid);
722 return new File(sessionStagingDir, "vmdl" + sessionId + ".tmp");
723 }
724
725 private File buildSessionDir(int sessionId, SessionParams params) {
726 if (params.isStaged) {
727 final File sessionStagingDir = Environment.getDataStagingDirectory(params.volumeUuid);
728 return new File(sessionStagingDir, "session_" + sessionId);
729 }
730 return buildTmpSessionDir(sessionId, params.volumeUuid);
Jeff Sharkeyb2b9ab82015-04-05 21:10:42 -0700731 }
732
733 static void prepareStageDir(File stageDir) throws IOException {
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700734 if (stageDir.exists()) {
735 throw new IOException("Session dir already exists: " + stageDir);
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700736 }
737
738 try {
Dario Frenid8bf22e2018-08-31 14:18:04 +0100739 Os.mkdir(stageDir.getAbsolutePath(), 0775);
740 Os.chmod(stageDir.getAbsolutePath(), 0775);
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700741 } catch (ErrnoException e) {
742 // This purposefully throws if directory already exists
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700743 throw new IOException("Failed to prepare session dir: " + stageDir, e);
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700744 }
745
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700746 if (!SELinux.restorecon(stageDir)) {
747 throw new IOException("Failed to restorecon session dir: " + stageDir);
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700748 }
Jeff Sharkeyec55ef02014-07-08 11:28:00 -0700749 }
750
Jeff Sharkey77d218e2014-09-06 12:20:37 -0700751 private String buildExternalStageCid(int sessionId) {
752 return "smdl" + sessionId + ".tmp";
753 }
Jeff Sharkey742e7902014-08-16 19:09:13 -0700754
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700755 @Override
Jeff Sharkeya0907432014-08-15 10:23:11 -0700756 public SessionInfo getSessionInfo(int sessionId) {
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700757 synchronized (mSessions) {
758 final PackageInstallerSession session = mSessions.get(sessionId);
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700759 return session != null ? session.generateInfo() : null;
760 }
761 }
762
763 @Override
Dario Freniaac4ba42018-12-06 15:47:16 +0000764 public ParceledListSlice<SessionInfo> getStagedSessions() {
Dario Frenibe98c3f2018-12-22 15:25:27 +0000765 return mStagingManager.getSessions();
Dario Freniaac4ba42018-12-06 15:47:16 +0000766 }
767
768 @Override
Jeff Sharkey97d47ed2014-10-15 09:19:47 -0700769 public ParceledListSlice<SessionInfo> getAllSessions(int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -0700770 mPermissionManager.enforceCrossUserPermission(
771 Binder.getCallingUid(), userId, true, false, "getAllSessions");
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700772
Jeff Sharkeya0907432014-08-15 10:23:11 -0700773 final List<SessionInfo> result = new ArrayList<>();
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700774 synchronized (mSessions) {
775 for (int i = 0; i < mSessions.size(); i++) {
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700776 final PackageInstallerSession session = mSessions.valueAt(i);
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000777 if (session.userId == userId && !session.hasParentSessionId()) {
Jeff Sharkeyda1247a2017-06-08 14:13:29 -0600778 result.add(session.generateInfo(false));
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700779 }
780 }
781 }
Jeff Sharkey97d47ed2014-10-15 09:19:47 -0700782 return new ParceledListSlice<>(result);
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700783 }
784
785 @Override
Jeff Sharkey97d47ed2014-10-15 09:19:47 -0700786 public ParceledListSlice<SessionInfo> getMySessions(String installerPackageName, int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -0700787 mPermissionManager.enforceCrossUserPermission(
788 Binder.getCallingUid(), userId, true, false, "getMySessions");
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700789 mAppOps.checkPackage(Binder.getCallingUid(), installerPackageName);
790
Jeff Sharkeya0907432014-08-15 10:23:11 -0700791 final List<SessionInfo> result = new ArrayList<>();
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700792 synchronized (mSessions) {
793 for (int i = 0; i < mSessions.size(); i++) {
794 final PackageInstallerSession session = mSessions.valueAt(i);
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000795
796 SessionInfo info = session.generateInfo(false);
797 if (Objects.equals(info.getInstallerPackageName(), installerPackageName)
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000798 && session.userId == userId && !session.hasParentSessionId()) {
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000799 result.add(info);
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700800 }
801 }
802 }
Jeff Sharkey97d47ed2014-10-15 09:19:47 -0700803 return new ParceledListSlice<>(result);
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700804 }
805
806 @Override
Svet Ganov67882122016-12-11 16:36:34 -0800807 public void uninstall(VersionedPackage versionedPackage, String callerPackageName, int flags,
Patrick Baumann466ddb52019-04-11 12:43:05 -0700808 IntentSender statusReceiver, int userId) {
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000809 final int callingUid = Binder.getCallingUid();
Todd Kennedy0eb97382017-10-03 16:57:22 -0700810 mPermissionManager.enforceCrossUserPermission(callingUid, userId, true, true, "uninstall");
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000811 if ((callingUid != Process.SHELL_UID) && (callingUid != Process.ROOT_UID)) {
812 mAppOps.checkPackage(callingUid, callerPackageName);
813 }
814
Benjamin Franzdabae882017-08-08 12:33:19 +0100815 // Check whether the caller is device owner or affiliated profile owner, in which case we do
816 // it silently.
Benjamin Franzdabae882017-08-08 12:33:19 +0100817 DevicePolicyManagerInternal dpmi =
818 LocalServices.getService(DevicePolicyManagerInternal.class);
Rubin Xufd4a3b42018-12-05 16:03:27 +0000819 final boolean canSilentlyInstallPackage =
820 dpmi != null && dpmi.canSilentlyInstallPackage(callerPackageName, callingUid);
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700821
Jeff Sharkeya0907432014-08-15 10:23:11 -0700822 final PackageDeleteObserverAdapter adapter = new PackageDeleteObserverAdapter(mContext,
Benjamin Franzdabae882017-08-08 12:33:19 +0100823 statusReceiver, versionedPackage.getPackageName(),
Rubin Xucb924152019-03-28 12:11:17 +0000824 canSilentlyInstallPackage, userId);
Sudheer Shanka72de4dd2016-07-22 15:46:37 -0700825 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DELETE_PACKAGES)
826 == PackageManager.PERMISSION_GRANTED) {
Jeff Sharkeyf0600952014-08-07 17:31:53 -0700827 // Sweet, call straight through!
Svet Ganov67882122016-12-11 16:36:34 -0800828 mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags);
Rubin Xufd4a3b42018-12-05 16:03:27 +0000829 } else if (canSilentlyInstallPackage) {
Benjamin Franzdabae882017-08-08 12:33:19 +0100830 // Allow the device owner and affiliated profile owner to silently delete packages
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000831 // Need to clear the calling identity to get DELETE_PACKAGES permission
832 long ident = Binder.clearCallingIdentity();
833 try {
Svet Ganov67882122016-12-11 16:36:34 -0800834 mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags);
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000835 } finally {
836 Binder.restoreCallingIdentity(ident);
837 }
Rubin Xu8b17ad02019-03-07 17:42:37 +0000838 DevicePolicyEventLogger
839 .createEvent(DevicePolicyEnums.UNINSTALL_PACKAGE)
840 .setAdmin(callerPackageName)
841 .write();
Jeff Sharkeyf0600952014-08-07 17:31:53 -0700842 } else {
Philip P. Moltmannd9bb39a2017-09-05 12:41:15 -0700843 ApplicationInfo appInfo = mPm.getApplicationInfo(callerPackageName, 0, userId);
844 if (appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
845 mContext.enforceCallingOrSelfPermission(Manifest.permission.REQUEST_DELETE_PACKAGES,
846 null);
847 }
848
Jeff Sharkeyf0600952014-08-07 17:31:53 -0700849 // Take a short detour to confirm with user
850 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
Svet Ganov67882122016-12-11 16:36:34 -0800851 intent.setData(Uri.fromParts("package", versionedPackage.getPackageName(), null));
Jeff Sharkeya0907432014-08-15 10:23:11 -0700852 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, adapter.getBinder().asBinder());
853 adapter.onUserActionRequired(intent);
Jeff Sharkeyf0600952014-08-07 17:31:53 -0700854 }
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -0700855 }
856
857 @Override
Chandan Nathe8e463b2019-01-28 15:23:38 +0000858 public void installExistingPackage(String packageName, int installFlags, int installReason,
Philip P. Moltmanna4bd1502019-05-13 17:10:46 -0700859 IntentSender statusReceiver, int userId, List<String> whiteListedPermissions) {
Chandan Nathe8e463b2019-01-28 15:23:38 +0000860 mPm.installExistingPackageAsUser(packageName, userId, installFlags, installReason,
Philip P. Moltmanna4bd1502019-05-13 17:10:46 -0700861 whiteListedPermissions, statusReceiver);
Chandan Nathe8e463b2019-01-28 15:23:38 +0000862 }
863
864 @Override
Jeff Sharkey7328a1b2014-08-07 14:01:43 -0700865 public void setPermissionsResult(int sessionId, boolean accepted) {
866 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, TAG);
867
868 synchronized (mSessions) {
Svet Ganov3baa8762016-04-08 09:22:54 -0700869 PackageInstallerSession session = mSessions.get(sessionId);
870 if (session != null) {
871 session.setPermissionsResult(accepted);
872 }
Jeff Sharkey7328a1b2014-08-07 14:01:43 -0700873 }
874 }
875
876 @Override
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700877 public void registerCallback(IPackageInstallerCallback callback, int userId) {
Todd Kennedy0eb97382017-10-03 16:57:22 -0700878 mPermissionManager.enforceCrossUserPermission(
879 Binder.getCallingUid(), userId, true, false, "registerCallback");
Jon Miranda2b340a22019-01-25 14:03:49 -0800880 registerCallback(callback, eventUserId -> userId == eventUserId);
881 }
882
883 /**
884 * Assume permissions already checked and caller's identity cleared
885 */
886 public void registerCallback(IPackageInstallerCallback callback, IntPredicate userCheck) {
887 mCallbacks.register(callback, userCheck);
Jeff Sharkeybb580672014-07-10 12:10:25 -0700888 }
889
890 @Override
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -0700891 public void unregisterCallback(IPackageInstallerCallback callback) {
892 mCallbacks.unregister(callback);
Jeff Sharkeya1031142014-07-12 18:09:46 -0700893 }
894
Patrick Baumann0aff9b12018-11-08 14:05:08 +0000895 @Override
896 public PackageInstallerSession getSession(int sessionId) {
897 synchronized (mSessions) {
898 return mSessions.get(sessionId);
899 }
900 }
901
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700902 private static int getSessionCount(SparseArray<PackageInstallerSession> sessions,
903 int installerUid) {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700904 int count = 0;
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700905 final int size = sessions.size();
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700906 for (int i = 0; i < size; i++) {
Jeff Sharkeyf174c6e2014-08-05 10:42:27 -0700907 final PackageInstallerSession session = sessions.valueAt(i);
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000908 if (session.getInstallerUid() == installerUid) {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -0700909 count++;
910 }
911 }
912 return count;
913 }
914
915 private boolean isCallingUidOwner(PackageInstallerSession session) {
916 final int callingUid = Binder.getCallingUid();
917 if (callingUid == Process.ROOT_UID) {
918 return true;
919 } else {
Philip P. Moltmann7460c592017-08-08 20:07:11 +0000920 return (session != null) && (callingUid == session.getInstallerUid());
Jeff Sharkeya1031142014-07-12 18:09:46 -0700921 }
922 }
923
Jeff Sharkeya0907432014-08-15 10:23:11 -0700924 static class PackageDeleteObserverAdapter extends PackageDeleteObserver {
925 private final Context mContext;
926 private final IntentSender mTarget;
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700927 private final String mPackageName;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000928 private final Notification mNotification;
Jeff Sharkeya0907432014-08-15 10:23:11 -0700929
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700930 public PackageDeleteObserverAdapter(Context context, IntentSender target,
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000931 String packageName, boolean showNotification, int userId) {
Jeff Sharkeya0907432014-08-15 10:23:11 -0700932 mContext = context;
933 mTarget = target;
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700934 mPackageName = packageName;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000935 if (showNotification) {
936 mNotification = buildSuccessNotification(mContext,
937 mContext.getResources().getString(R.string.package_deleted_device_owner),
938 packageName,
939 userId);
940 } else {
941 mNotification = null;
942 }
Jeff Sharkeya0907432014-08-15 10:23:11 -0700943 }
944
945 @Override
946 public void onUserActionRequired(Intent intent) {
Patrick Baumann466ddb52019-04-11 12:43:05 -0700947 if (mTarget == null) {
948 return;
949 }
Jeff Sharkeya0907432014-08-15 10:23:11 -0700950 final Intent fillIn = new Intent();
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700951 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, mPackageName);
Jeff Sharkeya0907432014-08-15 10:23:11 -0700952 fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
Jeff Sharkey742e7902014-08-16 19:09:13 -0700953 PackageInstaller.STATUS_PENDING_USER_ACTION);
Jeff Sharkeya0907432014-08-15 10:23:11 -0700954 fillIn.putExtra(Intent.EXTRA_INTENT, intent);
955 try {
956 mTarget.sendIntent(mContext, 0, fillIn, null, null);
957 } catch (SendIntentException ignored) {
958 }
959 }
960
961 @Override
962 public void onPackageDeleted(String basePackageName, int returnCode, String msg) {
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000963 if (PackageManager.DELETE_SUCCEEDED == returnCode && mNotification != null) {
964 NotificationManager notificationManager = (NotificationManager)
965 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Chris Wren282cfef2017-03-27 15:01:44 -0400966 notificationManager.notify(basePackageName,
967 SystemMessage.NOTE_PACKAGE_STATE,
968 mNotification);
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000969 }
Patrick Baumann466ddb52019-04-11 12:43:05 -0700970 if (mTarget == null) {
971 return;
972 }
Jeff Sharkeya0907432014-08-15 10:23:11 -0700973 final Intent fillIn = new Intent();
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700974 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, mPackageName);
Jeff Sharkeya0907432014-08-15 10:23:11 -0700975 fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
976 PackageManager.deleteStatusToPublicStatus(returnCode));
977 fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE,
978 PackageManager.deleteStatusToString(returnCode, msg));
979 fillIn.putExtra(PackageInstaller.EXTRA_LEGACY_STATUS, returnCode);
980 try {
981 mTarget.sendIntent(mContext, 0, fillIn, null, null);
982 } catch (SendIntentException ignored) {
983 }
984 }
985 }
986
987 static class PackageInstallObserverAdapter extends PackageInstallObserver {
988 private final Context mContext;
989 private final IntentSender mTarget;
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700990 private final int mSessionId;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000991 private final boolean mShowNotification;
992 private final int mUserId;
Jeff Sharkeya0907432014-08-15 10:23:11 -0700993
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000994 public PackageInstallObserverAdapter(Context context, IntentSender target, int sessionId,
995 boolean showNotification, int userId) {
Jeff Sharkeya0907432014-08-15 10:23:11 -0700996 mContext = context;
997 mTarget = target;
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -0700998 mSessionId = sessionId;
Benjamin Franz39fb7fd2015-02-18 16:11:18 +0000999 mShowNotification = showNotification;
1000 mUserId = userId;
Jeff Sharkeya0907432014-08-15 10:23:11 -07001001 }
1002
1003 @Override
1004 public void onUserActionRequired(Intent intent) {
1005 final Intent fillIn = new Intent();
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -07001006 fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId);
Jeff Sharkeya0907432014-08-15 10:23:11 -07001007 fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
Jeff Sharkey742e7902014-08-16 19:09:13 -07001008 PackageInstaller.STATUS_PENDING_USER_ACTION);
Jeff Sharkeya0907432014-08-15 10:23:11 -07001009 fillIn.putExtra(Intent.EXTRA_INTENT, intent);
1010 try {
1011 mTarget.sendIntent(mContext, 0, fillIn, null, null);
1012 } catch (SendIntentException ignored) {
1013 }
1014 }
1015
1016 @Override
1017 public void onPackageInstalled(String basePackageName, int returnCode, String msg,
1018 Bundle extras) {
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001019 if (PackageManager.INSTALL_SUCCEEDED == returnCode && mShowNotification) {
Benjamin Franz2e3e9432015-04-17 15:28:17 +01001020 boolean update = (extras != null) && extras.getBoolean(Intent.EXTRA_REPLACING);
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001021 Notification notification = buildSuccessNotification(mContext,
Benjamin Franz2e3e9432015-04-17 15:28:17 +01001022 mContext.getResources()
1023 .getString(update ? R.string.package_updated_device_owner :
1024 R.string.package_installed_device_owner),
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001025 basePackageName,
1026 mUserId);
1027 if (notification != null) {
1028 NotificationManager notificationManager = (NotificationManager)
1029 mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Chris Wren282cfef2017-03-27 15:01:44 -04001030 notificationManager.notify(basePackageName,
1031 SystemMessage.NOTE_PACKAGE_STATE,
1032 notification);
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001033 }
1034 }
Jeff Sharkeya0907432014-08-15 10:23:11 -07001035 final Intent fillIn = new Intent();
Benjamin Franz2e3e9432015-04-17 15:28:17 +01001036 fillIn.putExtra(PackageInstaller.EXTRA_PACKAGE_NAME, basePackageName);
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -07001037 fillIn.putExtra(PackageInstaller.EXTRA_SESSION_ID, mSessionId);
Jeff Sharkeya0907432014-08-15 10:23:11 -07001038 fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
1039 PackageManager.installStatusToPublicStatus(returnCode));
1040 fillIn.putExtra(PackageInstaller.EXTRA_STATUS_MESSAGE,
1041 PackageManager.installStatusToString(returnCode, msg));
1042 fillIn.putExtra(PackageInstaller.EXTRA_LEGACY_STATUS, returnCode);
1043 if (extras != null) {
1044 final String existing = extras.getString(
1045 PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE);
1046 if (!TextUtils.isEmpty(existing)) {
Jeff Sharkey941a8ba2014-08-20 16:26:32 -07001047 fillIn.putExtra(PackageInstaller.EXTRA_OTHER_PACKAGE_NAME, existing);
Jeff Sharkeya0907432014-08-15 10:23:11 -07001048 }
1049 }
1050 try {
1051 mTarget.sendIntent(mContext, 0, fillIn, null, null);
1052 } catch (SendIntentException ignored) {
1053 }
1054 }
1055 }
1056
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001057 /**
1058 * Build a notification for package installation / deletion by device owners that is shown if
1059 * the operation succeeds.
1060 */
1061 private static Notification buildSuccessNotification(Context context, String contentText,
1062 String basePackageName, int userId) {
1063 PackageInfo packageInfo = null;
1064 try {
1065 packageInfo = AppGlobals.getPackageManager().getPackageInfo(
Svet Ganova5c867c2017-05-15 01:17:05 -07001066 basePackageName, PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001067 } catch (RemoteException ignored) {
1068 }
1069 if (packageInfo == null || packageInfo.applicationInfo == null) {
1070 Slog.w(TAG, "Notification not built for package: " + basePackageName);
1071 return null;
1072 }
1073 PackageManager pm = context.getPackageManager();
1074 Bitmap packageIcon = ImageUtils.buildScaledBitmap(
1075 packageInfo.applicationInfo.loadIcon(pm),
1076 context.getResources().getDimensionPixelSize(
1077 android.R.dimen.notification_large_icon_width),
1078 context.getResources().getDimensionPixelSize(
1079 android.R.dimen.notification_large_icon_height));
1080 CharSequence packageLabel = packageInfo.applicationInfo.loadLabel(pm);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001081 return new Notification.Builder(context, SystemNotificationChannels.DEVICE_ADMIN)
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001082 .setSmallIcon(R.drawable.ic_check_circle_24px)
1083 .setColor(context.getResources().getColor(
1084 R.color.system_notification_accent_color))
1085 .setContentTitle(packageLabel)
1086 .setContentText(contentText)
Benjamin Franz2e3e9432015-04-17 15:28:17 +01001087 .setStyle(new Notification.BigTextStyle().bigText(contentText))
Benjamin Franz39fb7fd2015-02-18 16:11:18 +00001088 .setLargeIcon(packageIcon)
1089 .build();
1090 }
1091
Jeff Sharkey54d42be2015-07-20 16:36:55 -07001092 public static <E> ArraySet<E> newArraySet(E... elements) {
1093 final ArraySet<E> set = new ArraySet<E>();
1094 if (elements != null) {
1095 set.ensureCapacity(elements.length);
1096 Collections.addAll(set, elements);
1097 }
1098 return set;
1099 }
1100
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001101 private static class Callbacks extends Handler {
1102 private static final int MSG_SESSION_CREATED = 1;
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001103 private static final int MSG_SESSION_BADGING_CHANGED = 2;
Jeff Sharkeybc7bce32014-09-05 15:53:05 -07001104 private static final int MSG_SESSION_ACTIVE_CHANGED = 3;
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001105 private static final int MSG_SESSION_PROGRESS_CHANGED = 4;
Jeff Sharkeybc7bce32014-09-05 15:53:05 -07001106 private static final int MSG_SESSION_FINISHED = 5;
Jeff Sharkey16c8e3f2014-07-24 17:08:17 -07001107
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001108 private final RemoteCallbackList<IPackageInstallerCallback>
1109 mCallbacks = new RemoteCallbackList<>();
Jeff Sharkeya1031142014-07-12 18:09:46 -07001110
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001111 public Callbacks(Looper looper) {
1112 super(looper);
1113 }
1114
Jon Miranda2b340a22019-01-25 14:03:49 -08001115 public void register(IPackageInstallerCallback callback, IntPredicate userCheck) {
1116 mCallbacks.register(callback, userCheck);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001117 }
1118
1119 public void unregister(IPackageInstallerCallback callback) {
1120 mCallbacks.unregister(callback);
1121 }
1122
1123 @Override
1124 public void handleMessage(Message msg) {
1125 final int userId = msg.arg2;
1126 final int n = mCallbacks.beginBroadcast();
1127 for (int i = 0; i < n; i++) {
1128 final IPackageInstallerCallback callback = mCallbacks.getBroadcastItem(i);
Jon Miranda2b340a22019-01-25 14:03:49 -08001129 final IntPredicate userCheck = (IntPredicate) mCallbacks.getBroadcastCookie(i);
1130 if (userCheck.test(userId)) {
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001131 try {
1132 invokeCallback(callback, msg);
1133 } catch (RemoteException ignored) {
1134 }
Jeff Sharkeya1031142014-07-12 18:09:46 -07001135 }
1136 }
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001137 mCallbacks.finishBroadcast();
Jeff Sharkeya1031142014-07-12 18:09:46 -07001138 }
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001139
1140 private void invokeCallback(IPackageInstallerCallback callback, Message msg)
1141 throws RemoteException {
1142 final int sessionId = msg.arg1;
1143 switch (msg.what) {
1144 case MSG_SESSION_CREATED:
1145 callback.onSessionCreated(sessionId);
1146 break;
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001147 case MSG_SESSION_BADGING_CHANGED:
1148 callback.onSessionBadgingChanged(sessionId);
1149 break;
Jeff Sharkeybc7bce32014-09-05 15:53:05 -07001150 case MSG_SESSION_ACTIVE_CHANGED:
1151 callback.onSessionActiveChanged(sessionId, (boolean) msg.obj);
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001152 break;
1153 case MSG_SESSION_PROGRESS_CHANGED:
1154 callback.onSessionProgressChanged(sessionId, (float) msg.obj);
1155 break;
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001156 case MSG_SESSION_FINISHED:
1157 callback.onSessionFinished(sessionId, (boolean) msg.obj);
1158 break;
1159 }
1160 }
1161
1162 private void notifySessionCreated(int sessionId, int userId) {
1163 obtainMessage(MSG_SESSION_CREATED, sessionId, userId).sendToTarget();
1164 }
1165
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001166 private void notifySessionBadgingChanged(int sessionId, int userId) {
1167 obtainMessage(MSG_SESSION_BADGING_CHANGED, sessionId, userId).sendToTarget();
1168 }
1169
Jeff Sharkeybc7bce32014-09-05 15:53:05 -07001170 private void notifySessionActiveChanged(int sessionId, int userId, boolean active) {
1171 obtainMessage(MSG_SESSION_ACTIVE_CHANGED, sessionId, userId, active).sendToTarget();
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001172 }
1173
1174 private void notifySessionProgressChanged(int sessionId, int userId, float progress) {
1175 obtainMessage(MSG_SESSION_PROGRESS_CHANGED, sessionId, userId, progress).sendToTarget();
1176 }
1177
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001178 public void notifySessionFinished(int sessionId, int userId, boolean success) {
1179 obtainMessage(MSG_SESSION_FINISHED, sessionId, userId, success).sendToTarget();
1180 }
Jeff Sharkeya1031142014-07-12 18:09:46 -07001181 }
1182
1183 void dump(IndentingPrintWriter pw) {
Jeff Sharkeya1031142014-07-12 18:09:46 -07001184 synchronized (mSessions) {
Jeff Sharkey9a445772014-07-16 11:32:08 -07001185 pw.println("Active install sessions:");
1186 pw.increaseIndent();
1187 int N = mSessions.size();
Jeff Sharkeya1031142014-07-12 18:09:46 -07001188 for (int i = 0; i < N; i++) {
1189 final PackageInstallerSession session = mSessions.valueAt(i);
1190 session.dump(pw);
1191 pw.println();
1192 }
Jeff Sharkey9a445772014-07-16 11:32:08 -07001193 pw.println();
1194 pw.decreaseIndent();
1195
1196 pw.println("Historical install sessions:");
1197 pw.increaseIndent();
1198 N = mHistoricalSessions.size();
1199 for (int i = 0; i < N; i++) {
Narayan Kamatha22a7662017-06-12 13:34:29 +01001200 pw.print(mHistoricalSessions.get(i));
Jeff Sharkey9a445772014-07-16 11:32:08 -07001201 pw.println();
1202 }
1203 pw.println();
1204 pw.decreaseIndent();
Jeff Sharkey742e7902014-08-16 19:09:13 -07001205
1206 pw.println("Legacy install sessions:");
1207 pw.increaseIndent();
1208 pw.println(mLegacySessions.toString());
1209 pw.decreaseIndent();
Jeff Sharkeya1031142014-07-12 18:09:46 -07001210 }
Jeff Sharkeybb580672014-07-10 12:10:25 -07001211 }
1212
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001213 class InternalCallback {
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001214 public void onSessionBadgingChanged(PackageInstallerSession session) {
Richard Uhler1c9c5d22019-06-05 13:04:32 +01001215 if ((session.params.installFlags & PackageManager.INSTALL_DRY_RUN) == 0) {
1216 mCallbacks.notifySessionBadgingChanged(session.sessionId, session.userId);
1217 }
1218
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001219 writeSessionsAsync();
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -07001220 }
1221
Jeff Sharkeybc7bce32014-09-05 15:53:05 -07001222 public void onSessionActiveChanged(PackageInstallerSession session, boolean active) {
Richard Uhler1c9c5d22019-06-05 13:04:32 +01001223 if ((session.params.installFlags & PackageManager.INSTALL_DRY_RUN) == 0) {
1224 mCallbacks.notifySessionActiveChanged(session.sessionId, session.userId,
1225 active);
1226 }
Jeff Sharkey742e7902014-08-16 19:09:13 -07001227 }
1228
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001229 public void onSessionProgressChanged(PackageInstallerSession session, float progress) {
Richard Uhler1c9c5d22019-06-05 13:04:32 +01001230 if ((session.params.installFlags & PackageManager.INSTALL_DRY_RUN) == 0) {
1231 mCallbacks.notifySessionProgressChanged(session.sessionId, session.userId,
1232 progress);
1233 }
Jeff Sharkeyec9bad22014-09-05 09:45:20 -07001234 }
1235
Dario Freni0180d0b2019-01-11 21:08:13 +00001236 public void onStagedSessionChanged(PackageInstallerSession session) {
Gavin Corkeryd8311212019-02-22 17:52:30 +00001237 session.markUpdated();
Dario Freni0180d0b2019-01-11 21:08:13 +00001238 writeSessionsAsync();
Dario Freni14f885b2019-02-25 12:48:47 +00001239 if (mOkToSendBroadcasts) {
Dario Freni9694b802019-01-27 23:26:06 +00001240 mPm.sendSessionUpdatedBroadcast(session.generateInfo(false),
1241 session.userId);
1242 }
Dario Freni0180d0b2019-01-11 21:08:13 +00001243 }
1244
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001245 public void onSessionFinished(final PackageInstallerSession session, boolean success) {
Richard Uhler1c9c5d22019-06-05 13:04:32 +01001246 if ((session.params.installFlags & PackageManager.INSTALL_DRY_RUN) == 0) {
1247 mCallbacks.notifySessionFinished(session.sessionId, session.userId, success);
1248 }
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001249
1250 mInstallHandler.post(new Runnable() {
1251 @Override
1252 public void run() {
Dario Freniaac4ba42018-12-06 15:47:16 +00001253 if (session.isStaged()) {
Dario Freniaac4ba42018-12-06 15:47:16 +00001254 if (!success) {
Dario Frenibe98c3f2018-12-22 15:25:27 +00001255 mStagingManager.abortSession(session);
Dario Freniaac4ba42018-12-06 15:47:16 +00001256 }
1257 }
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001258 synchronized (mSessions) {
Dario Freni8e7d0ec2019-01-10 15:21:40 +00001259 if (!session.isStaged() || !success) {
1260 mSessions.remove(session.sessionId);
1261 }
Narayan Kamatha22a7662017-06-12 13:34:29 +01001262 addHistoricalSessionLocked(session);
Jeff Sharkey02bd7842014-10-06 15:14:27 -07001263
1264 final File appIconFile = buildAppIconFile(session.sessionId);
1265 if (appIconFile.exists()) {
1266 appIconFile.delete();
1267 }
1268
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001269 writeSessionsLocked();
1270 }
1271 }
1272 });
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -07001273 }
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -07001274
Jeff Sharkey77d218e2014-09-06 12:20:37 -07001275 public void onSessionPrepared(PackageInstallerSession session) {
1276 // We prepared the destination to write into; we want to persist
1277 // this, but it's not critical enough to block for.
1278 writeSessionsAsync();
1279 }
1280
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001281 public void onSessionSealedBlocking(PackageInstallerSession session) {
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -07001282 // It's very important that we block until we've recorded the
1283 // session as being sealed, since we never want to allow mutation
1284 // after sealing.
Jeff Sharkeycbf47912014-09-12 09:55:32 -07001285 synchronized (mSessions) {
1286 writeSessionsLocked();
1287 }
Jeff Sharkeybb7b7be2014-08-19 16:18:28 -07001288 }
Jeff Sharkey3a44f3f2014-04-28 17:36:31 -07001289 }
1290}