blob: 7467954918d86a6006f6c8666b6954c188275ef3 [file] [log] [blame]
Mårten Kongstadeabc9e92015-12-15 16:40:23 +01001/*
2 * Copyright (C) 2016 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.om;
18
19import static android.app.AppGlobals.getPackageManager;
20import static android.content.Intent.ACTION_PACKAGE_ADDED;
21import static android.content.Intent.ACTION_PACKAGE_CHANGED;
22import static android.content.Intent.ACTION_PACKAGE_REMOVED;
Adam Lesinskiada8deb2017-05-12 13:50:42 -070023import static android.content.Intent.ACTION_USER_ADDED;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +010024import static android.content.Intent.ACTION_USER_REMOVED;
25import static android.content.pm.PackageManager.SIGNATURE_MATCH;
26
27import android.annotation.NonNull;
28import android.annotation.Nullable;
29import android.app.ActivityManager;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +010030import android.app.IActivityManager;
31import android.content.BroadcastReceiver;
32import android.content.Context;
33import android.content.Intent;
34import android.content.IntentFilter;
35import android.content.om.IOverlayManager;
36import android.content.om.OverlayInfo;
37import android.content.pm.IPackageManager;
38import android.content.pm.PackageInfo;
39import android.content.pm.PackageManagerInternal;
40import android.content.pm.UserInfo;
41import android.net.Uri;
42import android.os.Binder;
43import android.os.Environment;
44import android.os.IBinder;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +010045import android.os.RemoteException;
46import android.os.ResultReceiver;
47import android.os.ShellCallback;
Adam Lesinskia5ca6242017-03-01 15:45:12 -080048import android.os.SystemProperties;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +010049import android.os.UserHandle;
Adam Lesinskiada8deb2017-05-12 13:50:42 -070050import android.os.UserManager;
Adam Lesinskia5ca6242017-03-01 15:45:12 -080051import android.text.TextUtils;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +010052import android.util.ArrayMap;
Adam Lesinskia5ca6242017-03-01 15:45:12 -080053import android.util.ArraySet;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +010054import android.util.AtomicFile;
55import android.util.Slog;
56import android.util.SparseArray;
57
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -080058import com.android.internal.util.ConcurrentUtils;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +010059import com.android.server.FgThread;
60import com.android.server.IoThread;
61import com.android.server.LocalServices;
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -080062import com.android.server.SystemServerInitThreadPool;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +010063import com.android.server.SystemService;
64import com.android.server.pm.Installer;
65import com.android.server.pm.UserManagerService;
66
67import org.xmlpull.v1.XmlPullParserException;
68
69import java.io.File;
70import java.io.FileDescriptor;
71import java.io.FileInputStream;
72import java.io.FileOutputStream;
73import java.io.IOException;
74import java.io.PrintWriter;
75import java.util.ArrayList;
Adam Lesinskid11c5512017-04-11 12:01:10 -070076import java.util.Arrays;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +010077import java.util.Collections;
78import java.util.HashMap;
79import java.util.List;
80import java.util.Map;
Adam Lesinskia5ca6242017-03-01 15:45:12 -080081import java.util.Set;
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -080082import java.util.concurrent.Future;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +010083import java.util.concurrent.atomic.AtomicBoolean;
84
85/**
86 * Service to manage asset overlays.
87 *
88 * <p>Asset overlays are additional resources that come from apks loaded
89 * alongside the system and app apks. This service, the OverlayManagerService
90 * (OMS), tracks which installed overlays to use and provides methods to change
91 * this. Changes propagate to running applications as part of the Activity
92 * lifecycle. This allows Activities to reread their resources at a well
93 * defined point.</p>
94 *
95 * <p>By itself, the OMS will not change what overlays should be active.
96 * Instead, it is only responsible for making sure that overlays *can* be used
97 * from a technical and security point of view and to activate overlays in
98 * response to external requests. The responsibility to toggle overlays on and
99 * off lies within components that implement different use-cases such as themes
100 * or dynamic customization.</p>
101 *
102 * <p>The OMS receives input from three sources:</p>
103 *
104 * <ul>
105 * <li>Callbacks from the SystemService class, specifically when the
106 * Android framework is booting and when the end user switches Android
107 * users.</li>
108 *
109 * <li>Intents from the PackageManagerService (PMS). Overlays are regular
110 * apks, and whenever a package is installed (or removed, or has a
111 * component enabled or disabled), the PMS broadcasts this as an intent.
112 * When the OMS receives one of these intents, it updates its internal
113 * representation of the available overlays and, if there was a visible
114 * change, triggers an asset refresh in the affected apps.</li>
115 *
116 * <li>External requests via the {@link IOverlayManager AIDL interface}.
117 * The interface allows clients to read information about the currently
118 * available overlays, change whether an overlay should be used or not, and
119 * change the relative order in which overlay packages are loaded.
120 * Read-access is granted if the request targets the same Android user as
121 * the caller runs as, or if the caller holds the
122 * INTERACT_ACROSS_USERS_FULL permission. Write-access is granted if the
123 * caller is granted read-access and additionaly holds the
124 * CHANGE_OVERLAY_PACKAGES permission.</li>
125 * </ul>
126 *
127 * <p>The AIDL interface works with String package names, int user IDs, and
128 * {@link OverlayInfo} objects. OverlayInfo instances are used to track a
129 * specific pair of target and overlay packages and include information such as
130 * the current state of the overlay. OverlayInfo objects are immutable.</p>
131 *
132 * <p>Internally, OverlayInfo objects are maintained by the
133 * OverlayManagerSettings class. The OMS and its helper classes are notified of
134 * changes to the settings by the OverlayManagerSettings.ChangeListener
135 * callback interface. The file /data/system/overlays.xml is used to persist
136 * the settings.</p>
137 *
138 * <p>Creation and deletion of idmap files are handled by the IdmapManager
139 * class.</p>
140 *
141 * <p>The following is an overview of OMS and its related classes. Note how box
142 * (2) does the heavy lifting, box (1) interacts with the Android framework,
143 * and box (3) replaces box (1) during unit testing.</p>
144 *
145 * <pre>
146 * Android framework
147 * | ^
148 * . . . | . . . . | . . . .
149 * . | | .
150 * . AIDL, broadcasts .
151 * . intents | .
152 * . | | . . . . . . . . . . . .
153 * . v | . .
154 * . OverlayManagerService . OverlayManagerTests .
155 * . \ . / .
156 * . (1) \ . / (3) .
157 * . . . . . . . . . . \ . . . / . . . . . . . . .
158 * . \ / .
159 * . (2) \ / .
160 * . OverlayManagerServiceImpl .
161 * . | | .
162 * . | | .
163 * . OverlayManagerSettings IdmapManager .
164 * . .
165 * . . . . . . . . . . . . . . . . . . . . . .
166 * </pre>
167 *
168 * <p>Finally, here is a list of keywords used in the OMS context.</p>
169 *
170 * <ul>
171 * <li><b>target [package]</b> -- A regular apk that may have its resource
172 * pool extended by zero or more overlay packages.</li>
173 *
174 * <li><b>overlay [package]</b> -- An apk that provides additional
175 * resources to another apk.</li>
176 *
177 * <li><b>OMS</b> -- The OverlayManagerService, i.e. this class.</li>
178 *
179 * <li><b>approved</b> -- An overlay is approved if the OMS has verified
180 * that it can be used technically speaking (its target package is
181 * installed, at least one resource name in both packages match, the
182 * idmap was created, etc) and that it is secure to do so. External
183 * clients can not change this state.</li>
184 *
185 * <li><b>not approved</b> -- The opposite of approved.</li>
186 *
187 * <li><b>enabled</b> -- An overlay currently in active use and thus part
188 * of resource lookups. This requires the overlay to be approved. Only
189 * external clients can change this state.</li>
190 *
191 * <li><b>disabled</b> -- The opposite of enabled.</li>
192 *
193 * <li><b>idmap</b> -- A mapping of resource IDs between target and overlay
194 * used during resource lookup. Also the name of the binary that creates
195 * the mapping.</li>
196 * </ul>
197 */
198public final class OverlayManagerService extends SystemService {
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100199 static final String TAG = "OverlayManager";
200
201 static final boolean DEBUG = false;
202
Adam Lesinskia5ca6242017-03-01 15:45:12 -0800203 /**
204 * The system property that specifies the default overlays to apply.
205 * This is a semicolon separated list of package names.
206 *
207 * Ex: com.android.vendor.overlay_one;com.android.vendor.overlay_two
208 */
209 private static final String DEFAULT_OVERLAYS_PROP = "ro.boot.vendor.overlay.theme";
210
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100211 private final Object mLock = new Object();
212
213 private final AtomicFile mSettingsFile;
214
215 private final PackageManagerHelper mPackageManager;
216
217 private final UserManagerService mUserManager;
218
219 private final OverlayManagerSettings mSettings;
220
221 private final OverlayManagerServiceImpl mImpl;
222
223 private final AtomicBoolean mPersistSettingsScheduled = new AtomicBoolean(false);
224
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -0800225 private Future<?> mInitCompleteSignal;
226
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100227 public OverlayManagerService(@NonNull final Context context,
228 @NonNull final Installer installer) {
229 super(context);
230 mSettingsFile =
Dianne Hackborne17b4452018-01-10 13:15:40 -0800231 new AtomicFile(new File(Environment.getDataSystemDirectory(), "overlays.xml"), "overlays");
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100232 mPackageManager = new PackageManagerHelper();
233 mUserManager = UserManagerService.getInstance();
234 IdmapManager im = new IdmapManager(installer);
235 mSettings = new OverlayManagerSettings();
Adam Lesinskia5ca6242017-03-01 15:45:12 -0800236 mImpl = new OverlayManagerServiceImpl(mPackageManager, im, mSettings,
Adam Lesinskic745f422017-04-05 16:31:30 -0700237 getDefaultOverlayPackages(), new OverlayChangeListener());
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -0800238 mInitCompleteSignal = SystemServerInitThreadPool.get().submit(() -> {
239 final IntentFilter packageFilter = new IntentFilter();
240 packageFilter.addAction(ACTION_PACKAGE_ADDED);
241 packageFilter.addAction(ACTION_PACKAGE_CHANGED);
242 packageFilter.addAction(ACTION_PACKAGE_REMOVED);
243 packageFilter.addDataScheme("package");
244 getContext().registerReceiverAsUser(new PackageReceiver(), UserHandle.ALL,
245 packageFilter, null, null);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100246
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -0800247 final IntentFilter userFilter = new IntentFilter();
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700248 userFilter.addAction(ACTION_USER_ADDED);
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -0800249 userFilter.addAction(ACTION_USER_REMOVED);
250 getContext().registerReceiverAsUser(new UserReceiver(), UserHandle.ALL,
251 userFilter, null, null);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100252
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -0800253 restoreSettings();
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700254
255 initIfNeeded();
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -0800256 onSwitchUser(UserHandle.USER_SYSTEM);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100257
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -0800258 publishBinderService(Context.OVERLAY_SERVICE, mService);
259 publishLocalService(OverlayManagerService.class, this);
260 }, "Init OverlayManagerService");
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100261 }
262
263 @Override
264 public void onStart() {
265 // Intentionally left empty.
266 }
267
268 @Override
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -0800269 public void onBootPhase(int phase) {
270 if (phase == PHASE_SYSTEM_SERVICES_READY) {
271 ConcurrentUtils.waitForFutureNoInterrupt(mInitCompleteSignal,
272 "Wait for OverlayManagerService init");
273 mInitCompleteSignal = null;
274 }
275 }
276
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700277 private void initIfNeeded() {
278 final UserManager um = getContext().getSystemService(UserManager.class);
279 final List<UserInfo> users = um.getUsers(true /*excludeDying*/);
280 synchronized (mLock) {
281 final int userCount = users.size();
282 for (int i = 0; i < userCount; i++) {
283 final UserInfo userInfo = users.get(i);
284 if (!userInfo.supportsSwitchTo() && userInfo.id != UserHandle.USER_SYSTEM) {
285 // Initialize any users that can't be switched to, as there state would
286 // never be setup in onSwitchUser(). We will switch to the system user right
287 // after this, and its state will be setup there.
288 final List<String> targets = mImpl.updateOverlaysForUser(users.get(i).id);
289 updateOverlayPaths(users.get(i).id, targets);
290 }
291 }
292 }
293 }
294
Fyodor Kupolov94ab1a62017-03-06 14:28:20 -0800295 @Override
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100296 public void onSwitchUser(final int newUserId) {
297 // ensure overlays in the settings are up-to-date, and propagate
298 // any asset changes to the rest of the system
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100299 synchronized (mLock) {
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700300 final List<String> targets = mImpl.updateOverlaysForUser(newUserId);
301 updateAssets(newUserId, targets);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100302 }
Adam Lesinskic745f422017-04-05 16:31:30 -0700303 schedulePersistSettings();
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100304 }
305
Adam Lesinskia5ca6242017-03-01 15:45:12 -0800306 private static Set<String> getDefaultOverlayPackages() {
307 final String str = SystemProperties.get(DEFAULT_OVERLAYS_PROP);
308 if (TextUtils.isEmpty(str)) {
309 return Collections.emptySet();
310 }
311
312 final ArraySet<String> defaultPackages = new ArraySet<>();
313 for (String packageName : str.split(";")) {
314 if (!TextUtils.isEmpty(packageName)) {
315 defaultPackages.add(packageName);
316 }
317 }
318 return defaultPackages;
319 }
320
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100321 private final class PackageReceiver extends BroadcastReceiver {
322 @Override
323 public void onReceive(@NonNull final Context context, @NonNull final Intent intent) {
324 final Uri data = intent.getData();
325 if (data == null) {
326 Slog.e(TAG, "Cannot handle package broadcast with null data");
327 return;
328 }
329 final String packageName = data.getSchemeSpecificPart();
330
331 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
332
333 final int[] userIds;
334 final int extraUid = intent.getIntExtra(Intent.EXTRA_UID, UserHandle.USER_NULL);
335 if (extraUid == UserHandle.USER_NULL) {
336 userIds = mUserManager.getUserIds();
337 } else {
338 userIds = new int[] { UserHandle.getUserId(extraUid) };
339 }
340
341 switch (intent.getAction()) {
342 case ACTION_PACKAGE_ADDED:
343 if (replacing) {
344 onPackageUpgraded(packageName, userIds);
345 } else {
346 onPackageAdded(packageName, userIds);
347 }
348 break;
349 case ACTION_PACKAGE_CHANGED:
350 onPackageChanged(packageName, userIds);
351 break;
352 case ACTION_PACKAGE_REMOVED:
353 if (replacing) {
354 onPackageUpgrading(packageName, userIds);
355 } else {
356 onPackageRemoved(packageName, userIds);
357 }
358 break;
359 default:
360 // do nothing
361 break;
362 }
363 }
364
365 private void onPackageAdded(@NonNull final String packageName,
366 @NonNull final int[] userIds) {
367 for (final int userId : userIds) {
368 synchronized (mLock) {
Adam Lesinskic745f422017-04-05 16:31:30 -0700369 final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId,
370 false);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100371 if (pi != null) {
372 mPackageManager.cachePackageInfo(packageName, userId, pi);
Adam Lesinskiab56b9d2017-11-14 00:50:18 -0800373 if (pi.isOverlayPackage()) {
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100374 mImpl.onOverlayPackageAdded(packageName, userId);
Adam Lesinskiab56b9d2017-11-14 00:50:18 -0800375 } else {
376 mImpl.onTargetPackageAdded(packageName, userId);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100377 }
378 }
379 }
380 }
381 }
382
383 private void onPackageChanged(@NonNull final String packageName,
384 @NonNull final int[] userIds) {
385 for (int userId : userIds) {
386 synchronized (mLock) {
Adam Lesinskic745f422017-04-05 16:31:30 -0700387 final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId,
388 false);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100389 if (pi != null) {
390 mPackageManager.cachePackageInfo(packageName, userId, pi);
Adam Lesinskiab56b9d2017-11-14 00:50:18 -0800391 if (pi.isOverlayPackage()) {
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100392 mImpl.onOverlayPackageChanged(packageName, userId);
Adam Lesinskiab56b9d2017-11-14 00:50:18 -0800393 } else {
394 mImpl.onTargetPackageChanged(packageName, userId);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100395 }
396 }
397 }
398 }
399 }
400
401 private void onPackageUpgrading(@NonNull final String packageName,
402 @NonNull final int[] userIds) {
403 for (int userId : userIds) {
404 synchronized (mLock) {
405 mPackageManager.forgetPackageInfo(packageName, userId);
406 final OverlayInfo oi = mImpl.getOverlayInfo(packageName, userId);
Adam Lesinskiab56b9d2017-11-14 00:50:18 -0800407 if (oi != null) {
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100408 mImpl.onOverlayPackageUpgrading(packageName, userId);
Adam Lesinskiab56b9d2017-11-14 00:50:18 -0800409 } else {
410 mImpl.onTargetPackageUpgrading(packageName, userId);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100411 }
412 }
413 }
414 }
415
416 private void onPackageUpgraded(@NonNull final String packageName,
417 @NonNull final int[] userIds) {
418 for (int userId : userIds) {
419 synchronized (mLock) {
Adam Lesinskic745f422017-04-05 16:31:30 -0700420 final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId,
421 false);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100422 if (pi != null) {
423 mPackageManager.cachePackageInfo(packageName, userId, pi);
Adam Lesinskiab56b9d2017-11-14 00:50:18 -0800424 if (pi.isOverlayPackage()) {
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100425 mImpl.onOverlayPackageUpgraded(packageName, userId);
Adam Lesinskiab56b9d2017-11-14 00:50:18 -0800426 } else {
427 mImpl.onTargetPackageUpgraded(packageName, userId);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100428 }
429 }
430 }
431 }
432 }
433
434 private void onPackageRemoved(@NonNull final String packageName,
435 @NonNull final int[] userIds) {
436 for (int userId : userIds) {
437 synchronized (mLock) {
438 mPackageManager.forgetPackageInfo(packageName, userId);
439 final OverlayInfo oi = mImpl.getOverlayInfo(packageName, userId);
Adam Lesinskiab56b9d2017-11-14 00:50:18 -0800440 if (oi != null) {
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100441 mImpl.onOverlayPackageRemoved(packageName, userId);
Adam Lesinskiab56b9d2017-11-14 00:50:18 -0800442 } else {
443 mImpl.onTargetPackageRemoved(packageName, userId);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100444 }
445 }
446 }
447 }
448 }
449
450 private final class UserReceiver extends BroadcastReceiver {
451 @Override
452 public void onReceive(@NonNull final Context context, @NonNull final Intent intent) {
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700453 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100454 switch (intent.getAction()) {
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700455 case ACTION_USER_ADDED:
456 if (userId != UserHandle.USER_NULL) {
457 final ArrayList<String> targets;
458 synchronized (mLock) {
459 targets = mImpl.updateOverlaysForUser(userId);
460 }
461 updateOverlayPaths(userId, targets);
462 }
463 break;
464
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100465 case ACTION_USER_REMOVED:
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100466 if (userId != UserHandle.USER_NULL) {
467 synchronized (mLock) {
468 mImpl.onUserRemoved(userId);
469 mPackageManager.forgetAllPackageInfos(userId);
470 }
471 }
472 break;
473 default:
474 // do nothing
475 break;
476 }
477 }
478 }
479
480 private final IBinder mService = new IOverlayManager.Stub() {
481 @Override
Adam Lesinskic745f422017-04-05 16:31:30 -0700482 public Map<String, List<OverlayInfo>> getAllOverlays(int userId) throws RemoteException {
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100483 userId = handleIncomingUser(userId, "getAllOverlays");
484
485 synchronized (mLock) {
486 return mImpl.getOverlaysForUser(userId);
487 }
488 }
489
490 @Override
491 public List<OverlayInfo> getOverlayInfosForTarget(@Nullable final String targetPackageName,
492 int userId) throws RemoteException {
493 userId = handleIncomingUser(userId, "getOverlayInfosForTarget");
494 if (targetPackageName == null) {
495 return Collections.emptyList();
496 }
497
498 synchronized (mLock) {
499 return mImpl.getOverlayInfosForTarget(targetPackageName, userId);
500 }
501 }
502
503 @Override
504 public OverlayInfo getOverlayInfo(@Nullable final String packageName,
505 int userId) throws RemoteException {
506 userId = handleIncomingUser(userId, "getOverlayInfo");
507 if (packageName == null) {
508 return null;
509 }
510
511 synchronized (mLock) {
512 return mImpl.getOverlayInfo(packageName, userId);
513 }
514 }
515
516 @Override
517 public boolean setEnabled(@Nullable final String packageName, final boolean enable,
518 int userId) throws RemoteException {
519 enforceChangeOverlayPackagesPermission("setEnabled");
520 userId = handleIncomingUser(userId, "setEnabled");
521 if (packageName == null) {
522 return false;
523 }
524
525 final long ident = Binder.clearCallingIdentity();
526 try {
527 synchronized (mLock) {
528 return mImpl.setEnabled(packageName, enable, userId);
529 }
530 } finally {
531 Binder.restoreCallingIdentity(ident);
532 }
533 }
534
535 @Override
Jason Monk929ed8d2017-03-07 16:01:20 -0500536 public boolean setEnabledExclusive(@Nullable final String packageName, final boolean enable,
537 int userId) throws RemoteException {
538 enforceChangeOverlayPackagesPermission("setEnabled");
539 userId = handleIncomingUser(userId, "setEnabled");
Adam Lesinskic745f422017-04-05 16:31:30 -0700540 if (packageName == null || !enable) {
Jason Monk929ed8d2017-03-07 16:01:20 -0500541 return false;
542 }
543
544 final long ident = Binder.clearCallingIdentity();
545 try {
546 synchronized (mLock) {
Adrian Roosc84df772018-01-19 21:20:22 +0100547 return mImpl.setEnabledExclusive(packageName, false /* withinCategory */,
548 userId);
549 }
550 } finally {
551 Binder.restoreCallingIdentity(ident);
552 }
553 }
554
555 @Override
556 public boolean setEnabledExclusiveInCategory(@Nullable String packageName, int userId)
557 throws RemoteException {
558 enforceChangeOverlayPackagesPermission("setEnabled");
559 userId = handleIncomingUser(userId, "setEnabled");
560 if (packageName == null) {
561 return false;
562 }
563
564 final long ident = Binder.clearCallingIdentity();
565 try {
566 synchronized (mLock) {
567 return mImpl.setEnabledExclusive(packageName, true /* withinCategory */,
568 userId);
Jason Monk929ed8d2017-03-07 16:01:20 -0500569 }
570 } finally {
571 Binder.restoreCallingIdentity(ident);
572 }
573 }
574
575 @Override
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100576 public boolean setPriority(@Nullable final String packageName,
577 @Nullable final String parentPackageName, int userId) throws RemoteException {
578 enforceChangeOverlayPackagesPermission("setPriority");
579 userId = handleIncomingUser(userId, "setPriority");
580 if (packageName == null || parentPackageName == null) {
581 return false;
582 }
583
584 final long ident = Binder.clearCallingIdentity();
585 try {
586 synchronized (mLock) {
587 return mImpl.setPriority(packageName, parentPackageName, userId);
588 }
589 } finally {
590 Binder.restoreCallingIdentity(ident);
591 }
592 }
593
594 @Override
595 public boolean setHighestPriority(@Nullable final String packageName, int userId)
596 throws RemoteException {
597 enforceChangeOverlayPackagesPermission("setHighestPriority");
598 userId = handleIncomingUser(userId, "setHighestPriority");
599 if (packageName == null) {
600 return false;
601 }
602
603 final long ident = Binder.clearCallingIdentity();
604 try {
605 synchronized (mLock) {
606 return mImpl.setHighestPriority(packageName, userId);
607 }
608 } finally {
609 Binder.restoreCallingIdentity(ident);
610 }
611 }
612
613 @Override
614 public boolean setLowestPriority(@Nullable final String packageName, int userId)
615 throws RemoteException {
616 enforceChangeOverlayPackagesPermission("setLowestPriority");
617 userId = handleIncomingUser(userId, "setLowestPriority");
618 if (packageName == null) {
619 return false;
620 }
621
622 final long ident = Binder.clearCallingIdentity();
623 try {
624 synchronized (mLock) {
625 return mImpl.setLowestPriority(packageName, userId);
626 }
627 } finally {
628 Binder.restoreCallingIdentity(ident);
629 }
630 }
631
632 @Override
633 public void onShellCommand(@NonNull final FileDescriptor in,
634 @NonNull final FileDescriptor out, @NonNull final FileDescriptor err,
635 @NonNull final String[] args, @NonNull final ShellCallback callback,
636 @NonNull final ResultReceiver resultReceiver) {
637 (new OverlayManagerShellCommand(this)).exec(
638 this, in, out, err, args, callback, resultReceiver);
639 }
640
641 @Override
642 protected void dump(@NonNull final FileDescriptor fd, @NonNull final PrintWriter pw,
643 @NonNull final String[] argv) {
644 enforceDumpPermission("dump");
645
646 final boolean verbose = argv.length > 0 && "--verbose".equals(argv[0]);
647
648 synchronized (mLock) {
649 mImpl.onDump(pw);
650 mPackageManager.dump(pw, verbose);
651 }
652 }
653
654 /**
655 * Ensure that the caller has permission to interact with the given userId.
656 * If the calling user is not the same as the provided user, the caller needs
657 * to hold the INTERACT_ACROSS_USERS_FULL permission (or be system uid or
658 * root).
659 *
660 * @param userId the user to interact with
661 * @param message message for any SecurityException
662 */
663 private int handleIncomingUser(final int userId, @NonNull final String message) {
664 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
665 Binder.getCallingUid(), userId, false, true, message, null);
666 }
667
668 /**
669 * Enforce that the caller holds the CHANGE_OVERLAY_PACKAGES permission (or is
670 * system or root).
671 *
672 * @param message used as message if SecurityException is thrown
673 * @throws SecurityException if the permission check fails
674 */
675 private void enforceChangeOverlayPackagesPermission(@NonNull final String message) {
676 getContext().enforceCallingOrSelfPermission(
677 android.Manifest.permission.CHANGE_OVERLAY_PACKAGES, message);
678 }
679
680 /**
681 * Enforce that the caller holds the DUMP permission (or is system or root).
682 *
683 * @param message used as message if SecurityException is thrown
684 * @throws SecurityException if the permission check fails
685 */
686 private void enforceDumpPermission(@NonNull final String message) {
687 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
688 message);
689 }
690 };
691
Adam Lesinskic745f422017-04-05 16:31:30 -0700692 private final class OverlayChangeListener
693 implements OverlayManagerServiceImpl.OverlayChangeListener {
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100694 @Override
Adam Lesinskic745f422017-04-05 16:31:30 -0700695 public void onOverlaysChanged(@NonNull final String targetPackageName, final int userId) {
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100696 schedulePersistSettings();
Adam Lesinskic745f422017-04-05 16:31:30 -0700697 FgThread.getHandler().post(() -> {
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700698 updateAssets(userId, targetPackageName);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100699
Adam Lesinskic745f422017-04-05 16:31:30 -0700700 final Intent intent = new Intent(Intent.ACTION_OVERLAY_CHANGED,
701 Uri.fromParts("package", targetPackageName, null));
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100702 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinskic745f422017-04-05 16:31:30 -0700703
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100704 if (DEBUG) {
Adam Lesinskic745f422017-04-05 16:31:30 -0700705 Slog.d(TAG, "send broadcast " + intent);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100706 }
Adam Lesinskic745f422017-04-05 16:31:30 -0700707
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100708 try {
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200709 ActivityManager.getService().broadcastIntent(null, intent, null, null, 0,
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100710 null, null, null, android.app.AppOpsManager.OP_NONE, null, false, false,
711 userId);
712 } catch (RemoteException e) {
713 // Intentionally left empty.
714 }
Adam Lesinskic745f422017-04-05 16:31:30 -0700715 });
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100716 }
717 }
718
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700719 /**
720 * Updates the target packages' set of enabled overlays in PackageManager.
721 */
722 private void updateOverlayPaths(int userId, List<String> targetPackageNames) {
Adam Lesinskic745f422017-04-05 16:31:30 -0700723 if (DEBUG) {
724 Slog.d(TAG, "Updating overlay assets");
725 }
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200726 final PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
727 final boolean updateFrameworkRes = targetPackageNames.contains("android");
728 if (updateFrameworkRes) {
729 targetPackageNames = pm.getTargetPackageNames(userId);
730 }
731
732 final Map<String, List<String>> pendingChanges = new ArrayMap<>(targetPackageNames.size());
733 synchronized (mLock) {
Todd Kennedy560830c2017-06-16 13:55:13 -0700734 final List<String> frameworkOverlays =
735 mImpl.getEnabledOverlayPackageNames("android", userId);
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200736 final int N = targetPackageNames.size();
737 for (int i = 0; i < N; i++) {
738 final String targetPackageName = targetPackageNames.get(i);
Todd Kennedy560830c2017-06-16 13:55:13 -0700739 List<String> list = new ArrayList<>();
740 if (!"android".equals(targetPackageName)) {
741 list.addAll(frameworkOverlays);
742 }
743 list.addAll(mImpl.getEnabledOverlayPackageNames(targetPackageName, userId));
744 pendingChanges.put(targetPackageName, list);
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200745 }
746 }
747
748 final int N = targetPackageNames.size();
749 for (int i = 0; i < N; i++) {
750 final String targetPackageName = targetPackageNames.get(i);
Adam Lesinskic745f422017-04-05 16:31:30 -0700751 if (DEBUG) {
752 Slog.d(TAG, "-> Updating overlay: target=" + targetPackageName + " overlays=["
753 + TextUtils.join(",", pendingChanges.get(targetPackageName))
754 + "] userId=" + userId);
755 }
756
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200757 if (!pm.setEnabledOverlayPackages(
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700758 userId, targetPackageName, pendingChanges.get(targetPackageName))) {
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200759 Slog.e(TAG, String.format("Failed to change enabled overlays for %s user %d",
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700760 targetPackageName, userId));
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200761 }
762 }
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700763 }
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200764
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700765 private void updateAssets(final int userId, final String targetPackageName) {
766 updateAssets(userId, Collections.singletonList(targetPackageName));
767 }
768
769 private void updateAssets(final int userId, List<String> targetPackageNames) {
770 updateOverlayPaths(userId, targetPackageNames);
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200771 final IActivityManager am = ActivityManager.getService();
772 try {
773 am.scheduleApplicationInfoChanged(targetPackageNames, userId);
774 } catch (RemoteException e) {
775 // Intentionally left empty.
776 }
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100777 }
778
779 private void schedulePersistSettings() {
780 if (mPersistSettingsScheduled.getAndSet(true)) {
781 return;
782 }
Adam Lesinskic745f422017-04-05 16:31:30 -0700783 IoThread.getHandler().post(() -> {
784 mPersistSettingsScheduled.set(false);
785 if (DEBUG) {
786 Slog.d(TAG, "Writing overlay settings");
787 }
788 synchronized (mLock) {
789 FileOutputStream stream = null;
790 try {
791 stream = mSettingsFile.startWrite();
792 mSettings.persist(stream);
793 mSettingsFile.finishWrite(stream);
794 } catch (IOException | XmlPullParserException e) {
795 mSettingsFile.failWrite(stream);
796 Slog.e(TAG, "failed to persist overlay state", e);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100797 }
798 }
799 });
800 }
801
802 private void restoreSettings() {
803 synchronized (mLock) {
804 if (!mSettingsFile.getBaseFile().exists()) {
805 return;
806 }
807 try (final FileInputStream stream = mSettingsFile.openRead()) {
808 mSettings.restore(stream);
809
810 // We might have data for dying users if the device was
811 // restarted before we received USER_REMOVED. Remove data for
812 // users that will not exist after the system is ready.
813
Adam Lesinskid11c5512017-04-11 12:01:10 -0700814 final List<UserInfo> liveUsers = mUserManager.getUsers(true /*excludeDying*/);
815 final int[] liveUserIds = new int[liveUsers.size()];
816 for (int i = 0; i < liveUsers.size(); i++) {
817 liveUserIds[i] = liveUsers.get(i).getUserHandle().getIdentifier();
818 }
819 Arrays.sort(liveUserIds);
820
821 for (int userId : mSettings.getUsers()) {
822 if (Arrays.binarySearch(liveUserIds, userId) < 0) {
823 mSettings.removeUser(userId);
824 }
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100825 }
826 } catch (IOException | XmlPullParserException e) {
827 Slog.e(TAG, "failed to restore overlay state", e);
828 }
829 }
830 }
831
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100832 private static final class PackageManagerHelper implements
833 OverlayManagerServiceImpl.PackageManagerHelper {
834
835 private final IPackageManager mPackageManager;
836 private final PackageManagerInternal mPackageManagerInternal;
837
838 // Use a cache for performance and for consistency within OMS: because
839 // additional PACKAGE_* intents may be delivered while we process an
840 // intent, querying the PackageManagerService for the actual current
841 // state may lead to contradictions within OMS. Better then to lag
842 // behind until all pending intents have been processed.
843 private final SparseArray<HashMap<String, PackageInfo>> mCache = new SparseArray<>();
844
845 PackageManagerHelper() {
846 mPackageManager = getPackageManager();
847 mPackageManagerInternal = LocalServices.getService(PackageManagerInternal.class);
848 }
849
850 public PackageInfo getPackageInfo(@NonNull final String packageName, final int userId,
851 final boolean useCache) {
852 if (useCache) {
853 final PackageInfo cachedPi = getCachedPackageInfo(packageName, userId);
854 if (cachedPi != null) {
855 return cachedPi;
856 }
857 }
858 try {
859 final PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0, userId);
860 if (useCache && pi != null) {
861 cachePackageInfo(packageName, userId, pi);
862 }
863 return pi;
864 } catch (RemoteException e) {
865 // Intentionally left empty.
866 }
867 return null;
868 }
869
870 @Override
871 public PackageInfo getPackageInfo(@NonNull final String packageName, final int userId) {
872 return getPackageInfo(packageName, userId, true);
873 }
874
875 @Override
876 public boolean signaturesMatching(@NonNull final String packageName1,
877 @NonNull final String packageName2, final int userId) {
878 // The package manager does not support different versions of packages
879 // to be installed for different users: ignore userId for now.
880 try {
Adam Lesinskic745f422017-04-05 16:31:30 -0700881 return mPackageManager.checkSignatures(
882 packageName1, packageName2) == SIGNATURE_MATCH;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100883 } catch (RemoteException e) {
884 // Intentionally left blank
885 }
886 return false;
887 }
888
889 @Override
890 public List<PackageInfo> getOverlayPackages(final int userId) {
891 return mPackageManagerInternal.getOverlayPackages(userId);
892 }
893
894 public PackageInfo getCachedPackageInfo(@NonNull final String packageName,
895 final int userId) {
896 final HashMap<String, PackageInfo> map = mCache.get(userId);
897 return map == null ? null : map.get(packageName);
898 }
899
900 public void cachePackageInfo(@NonNull final String packageName, final int userId,
901 @NonNull final PackageInfo pi) {
902 HashMap<String, PackageInfo> map = mCache.get(userId);
903 if (map == null) {
904 map = new HashMap<>();
905 mCache.put(userId, map);
906 }
907 map.put(packageName, pi);
908 }
909
910 public void forgetPackageInfo(@NonNull final String packageName, final int userId) {
911 final HashMap<String, PackageInfo> map = mCache.get(userId);
912 if (map == null) {
913 return;
914 }
915 map.remove(packageName);
916 if (map.isEmpty()) {
917 mCache.delete(userId);
918 }
919 }
920
921 public void forgetAllPackageInfos(final int userId) {
922 mCache.delete(userId);
923 }
924
925 private static final String TAB1 = " ";
926 private static final String TAB2 = TAB1 + TAB1;
927
928 public void dump(@NonNull final PrintWriter pw, final boolean verbose) {
929 pw.println("PackageInfo cache");
930
931 if (!verbose) {
932 int count = 0;
933 final int N = mCache.size();
934 for (int i = 0; i < N; i++) {
935 final int userId = mCache.keyAt(i);
936 count += mCache.get(userId).size();
937 }
938 pw.println(TAB1 + count + " package(s)");
939 return;
940 }
941
942 if (mCache.size() == 0) {
943 pw.println(TAB1 + "<empty>");
944 return;
945 }
946
947 final int N = mCache.size();
948 for (int i = 0; i < N; i++) {
949 final int userId = mCache.keyAt(i);
950 pw.println(TAB1 + "User " + userId);
951 final HashMap<String, PackageInfo> map = mCache.get(userId);
952 for (Map.Entry<String, PackageInfo> entry : map.entrySet()) {
953 pw.println(TAB2 + entry.getKey() + ": " + entry.getValue());
954 }
955 }
956 }
957 }
958}