blob: 4bc4a7ecc055c3d8c28a7fcaea98963ad07c0ea4 [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) {
Adam Lesinskic745f422017-04-05 16:31:30 -0700547 return mImpl.setEnabledExclusive(packageName, userId);
Jason Monk929ed8d2017-03-07 16:01:20 -0500548 }
549 } finally {
550 Binder.restoreCallingIdentity(ident);
551 }
552 }
553
554 @Override
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100555 public boolean setPriority(@Nullable final String packageName,
556 @Nullable final String parentPackageName, int userId) throws RemoteException {
557 enforceChangeOverlayPackagesPermission("setPriority");
558 userId = handleIncomingUser(userId, "setPriority");
559 if (packageName == null || parentPackageName == null) {
560 return false;
561 }
562
563 final long ident = Binder.clearCallingIdentity();
564 try {
565 synchronized (mLock) {
566 return mImpl.setPriority(packageName, parentPackageName, userId);
567 }
568 } finally {
569 Binder.restoreCallingIdentity(ident);
570 }
571 }
572
573 @Override
574 public boolean setHighestPriority(@Nullable final String packageName, int userId)
575 throws RemoteException {
576 enforceChangeOverlayPackagesPermission("setHighestPriority");
577 userId = handleIncomingUser(userId, "setHighestPriority");
578 if (packageName == null) {
579 return false;
580 }
581
582 final long ident = Binder.clearCallingIdentity();
583 try {
584 synchronized (mLock) {
585 return mImpl.setHighestPriority(packageName, userId);
586 }
587 } finally {
588 Binder.restoreCallingIdentity(ident);
589 }
590 }
591
592 @Override
593 public boolean setLowestPriority(@Nullable final String packageName, int userId)
594 throws RemoteException {
595 enforceChangeOverlayPackagesPermission("setLowestPriority");
596 userId = handleIncomingUser(userId, "setLowestPriority");
597 if (packageName == null) {
598 return false;
599 }
600
601 final long ident = Binder.clearCallingIdentity();
602 try {
603 synchronized (mLock) {
604 return mImpl.setLowestPriority(packageName, userId);
605 }
606 } finally {
607 Binder.restoreCallingIdentity(ident);
608 }
609 }
610
611 @Override
612 public void onShellCommand(@NonNull final FileDescriptor in,
613 @NonNull final FileDescriptor out, @NonNull final FileDescriptor err,
614 @NonNull final String[] args, @NonNull final ShellCallback callback,
615 @NonNull final ResultReceiver resultReceiver) {
616 (new OverlayManagerShellCommand(this)).exec(
617 this, in, out, err, args, callback, resultReceiver);
618 }
619
620 @Override
621 protected void dump(@NonNull final FileDescriptor fd, @NonNull final PrintWriter pw,
622 @NonNull final String[] argv) {
623 enforceDumpPermission("dump");
624
625 final boolean verbose = argv.length > 0 && "--verbose".equals(argv[0]);
626
627 synchronized (mLock) {
628 mImpl.onDump(pw);
629 mPackageManager.dump(pw, verbose);
630 }
631 }
632
633 /**
634 * Ensure that the caller has permission to interact with the given userId.
635 * If the calling user is not the same as the provided user, the caller needs
636 * to hold the INTERACT_ACROSS_USERS_FULL permission (or be system uid or
637 * root).
638 *
639 * @param userId the user to interact with
640 * @param message message for any SecurityException
641 */
642 private int handleIncomingUser(final int userId, @NonNull final String message) {
643 return ActivityManager.handleIncomingUser(Binder.getCallingPid(),
644 Binder.getCallingUid(), userId, false, true, message, null);
645 }
646
647 /**
648 * Enforce that the caller holds the CHANGE_OVERLAY_PACKAGES permission (or is
649 * system or root).
650 *
651 * @param message used as message if SecurityException is thrown
652 * @throws SecurityException if the permission check fails
653 */
654 private void enforceChangeOverlayPackagesPermission(@NonNull final String message) {
655 getContext().enforceCallingOrSelfPermission(
656 android.Manifest.permission.CHANGE_OVERLAY_PACKAGES, message);
657 }
658
659 /**
660 * Enforce that the caller holds the DUMP permission (or is system or root).
661 *
662 * @param message used as message if SecurityException is thrown
663 * @throws SecurityException if the permission check fails
664 */
665 private void enforceDumpPermission(@NonNull final String message) {
666 getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
667 message);
668 }
669 };
670
Adam Lesinskic745f422017-04-05 16:31:30 -0700671 private final class OverlayChangeListener
672 implements OverlayManagerServiceImpl.OverlayChangeListener {
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100673 @Override
Adam Lesinskic745f422017-04-05 16:31:30 -0700674 public void onOverlaysChanged(@NonNull final String targetPackageName, final int userId) {
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100675 schedulePersistSettings();
Adam Lesinskic745f422017-04-05 16:31:30 -0700676 FgThread.getHandler().post(() -> {
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700677 updateAssets(userId, targetPackageName);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100678
Adam Lesinskic745f422017-04-05 16:31:30 -0700679 final Intent intent = new Intent(Intent.ACTION_OVERLAY_CHANGED,
680 Uri.fromParts("package", targetPackageName, null));
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100681 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Adam Lesinskic745f422017-04-05 16:31:30 -0700682
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100683 if (DEBUG) {
Adam Lesinskic745f422017-04-05 16:31:30 -0700684 Slog.d(TAG, "send broadcast " + intent);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100685 }
Adam Lesinskic745f422017-04-05 16:31:30 -0700686
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100687 try {
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200688 ActivityManager.getService().broadcastIntent(null, intent, null, null, 0,
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100689 null, null, null, android.app.AppOpsManager.OP_NONE, null, false, false,
690 userId);
691 } catch (RemoteException e) {
692 // Intentionally left empty.
693 }
Adam Lesinskic745f422017-04-05 16:31:30 -0700694 });
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100695 }
696 }
697
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700698 /**
699 * Updates the target packages' set of enabled overlays in PackageManager.
700 */
701 private void updateOverlayPaths(int userId, List<String> targetPackageNames) {
Adam Lesinskic745f422017-04-05 16:31:30 -0700702 if (DEBUG) {
703 Slog.d(TAG, "Updating overlay assets");
704 }
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200705 final PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
706 final boolean updateFrameworkRes = targetPackageNames.contains("android");
707 if (updateFrameworkRes) {
708 targetPackageNames = pm.getTargetPackageNames(userId);
709 }
710
711 final Map<String, List<String>> pendingChanges = new ArrayMap<>(targetPackageNames.size());
712 synchronized (mLock) {
Todd Kennedy560830c2017-06-16 13:55:13 -0700713 final List<String> frameworkOverlays =
714 mImpl.getEnabledOverlayPackageNames("android", userId);
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200715 final int N = targetPackageNames.size();
716 for (int i = 0; i < N; i++) {
717 final String targetPackageName = targetPackageNames.get(i);
Todd Kennedy560830c2017-06-16 13:55:13 -0700718 List<String> list = new ArrayList<>();
719 if (!"android".equals(targetPackageName)) {
720 list.addAll(frameworkOverlays);
721 }
722 list.addAll(mImpl.getEnabledOverlayPackageNames(targetPackageName, userId));
723 pendingChanges.put(targetPackageName, list);
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200724 }
725 }
726
727 final int N = targetPackageNames.size();
728 for (int i = 0; i < N; i++) {
729 final String targetPackageName = targetPackageNames.get(i);
Adam Lesinskic745f422017-04-05 16:31:30 -0700730 if (DEBUG) {
731 Slog.d(TAG, "-> Updating overlay: target=" + targetPackageName + " overlays=["
732 + TextUtils.join(",", pendingChanges.get(targetPackageName))
733 + "] userId=" + userId);
734 }
735
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200736 if (!pm.setEnabledOverlayPackages(
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700737 userId, targetPackageName, pendingChanges.get(targetPackageName))) {
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200738 Slog.e(TAG, String.format("Failed to change enabled overlays for %s user %d",
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700739 targetPackageName, userId));
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200740 }
741 }
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700742 }
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200743
Adam Lesinskiada8deb2017-05-12 13:50:42 -0700744 private void updateAssets(final int userId, final String targetPackageName) {
745 updateAssets(userId, Collections.singletonList(targetPackageName));
746 }
747
748 private void updateAssets(final int userId, List<String> targetPackageNames) {
749 updateOverlayPaths(userId, targetPackageNames);
Mårten Kongstad2e0d0f32016-06-02 09:35:31 +0200750 final IActivityManager am = ActivityManager.getService();
751 try {
752 am.scheduleApplicationInfoChanged(targetPackageNames, userId);
753 } catch (RemoteException e) {
754 // Intentionally left empty.
755 }
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100756 }
757
758 private void schedulePersistSettings() {
759 if (mPersistSettingsScheduled.getAndSet(true)) {
760 return;
761 }
Adam Lesinskic745f422017-04-05 16:31:30 -0700762 IoThread.getHandler().post(() -> {
763 mPersistSettingsScheduled.set(false);
764 if (DEBUG) {
765 Slog.d(TAG, "Writing overlay settings");
766 }
767 synchronized (mLock) {
768 FileOutputStream stream = null;
769 try {
770 stream = mSettingsFile.startWrite();
771 mSettings.persist(stream);
772 mSettingsFile.finishWrite(stream);
773 } catch (IOException | XmlPullParserException e) {
774 mSettingsFile.failWrite(stream);
775 Slog.e(TAG, "failed to persist overlay state", e);
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100776 }
777 }
778 });
779 }
780
781 private void restoreSettings() {
782 synchronized (mLock) {
783 if (!mSettingsFile.getBaseFile().exists()) {
784 return;
785 }
786 try (final FileInputStream stream = mSettingsFile.openRead()) {
787 mSettings.restore(stream);
788
789 // We might have data for dying users if the device was
790 // restarted before we received USER_REMOVED. Remove data for
791 // users that will not exist after the system is ready.
792
Adam Lesinskid11c5512017-04-11 12:01:10 -0700793 final List<UserInfo> liveUsers = mUserManager.getUsers(true /*excludeDying*/);
794 final int[] liveUserIds = new int[liveUsers.size()];
795 for (int i = 0; i < liveUsers.size(); i++) {
796 liveUserIds[i] = liveUsers.get(i).getUserHandle().getIdentifier();
797 }
798 Arrays.sort(liveUserIds);
799
800 for (int userId : mSettings.getUsers()) {
801 if (Arrays.binarySearch(liveUserIds, userId) < 0) {
802 mSettings.removeUser(userId);
803 }
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100804 }
805 } catch (IOException | XmlPullParserException e) {
806 Slog.e(TAG, "failed to restore overlay state", e);
807 }
808 }
809 }
810
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100811 private static final class PackageManagerHelper implements
812 OverlayManagerServiceImpl.PackageManagerHelper {
813
814 private final IPackageManager mPackageManager;
815 private final PackageManagerInternal mPackageManagerInternal;
816
817 // Use a cache for performance and for consistency within OMS: because
818 // additional PACKAGE_* intents may be delivered while we process an
819 // intent, querying the PackageManagerService for the actual current
820 // state may lead to contradictions within OMS. Better then to lag
821 // behind until all pending intents have been processed.
822 private final SparseArray<HashMap<String, PackageInfo>> mCache = new SparseArray<>();
823
824 PackageManagerHelper() {
825 mPackageManager = getPackageManager();
826 mPackageManagerInternal = LocalServices.getService(PackageManagerInternal.class);
827 }
828
829 public PackageInfo getPackageInfo(@NonNull final String packageName, final int userId,
830 final boolean useCache) {
831 if (useCache) {
832 final PackageInfo cachedPi = getCachedPackageInfo(packageName, userId);
833 if (cachedPi != null) {
834 return cachedPi;
835 }
836 }
837 try {
838 final PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0, userId);
839 if (useCache && pi != null) {
840 cachePackageInfo(packageName, userId, pi);
841 }
842 return pi;
843 } catch (RemoteException e) {
844 // Intentionally left empty.
845 }
846 return null;
847 }
848
849 @Override
850 public PackageInfo getPackageInfo(@NonNull final String packageName, final int userId) {
851 return getPackageInfo(packageName, userId, true);
852 }
853
854 @Override
855 public boolean signaturesMatching(@NonNull final String packageName1,
856 @NonNull final String packageName2, final int userId) {
857 // The package manager does not support different versions of packages
858 // to be installed for different users: ignore userId for now.
859 try {
Adam Lesinskic745f422017-04-05 16:31:30 -0700860 return mPackageManager.checkSignatures(
861 packageName1, packageName2) == SIGNATURE_MATCH;
Mårten Kongstadeabc9e92015-12-15 16:40:23 +0100862 } catch (RemoteException e) {
863 // Intentionally left blank
864 }
865 return false;
866 }
867
868 @Override
869 public List<PackageInfo> getOverlayPackages(final int userId) {
870 return mPackageManagerInternal.getOverlayPackages(userId);
871 }
872
873 public PackageInfo getCachedPackageInfo(@NonNull final String packageName,
874 final int userId) {
875 final HashMap<String, PackageInfo> map = mCache.get(userId);
876 return map == null ? null : map.get(packageName);
877 }
878
879 public void cachePackageInfo(@NonNull final String packageName, final int userId,
880 @NonNull final PackageInfo pi) {
881 HashMap<String, PackageInfo> map = mCache.get(userId);
882 if (map == null) {
883 map = new HashMap<>();
884 mCache.put(userId, map);
885 }
886 map.put(packageName, pi);
887 }
888
889 public void forgetPackageInfo(@NonNull final String packageName, final int userId) {
890 final HashMap<String, PackageInfo> map = mCache.get(userId);
891 if (map == null) {
892 return;
893 }
894 map.remove(packageName);
895 if (map.isEmpty()) {
896 mCache.delete(userId);
897 }
898 }
899
900 public void forgetAllPackageInfos(final int userId) {
901 mCache.delete(userId);
902 }
903
904 private static final String TAB1 = " ";
905 private static final String TAB2 = TAB1 + TAB1;
906
907 public void dump(@NonNull final PrintWriter pw, final boolean verbose) {
908 pw.println("PackageInfo cache");
909
910 if (!verbose) {
911 int count = 0;
912 final int N = mCache.size();
913 for (int i = 0; i < N; i++) {
914 final int userId = mCache.keyAt(i);
915 count += mCache.get(userId).size();
916 }
917 pw.println(TAB1 + count + " package(s)");
918 return;
919 }
920
921 if (mCache.size() == 0) {
922 pw.println(TAB1 + "<empty>");
923 return;
924 }
925
926 final int N = mCache.size();
927 for (int i = 0; i < N; i++) {
928 final int userId = mCache.keyAt(i);
929 pw.println(TAB1 + "User " + userId);
930 final HashMap<String, PackageInfo> map = mCache.get(userId);
931 for (Map.Entry<String, PackageInfo> entry : map.entrySet()) {
932 pw.println(TAB2 + entry.getKey() + ": " + entry.getValue());
933 }
934 }
935 }
936 }
937}