blob: 73a365b0da7216a0e46b816e969c3265f53e728e [file] [log] [blame]
John Spurlock7340fc82014-04-24 18:50:12 -04001/**
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.notification;
18
Felipe Lemea1b79bf2016-05-24 13:06:54 -070019import static android.content.Context.BIND_ALLOW_WHITELIST_MANAGEMENT;
20import static android.content.Context.BIND_AUTO_CREATE;
21import static android.content.Context.BIND_FOREGROUND_SERVICE;
Esteban Talavera9c6458d2017-03-30 17:59:50 +010022import static android.content.Context.DEVICE_POLICY_SERVICE;
Felipe Lemea1b79bf2016-05-24 13:06:54 -070023
Ruben Brunke24b9a62016-02-16 21:38:24 -080024import android.annotation.NonNull;
John Spurlock7340fc82014-04-24 18:50:12 -040025import android.app.ActivityManager;
26import android.app.PendingIntent;
Esteban Talavera9c6458d2017-03-30 17:59:50 +010027import android.app.admin.DevicePolicyManager;
Christopher Tate6597e342015-02-17 12:15:25 -080028import android.content.BroadcastReceiver;
John Spurlock7340fc82014-04-24 18:50:12 -040029import android.content.ComponentName;
30import android.content.ContentResolver;
31import android.content.Context;
32import android.content.Intent;
Christopher Tate6597e342015-02-17 12:15:25 -080033import android.content.IntentFilter;
John Spurlock7340fc82014-04-24 18:50:12 -040034import android.content.ServiceConnection;
35import android.content.pm.ApplicationInfo;
Julia Reynoldsa75c7522017-03-21 17:34:25 -040036import android.content.pm.IPackageManager;
John Spurlock7340fc82014-04-24 18:50:12 -040037import android.content.pm.PackageManager;
38import android.content.pm.PackageManager.NameNotFoundException;
39import android.content.pm.ResolveInfo;
40import android.content.pm.ServiceInfo;
41import android.content.pm.UserInfo;
42import android.database.ContentObserver;
43import android.net.Uri;
Esteban Talavera9c6458d2017-03-30 17:59:50 +010044import android.os.Binder;
John Spurlock7340fc82014-04-24 18:50:12 -040045import android.os.Build;
46import android.os.Handler;
47import android.os.IBinder;
48import android.os.IInterface;
49import android.os.RemoteException;
Julia Reynoldsa75c7522017-03-21 17:34:25 -040050import android.os.ServiceManager;
John Spurlock7340fc82014-04-24 18:50:12 -040051import android.os.UserHandle;
52import android.os.UserManager;
53import android.provider.Settings;
54import android.text.TextUtils;
55import android.util.ArraySet;
John Spurlock4db0d982014-08-13 09:19:03 -040056import android.util.Log;
John Spurlock7340fc82014-04-24 18:50:12 -040057import android.util.Slog;
58import android.util.SparseArray;
59
John Spurlock25e2d242014-06-27 13:58:23 -040060import com.android.server.notification.NotificationManagerService.DumpFilter;
61
John Spurlock7340fc82014-04-24 18:50:12 -040062import java.io.PrintWriter;
63import java.util.ArrayList;
John Spurlocke77bb362014-04-26 10:24:59 -040064import java.util.Arrays;
Julia Reynolds9a86cc02016-02-10 15:38:15 -050065import java.util.HashSet;
John Spurlock7340fc82014-04-24 18:50:12 -040066import java.util.List;
Christopher Tate6597e342015-02-17 12:15:25 -080067import java.util.Objects;
John Spurlock7340fc82014-04-24 18:50:12 -040068import java.util.Set;
69
70/**
71 * Manages the lifecycle of application-provided services bound by system server.
72 *
73 * Services managed by this helper must have:
74 * - An associated system settings value with a list of enabled component names.
75 * - A well-known action for services to use in their intent-filter.
76 * - A system permission for services to require in order to ensure system has exclusive binding.
77 * - A settings page for user configuration of enabled services, and associated intent action.
78 * - A remote interface definition (aidl) provided by the service used for communication.
79 */
80abstract public class ManagedServices {
81 protected final String TAG = getClass().getSimpleName();
John Spurlock4db0d982014-08-13 09:19:03 -040082 protected final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
John Spurlock7340fc82014-04-24 18:50:12 -040083
Julia Reynoldsc279b992015-10-30 08:23:51 -040084 protected static final String ENABLED_SERVICES_SEPARATOR = ":";
John Spurlock7340fc82014-04-24 18:50:12 -040085
John Spurlockaf8d6c42014-05-07 17:49:08 -040086 protected final Context mContext;
John Spurlocke77bb362014-04-26 10:24:59 -040087 protected final Object mMutex;
John Spurlock7340fc82014-04-24 18:50:12 -040088 private final UserProfiles mUserProfiles;
89 private final SettingsObserver mSettingsObserver;
Julia Reynoldsa75c7522017-03-21 17:34:25 -040090 private final IPackageManager mPm;
John Spurlock7340fc82014-04-24 18:50:12 -040091 private final Config mConfig;
Christopher Tate6597e342015-02-17 12:15:25 -080092 private ArraySet<String> mRestored;
John Spurlock7340fc82014-04-24 18:50:12 -040093
94 // contains connections to all connected services, including app services
95 // and system services
Julia Reynolds00314d92017-04-14 10:01:24 -040096 private final ArrayList<ManagedServiceInfo> mServices = new ArrayList<ManagedServiceInfo>();
John Spurlock7340fc82014-04-24 18:50:12 -040097 // things that will be put into mServices as soon as they're ready
98 private final ArrayList<String> mServicesBinding = new ArrayList<String>();
Chris Wrenab41eec2016-01-04 18:01:27 -050099 // lists the component names of all enabled (and therefore potentially connected)
John Spurlock7340fc82014-04-24 18:50:12 -0400100 // app services for current profiles.
101 private ArraySet<ComponentName> mEnabledServicesForCurrentProfiles
102 = new ArraySet<ComponentName>();
103 // Just the packages from mEnabledServicesForCurrentProfiles
104 private ArraySet<String> mEnabledServicesPackageNames = new ArraySet<String>();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200105 // List of packages in restored setting across all mUserProfiles, for quick
106 // filtering upon package updates.
107 private ArraySet<String> mRestoredPackages = new ArraySet<>();
Chris Wrenab41eec2016-01-04 18:01:27 -0500108 // List of enabled packages that have nevertheless asked not to be run
109 private ArraySet<ComponentName> mSnoozingForCurrentProfiles = new ArraySet<>();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200110
John Spurlock7340fc82014-04-24 18:50:12 -0400111
Christoph Studerb53dfd42014-09-12 14:45:59 +0200112 // Kept to de-dupe user change events (experienced after boot, when we receive a settings and a
113 // user change).
114 private int[] mLastSeenProfileIds;
115
Christopher Tate6597e342015-02-17 12:15:25 -0800116 private final BroadcastReceiver mRestoreReceiver;
117
John Spurlock7340fc82014-04-24 18:50:12 -0400118 public ManagedServices(Context context, Handler handler, Object mutex,
119 UserProfiles userProfiles) {
120 mContext = context;
121 mMutex = mutex;
122 mUserProfiles = userProfiles;
Julia Reynoldsa75c7522017-03-21 17:34:25 -0400123 mPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
John Spurlock7340fc82014-04-24 18:50:12 -0400124 mConfig = getConfig();
125 mSettingsObserver = new SettingsObserver(handler);
Christopher Tate6597e342015-02-17 12:15:25 -0800126
127 mRestoreReceiver = new SettingRestoredReceiver();
128 IntentFilter filter = new IntentFilter(Intent.ACTION_SETTING_RESTORED);
129 context.registerReceiver(mRestoreReceiver, filter);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200130 rebuildRestoredPackages();
Christopher Tate6597e342015-02-17 12:15:25 -0800131 }
132
133 class SettingRestoredReceiver extends BroadcastReceiver {
134 @Override
135 public void onReceive(Context context, Intent intent) {
136 if (Intent.ACTION_SETTING_RESTORED.equals(intent.getAction())) {
137 String element = intent.getStringExtra(Intent.EXTRA_SETTING_NAME);
Julia Reynolds6e839b02016-04-13 10:01:17 -0400138 if (Objects.equals(element, mConfig.secureSettingName)
139 || Objects.equals(element, mConfig.secondarySettingName)) {
Christopher Tate6597e342015-02-17 12:15:25 -0800140 String prevValue = intent.getStringExtra(Intent.EXTRA_SETTING_PREVIOUS_VALUE);
141 String newValue = intent.getStringExtra(Intent.EXTRA_SETTING_NEW_VALUE);
142 settingRestored(element, prevValue, newValue, getSendingUserId());
143 }
144 }
145 }
John Spurlock7340fc82014-04-24 18:50:12 -0400146 }
147
148 abstract protected Config getConfig();
149
150 private String getCaption() {
151 return mConfig.caption;
152 }
153
154 abstract protected IInterface asInterface(IBinder binder);
155
Chris Wren51017d02015-12-15 15:34:46 -0500156 abstract protected boolean checkType(IInterface service);
157
John Spurlock3b98b3f2014-05-01 09:08:48 -0400158 abstract protected void onServiceAdded(ManagedServiceInfo info);
John Spurlock7340fc82014-04-24 18:50:12 -0400159
Julia Reynolds73ed76b2017-04-04 17:04:38 -0400160 protected List<ManagedServiceInfo> getServices() {
161 synchronized (mMutex) {
162 List<ManagedServiceInfo> services = new ArrayList<>(mServices);
163 return services;
164 }
165 }
166
John Spurlocke77bb362014-04-26 10:24:59 -0400167 protected void onServiceRemovedLocked(ManagedServiceInfo removed) { }
168
John Spurlock7340fc82014-04-24 18:50:12 -0400169 private ManagedServiceInfo newServiceInfo(IInterface service,
170 ComponentName component, int userid, boolean isSystem, ServiceConnection connection,
171 int targetSdkVersion) {
172 return new ManagedServiceInfo(service, component, userid, isSystem, connection,
173 targetSdkVersion);
174 }
175
176 public void onBootPhaseAppsCanStart() {
177 mSettingsObserver.observe();
178 }
179
John Spurlock25e2d242014-06-27 13:58:23 -0400180 public void dump(PrintWriter pw, DumpFilter filter) {
John Spurlocke77bb362014-04-26 10:24:59 -0400181 pw.println(" All " + getCaption() + "s (" + mEnabledServicesForCurrentProfiles.size()
John Spurlock7340fc82014-04-24 18:50:12 -0400182 + ") enabled for current profiles:");
183 for (ComponentName cmpt : mEnabledServicesForCurrentProfiles) {
John Spurlock25e2d242014-06-27 13:58:23 -0400184 if (filter != null && !filter.matches(cmpt)) continue;
John Spurlocke77bb362014-04-26 10:24:59 -0400185 pw.println(" " + cmpt);
John Spurlock7340fc82014-04-24 18:50:12 -0400186 }
187
John Spurlocke77bb362014-04-26 10:24:59 -0400188 pw.println(" Live " + getCaption() + "s (" + mServices.size() + "):");
John Spurlock7340fc82014-04-24 18:50:12 -0400189 for (ManagedServiceInfo info : mServices) {
John Spurlock25e2d242014-06-27 13:58:23 -0400190 if (filter != null && !filter.matches(info.component)) continue;
John Spurlocke77bb362014-04-26 10:24:59 -0400191 pw.println(" " + info.component
John Spurlock7340fc82014-04-24 18:50:12 -0400192 + " (user " + info.userid + "): " + info.service
Chris Wren51017d02015-12-15 15:34:46 -0500193 + (info.isSystem?" SYSTEM":"")
194 + (info.isGuest(this)?" GUEST":""));
John Spurlock7340fc82014-04-24 18:50:12 -0400195 }
Chris Wrenab41eec2016-01-04 18:01:27 -0500196
197 pw.println(" Snoozed " + getCaption() + "s (" +
198 mSnoozingForCurrentProfiles.size() + "):");
199 for (ComponentName name : mSnoozingForCurrentProfiles) {
200 pw.println(" " + name.flattenToShortString());
201 }
John Spurlock7340fc82014-04-24 18:50:12 -0400202 }
203
Christopher Tate6597e342015-02-17 12:15:25 -0800204 // By convention, restored settings are replicated to another settings
205 // entry, named similarly but with a disambiguation suffix.
Julia Reynolds6e839b02016-04-13 10:01:17 -0400206 public static String restoredSettingName(String setting) {
207 return setting + ":restored";
Christopher Tate6597e342015-02-17 12:15:25 -0800208 }
209
210 // The OS has done a restore of this service's saved state. We clone it to the
211 // 'restored' reserve, and then once we return and the actual write to settings is
212 // performed, our observer will do the work of maintaining the restored vs live
213 // settings data.
214 public void settingRestored(String element, String oldValue, String newValue, int userid) {
215 if (DEBUG) Slog.d(TAG, "Restored managed service setting: " + element
216 + " ovalue=" + oldValue + " nvalue=" + newValue);
Julia Reynolds6e839b02016-04-13 10:01:17 -0400217 if (mConfig.secureSettingName.equals(element) ||
218 mConfig.secondarySettingName.equals(element)) {
Christopher Tate6597e342015-02-17 12:15:25 -0800219 if (element != null) {
Christopher Tate6597e342015-02-17 12:15:25 -0800220 Settings.Secure.putStringForUser(mContext.getContentResolver(),
Julia Reynolds6e839b02016-04-13 10:01:17 -0400221 restoredSettingName(element),
Christopher Tate6597e342015-02-17 12:15:25 -0800222 newValue,
223 userid);
Julia Reynolds5ddacf22017-05-30 15:36:49 -0400224 if (mConfig.secureSettingName.equals(element)) {
225 updateSettingsAccordingToInstalledServices(element, userid);
226 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200227 rebuildRestoredPackages();
Christopher Tate6597e342015-02-17 12:15:25 -0800228 }
229 }
230 }
231
John Spurlock80774932015-05-07 17:38:50 -0400232 public boolean isComponentEnabledForPackage(String pkg) {
233 return mEnabledServicesPackageNames.contains(pkg);
234 }
235
Julia Reynolds6434eb22016-08-08 17:19:26 -0400236 public void onPackagesChanged(boolean removingPackage, String[] pkgList) {
237 if (DEBUG) Slog.d(TAG, "onPackagesChanged removingPackage=" + removingPackage
John Spurlocke77bb362014-04-26 10:24:59 -0400238 + " pkgList=" + (pkgList == null ? null : Arrays.asList(pkgList))
239 + " mEnabledServicesPackageNames=" + mEnabledServicesPackageNames);
John Spurlock7340fc82014-04-24 18:50:12 -0400240 boolean anyServicesInvolved = false;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200241
John Spurlock7340fc82014-04-24 18:50:12 -0400242 if (pkgList != null && (pkgList.length > 0)) {
243 for (String pkgName : pkgList) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200244 if (mEnabledServicesPackageNames.contains(pkgName) ||
245 mRestoredPackages.contains(pkgName)) {
John Spurlock7340fc82014-04-24 18:50:12 -0400246 anyServicesInvolved = true;
247 }
248 }
249 }
250
251 if (anyServicesInvolved) {
252 // if we're not replacing a package, clean up orphaned bits
Julia Reynolds6434eb22016-08-08 17:19:26 -0400253 if (removingPackage) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200254 updateSettingsAccordingToInstalledServices();
255 rebuildRestoredPackages();
John Spurlock7340fc82014-04-24 18:50:12 -0400256 }
257 // make sure we're still bound to any of our services who may have just upgraded
Julia Reynolds1c9bd422016-03-15 09:25:56 -0400258 rebindServices(false);
John Spurlock7340fc82014-04-24 18:50:12 -0400259 }
260 }
261
John Spurlock1b8b22b2015-05-20 09:47:13 -0400262 public void onUserSwitched(int user) {
263 if (DEBUG) Slog.d(TAG, "onUserSwitched u=" + user);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200264 rebuildRestoredPackages();
Christoph Studerb53dfd42014-09-12 14:45:59 +0200265 if (Arrays.equals(mLastSeenProfileIds, mUserProfiles.getCurrentProfileIds())) {
266 if (DEBUG) Slog.d(TAG, "Current profile IDs didn't change, skipping rebindServices().");
267 return;
268 }
Julia Reynolds1c9bd422016-03-15 09:25:56 -0400269 rebindServices(true);
Christoph Studerb53dfd42014-09-12 14:45:59 +0200270 }
271
Julia Reynoldsa3dcaff2016-02-03 15:04:05 -0500272 public void onUserUnlocked(int user) {
273 if (DEBUG) Slog.d(TAG, "onUserUnlocked u=" + user);
274 rebuildRestoredPackages();
Julia Reynolds1c9bd422016-03-15 09:25:56 -0400275 rebindServices(false);
Julia Reynoldsa3dcaff2016-02-03 15:04:05 -0500276 }
277
Chris Wrenab41eec2016-01-04 18:01:27 -0500278 public ManagedServiceInfo getServiceFromTokenLocked(IInterface service) {
279 if (service == null) {
280 return null;
281 }
John Spurlock7340fc82014-04-24 18:50:12 -0400282 final IBinder token = service.asBinder();
283 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200284 for (int i = 0; i < N; i++) {
John Spurlock7340fc82014-04-24 18:50:12 -0400285 final ManagedServiceInfo info = mServices.get(i);
286 if (info.service.asBinder() == token) return info;
287 }
Chris Wrenab41eec2016-01-04 18:01:27 -0500288 return null;
289 }
290
291 public ManagedServiceInfo checkServiceTokenLocked(IInterface service) {
292 checkNotNull(service);
293 ManagedServiceInfo info = getServiceFromTokenLocked(service);
294 if (info != null) {
295 return info;
296 }
John Spurlock7340fc82014-04-24 18:50:12 -0400297 throw new SecurityException("Disallowed call from unknown " + getCaption() + ": "
298 + service);
299 }
300
301 public void unregisterService(IInterface service, int userid) {
302 checkNotNull(service);
303 // no need to check permissions; if your service binder is in the list,
304 // that's proof that you had permission to add it in the first place
305 unregisterServiceImpl(service, userid);
306 }
307
308 public void registerService(IInterface service, ComponentName component, int userid) {
309 checkNotNull(service);
Christoph Studer3e144d32014-05-22 16:48:40 +0200310 ManagedServiceInfo info = registerServiceImpl(service, component, userid);
311 if (info != null) {
312 onServiceAdded(info);
313 }
John Spurlock7340fc82014-04-24 18:50:12 -0400314 }
315
Chris Wren51017d02015-12-15 15:34:46 -0500316 /**
317 * Add a service to our callbacks. The lifecycle of this service is managed externally,
318 * but unlike a system service, it should not be considered privledged.
319 * */
320 public void registerGuestService(ManagedServiceInfo guest) {
321 checkNotNull(guest.service);
Ruben Brunke24b9a62016-02-16 21:38:24 -0800322 if (!checkType(guest.service)) {
323 throw new IllegalArgumentException();
324 }
Chris Wren51017d02015-12-15 15:34:46 -0500325 if (registerServiceImpl(guest) != null) {
326 onServiceAdded(guest);
Chris Wrenab41eec2016-01-04 18:01:27 -0500327 }
328 }
329
330 public void setComponentState(ComponentName component, boolean enabled) {
331 boolean previous = !mSnoozingForCurrentProfiles.contains(component);
332 if (previous == enabled) {
333 return;
334 }
335
336 if (enabled) {
337 mSnoozingForCurrentProfiles.remove(component);
338 } else {
339 mSnoozingForCurrentProfiles.add(component);
340 }
341
342 // State changed
343 if (DEBUG) {
344 Slog.d(TAG, ((enabled) ? "Enabling " : "Disabling ") + "component " +
345 component.flattenToShortString());
346 }
347
Chris Wren0efdb882016-03-01 17:17:47 -0500348
349 synchronized (mMutex) {
350 final int[] userIds = mUserProfiles.getCurrentProfileIds();
351
352 for (int userId : userIds) {
353 if (enabled) {
354 registerServiceLocked(component, userId);
355 } else {
356 unregisterServiceLocked(component, userId);
357 }
Chris Wrenab41eec2016-01-04 18:01:27 -0500358 }
Chris Wren51017d02015-12-15 15:34:46 -0500359 }
360 }
361
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200362 private void rebuildRestoredPackages() {
363 mRestoredPackages.clear();
Julia Reynolds6e839b02016-04-13 10:01:17 -0400364 String secureSettingName = restoredSettingName(mConfig.secureSettingName);
365 String secondarySettingName = mConfig.secondarySettingName == null
366 ? null : restoredSettingName(mConfig.secondarySettingName);
John Spurlock7340fc82014-04-24 18:50:12 -0400367 int[] userIds = mUserProfiles.getCurrentProfileIds();
368 final int N = userIds.length;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200369 for (int i = 0; i < N; ++i) {
Julia Reynolds6e839b02016-04-13 10:01:17 -0400370 ArraySet<ComponentName> names =
371 loadComponentNamesFromSetting(secureSettingName, userIds[i]);
372 if (secondarySettingName != null) {
373 names.addAll(loadComponentNamesFromSetting(secondarySettingName, userIds[i]));
374 }
375 for (ComponentName name : names) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200376 mRestoredPackages.add(name.getPackageName());
377 }
John Spurlock7340fc82014-04-24 18:50:12 -0400378 }
379 }
380
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200381
Julia Reynolds6e839b02016-04-13 10:01:17 -0400382 protected @NonNull ArraySet<ComponentName> loadComponentNamesFromSetting(String settingName,
Julia Reynoldsc279b992015-10-30 08:23:51 -0400383 int userId) {
Christopher Tate6597e342015-02-17 12:15:25 -0800384 final ContentResolver cr = mContext.getContentResolver();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200385 String settingValue = Settings.Secure.getStringForUser(
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800386 cr,
387 settingName,
388 userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200389 if (TextUtils.isEmpty(settingValue))
Julia Reynolds6e839b02016-04-13 10:01:17 -0400390 return new ArraySet<>();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200391 String[] restored = settingValue.split(ENABLED_SERVICES_SEPARATOR);
392 ArraySet<ComponentName> result = new ArraySet<>(restored.length);
393 for (int i = 0; i < restored.length; i++) {
394 ComponentName value = ComponentName.unflattenFromString(restored[i]);
395 if (null != value) {
396 result.add(value);
Christopher Tate6597e342015-02-17 12:15:25 -0800397 }
398 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200399 return result;
400 }
John Spurlock7340fc82014-04-24 18:50:12 -0400401
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200402 private void storeComponentsToSetting(Set<ComponentName> components,
403 String settingName,
404 int userId) {
405 String[] componentNames = null;
406 if (null != components) {
407 componentNames = new String[components.size()];
408 int index = 0;
409 for (ComponentName c: components) {
410 componentNames[index++] = c.flattenToString();
411 }
412 }
413 final String value = (componentNames == null) ? "" :
414 TextUtils.join(ENABLED_SERVICES_SEPARATOR, componentNames);
415 final ContentResolver cr = mContext.getContentResolver();
416 Settings.Secure.putStringForUser(
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800417 cr,
418 settingName,
419 value,
420 userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200421 }
422
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200423 /**
424 * Remove access for any services that no longer exist.
425 */
426 private void updateSettingsAccordingToInstalledServices() {
427 int[] userIds = mUserProfiles.getCurrentProfileIds();
428 final int N = userIds.length;
429 for (int i = 0; i < N; ++i) {
Julia Reynolds6e839b02016-04-13 10:01:17 -0400430 updateSettingsAccordingToInstalledServices(mConfig.secureSettingName, userIds[i]);
431 if (mConfig.secondarySettingName != null) {
432 updateSettingsAccordingToInstalledServices(
433 mConfig.secondarySettingName, userIds[i]);
434 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200435 }
436 rebuildRestoredPackages();
437 }
438
Julia Reynoldsc279b992015-10-30 08:23:51 -0400439 protected Set<ComponentName> queryPackageForServices(String packageName, int userId) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200440 Set<ComponentName> installed = new ArraySet<>();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200441 final PackageManager pm = mContext.getPackageManager();
Julia Reynoldsc279b992015-10-30 08:23:51 -0400442 Intent queryIntent = new Intent(mConfig.serviceInterface);
443 if (!TextUtils.isEmpty(packageName)) {
444 queryIntent.setPackage(packageName);
445 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200446 List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
Julia Reynoldsc279b992015-10-30 08:23:51 -0400447 queryIntent,
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200448 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
449 userId);
450 if (DEBUG)
451 Slog.v(TAG, mConfig.serviceInterface + " services: " + installedServices);
Julia Reynolds50f05142015-10-30 17:03:59 -0400452 if (installedServices != null) {
453 for (int i = 0, count = installedServices.size(); i < count; i++) {
454 ResolveInfo resolveInfo = installedServices.get(i);
455 ServiceInfo info = resolveInfo.serviceInfo;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200456
Julia Reynolds50f05142015-10-30 17:03:59 -0400457 ComponentName component = new ComponentName(info.packageName, info.name);
458 if (!mConfig.bindPermission.equals(info.permission)) {
459 Slog.w(TAG, "Skipping " + getCaption() + " service "
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800460 + info.packageName + "/" + info.name
461 + ": it does not require the permission "
462 + mConfig.bindPermission);
Julia Reynolds50f05142015-10-30 17:03:59 -0400463 continue;
464 }
465 installed.add(component);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200466 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200467 }
Julia Reynoldsc279b992015-10-30 08:23:51 -0400468 return installed;
469 }
470
Julia Reynolds6e839b02016-04-13 10:01:17 -0400471 private void updateSettingsAccordingToInstalledServices(String setting, int userId) {
Julia Reynoldsc279b992015-10-30 08:23:51 -0400472 boolean restoredChanged = false;
473 boolean currentChanged = false;
474 Set<ComponentName> restored =
Julia Reynolds6e839b02016-04-13 10:01:17 -0400475 loadComponentNamesFromSetting(restoredSettingName(setting), userId);
Julia Reynoldsc279b992015-10-30 08:23:51 -0400476 Set<ComponentName> current =
Julia Reynolds6e839b02016-04-13 10:01:17 -0400477 loadComponentNamesFromSetting(setting, userId);
Julia Reynoldsc279b992015-10-30 08:23:51 -0400478 // Load all services for all packages.
479 Set<ComponentName> installed = queryPackageForServices(null, userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200480
481 ArraySet<ComponentName> retained = new ArraySet<>();
482
483 for (ComponentName component : installed) {
484 if (null != restored) {
485 boolean wasRestored = restored.remove(component);
486 if (wasRestored) {
487 // Freshly installed package has service that was mentioned in restored setting.
488 if (DEBUG)
489 Slog.v(TAG, "Restoring " + component + " for user " + userId);
490 restoredChanged = true;
491 currentChanged = true;
492 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400493 continue;
494 }
John Spurlock7340fc82014-04-24 18:50:12 -0400495 }
496
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200497 if (null != current) {
498 if (current.contains(component))
499 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400500 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200501 }
502
503 currentChanged |= ((current == null ? 0 : current.size()) != retained.size());
504
505 if (currentChanged) {
506 if (DEBUG) Slog.v(TAG, "List of " + getCaption() + " services was updated " + current);
Julia Reynolds6e839b02016-04-13 10:01:17 -0400507 storeComponentsToSetting(retained, setting, userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200508 }
509
510 if (restoredChanged) {
511 if (DEBUG) Slog.v(TAG,
512 "List of " + getCaption() + " restored services was updated " + restored);
Julia Reynolds6e839b02016-04-13 10:01:17 -0400513 storeComponentsToSetting(restored, restoredSettingName(setting), userId);
John Spurlock7340fc82014-04-24 18:50:12 -0400514 }
515 }
516
517 /**
518 * Called whenever packages change, the user switches, or the secure setting
519 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
520 */
Julia Reynolds1c9bd422016-03-15 09:25:56 -0400521 private void rebindServices(boolean forceRebind) {
John Spurlock7340fc82014-04-24 18:50:12 -0400522 if (DEBUG) Slog.d(TAG, "rebindServices");
523 final int[] userIds = mUserProfiles.getCurrentProfileIds();
524 final int nUserIds = userIds.length;
525
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200526 final SparseArray<ArraySet<ComponentName>> componentsByUser = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400527
528 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200529 componentsByUser.put(userIds[i],
530 loadComponentNamesFromSetting(mConfig.secureSettingName, userIds[i]));
Julia Reynolds6e839b02016-04-13 10:01:17 -0400531 if (mConfig.secondarySettingName != null) {
532 componentsByUser.get(userIds[i]).addAll(
533 loadComponentNamesFromSetting(mConfig.secondarySettingName, userIds[i]));
534 }
John Spurlock7340fc82014-04-24 18:50:12 -0400535 }
536
Julia Reynolds9a86cc02016-02-10 15:38:15 -0500537 final ArrayList<ManagedServiceInfo> removableBoundServices = new ArrayList<>();
538 final SparseArray<Set<ComponentName>> toAdd = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400539
540 synchronized (mMutex) {
Julia Reynolds1c9bd422016-03-15 09:25:56 -0400541 // Rebind to non-system services if user switched
Christoph Studer5d423842014-05-23 13:15:54 +0200542 for (ManagedServiceInfo service : mServices) {
Chris Wren51017d02015-12-15 15:34:46 -0500543 if (!service.isSystem && !service.isGuest(this)) {
Julia Reynolds9a86cc02016-02-10 15:38:15 -0500544 removableBoundServices.add(service);
Christoph Studer5d423842014-05-23 13:15:54 +0200545 }
546 }
John Spurlock7340fc82014-04-24 18:50:12 -0400547
Julia Reynolds1c9bd422016-03-15 09:25:56 -0400548 mEnabledServicesForCurrentProfiles.clear();
549 mEnabledServicesPackageNames.clear();
John Spurlock7340fc82014-04-24 18:50:12 -0400550
551 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200552 // decode the list of components
553 final ArraySet<ComponentName> userComponents = componentsByUser.get(userIds[i]);
554 if (null == userComponents) {
Julia Reynolds6e839b02016-04-13 10:01:17 -0400555 toAdd.put(userIds[i], new ArraySet<ComponentName>());
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200556 continue;
557 }
558
Julia Reynolds9a86cc02016-02-10 15:38:15 -0500559 final Set<ComponentName> add = new HashSet<>(userComponents);
Chris Wrenab41eec2016-01-04 18:01:27 -0500560 add.removeAll(mSnoozingForCurrentProfiles);
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800561
John Spurlock7340fc82014-04-24 18:50:12 -0400562 toAdd.put(userIds[i], add);
563
Julia Reynolds1c9bd422016-03-15 09:25:56 -0400564 mEnabledServicesForCurrentProfiles.addAll(userComponents);
John Spurlock7340fc82014-04-24 18:50:12 -0400565
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200566 for (int j = 0; j < userComponents.size(); j++) {
Chris Wren083094c2015-12-15 16:25:07 -0500567 final ComponentName component = userComponents.valueAt(j);
Julia Reynolds1c9bd422016-03-15 09:25:56 -0400568 mEnabledServicesPackageNames.add(component.getPackageName());
John Spurlock7340fc82014-04-24 18:50:12 -0400569 }
570 }
John Spurlock7340fc82014-04-24 18:50:12 -0400571 }
572
Julia Reynolds9a86cc02016-02-10 15:38:15 -0500573 for (ManagedServiceInfo info : removableBoundServices) {
John Spurlock7340fc82014-04-24 18:50:12 -0400574 final ComponentName component = info.component;
575 final int oldUser = info.userid;
Julia Reynolds9a86cc02016-02-10 15:38:15 -0500576 final Set<ComponentName> allowedComponents = toAdd.get(info.userid);
577 if (allowedComponents != null) {
Julia Reynolds1c9bd422016-03-15 09:25:56 -0400578 if (allowedComponents.contains(component) && !forceRebind) {
Julia Reynolds9a86cc02016-02-10 15:38:15 -0500579 // Already bound, don't need to bind again.
580 allowedComponents.remove(component);
581 } else {
Julia Reynolds1c9bd422016-03-15 09:25:56 -0400582 // No longer allowed to be bound, or must rebind.
Julia Reynolds9a86cc02016-02-10 15:38:15 -0500583 Slog.v(TAG, "disabling " + getCaption() + " for user "
584 + oldUser + ": " + component);
585 unregisterService(component, oldUser);
586 }
587 }
John Spurlock7340fc82014-04-24 18:50:12 -0400588 }
589
590 for (int i = 0; i < nUserIds; ++i) {
Julia Reynolds9a86cc02016-02-10 15:38:15 -0500591 final Set<ComponentName> add = toAdd.get(userIds[i]);
592 for (ComponentName component : add) {
Julia Reynoldsa75c7522017-03-21 17:34:25 -0400593 try {
594 ServiceInfo info = mPm.getServiceInfo(component,
595 PackageManager.MATCH_DIRECT_BOOT_AWARE
596 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userIds[i]);
Julia Reynolds8bb5c932017-03-23 14:09:06 -0400597 if (info == null || !mConfig.bindPermission.equals(info.permission)) {
Julia Reynoldsa75c7522017-03-21 17:34:25 -0400598 Slog.w(TAG, "Skipping " + getCaption() + " service " + component
599 + ": it does not require the permission " + mConfig.bindPermission);
600 continue;
601 }
602 Slog.v(TAG,
603 "enabling " + getCaption() + " for " + userIds[i] + ": " + component);
604 registerService(component, userIds[i]);
605 } catch (RemoteException e) {
606 e.rethrowFromSystemServer();
607 }
John Spurlock7340fc82014-04-24 18:50:12 -0400608 }
609 }
Christoph Studerb53dfd42014-09-12 14:45:59 +0200610
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200611 mLastSeenProfileIds = userIds;
John Spurlock7340fc82014-04-24 18:50:12 -0400612 }
613
614 /**
615 * Version of registerService that takes the name of a service component to bind to.
616 */
617 private void registerService(final ComponentName name, final int userid) {
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800618 synchronized (mMutex) {
619 registerServiceLocked(name, userid);
620 }
621 }
622
Chris Wren0efdb882016-03-01 17:17:47 -0500623 /**
624 * Inject a system service into the management list.
625 */
626 public void registerSystemService(final ComponentName name, final int userid) {
627 synchronized (mMutex) {
628 registerServiceLocked(name, userid, true /* isSystem */);
629 }
630 }
631
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800632 private void registerServiceLocked(final ComponentName name, final int userid) {
Chris Wren0efdb882016-03-01 17:17:47 -0500633 registerServiceLocked(name, userid, false /* isSystem */);
634 }
635
636 private void registerServiceLocked(final ComponentName name, final int userid,
637 final boolean isSystem) {
John Spurlock7340fc82014-04-24 18:50:12 -0400638 if (DEBUG) Slog.v(TAG, "registerService: " + name + " u=" + userid);
639
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800640 final String servicesBindingTag = name.toString() + "/" + userid;
641 if (mServicesBinding.contains(servicesBindingTag)) {
642 // stop registering this thing already! we're working on it
643 return;
644 }
645 mServicesBinding.add(servicesBindingTag);
John Spurlock7340fc82014-04-24 18:50:12 -0400646
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800647 final int N = mServices.size();
648 for (int i = N - 1; i >= 0; i--) {
649 final ManagedServiceInfo info = mServices.get(i);
650 if (name.equals(info.component)
651 && info.userid == userid) {
652 // cut old connections
653 if (DEBUG) Slog.v(TAG, " disconnecting old " + getCaption() + ": "
654 + info.service);
655 removeServiceLocked(i);
656 if (info.connection != null) {
657 mContext.unbindService(info.connection);
John Spurlock7340fc82014-04-24 18:50:12 -0400658 }
659 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800660 }
John Spurlock7340fc82014-04-24 18:50:12 -0400661
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800662 Intent intent = new Intent(mConfig.serviceInterface);
663 intent.setComponent(name);
John Spurlock7340fc82014-04-24 18:50:12 -0400664
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800665 intent.putExtra(Intent.EXTRA_CLIENT_LABEL, mConfig.clientLabel);
John Spurlock7340fc82014-04-24 18:50:12 -0400666
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800667 final PendingIntent pendingIntent = PendingIntent.getActivity(
668 mContext, 0, new Intent(mConfig.settingsAction), 0);
669 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, pendingIntent);
John Spurlock7340fc82014-04-24 18:50:12 -0400670
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800671 ApplicationInfo appInfo = null;
672 try {
673 appInfo = mContext.getPackageManager().getApplicationInfo(
674 name.getPackageName(), 0);
675 } catch (NameNotFoundException e) {
676 // Ignore if the package doesn't exist we won't be able to bind to the service.
677 }
678 final int targetSdkVersion =
679 appInfo != null ? appInfo.targetSdkVersion : Build.VERSION_CODES.BASE;
John Spurlock7340fc82014-04-24 18:50:12 -0400680
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800681 try {
682 if (DEBUG) Slog.v(TAG, "binding: " + intent);
683 ServiceConnection serviceConnection = new ServiceConnection() {
684 IInterface mService;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200685
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800686 @Override
687 public void onServiceConnected(ComponentName name, IBinder binder) {
688 boolean added = false;
689 ManagedServiceInfo info = null;
690 synchronized (mMutex) {
691 mServicesBinding.remove(servicesBindingTag);
692 try {
693 mService = asInterface(binder);
694 info = newServiceInfo(mService, name,
Chris Wren0efdb882016-03-01 17:17:47 -0500695 userid, isSystem, this, targetSdkVersion);
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800696 binder.linkToDeath(info, 0);
697 added = mServices.add(info);
698 } catch (RemoteException e) {
699 // already dead
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200700 }
701 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800702 if (added) {
703 onServiceAdded(info);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200704 }
John Spurlock7340fc82014-04-24 18:50:12 -0400705 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800706
707 @Override
708 public void onServiceDisconnected(ComponentName name) {
709 Slog.v(TAG, getCaption() + " connection lost: " + name);
710 }
711 };
712 if (!mContext.bindServiceAsUser(intent,
713 serviceConnection,
Felipe Lemea1b79bf2016-05-24 13:06:54 -0700714 BIND_AUTO_CREATE | BIND_FOREGROUND_SERVICE | BIND_ALLOW_WHITELIST_MANAGEMENT,
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800715 new UserHandle(userid))) {
716 mServicesBinding.remove(servicesBindingTag);
717 Slog.w(TAG, "Unable to bind " + getCaption() + " service: " + intent);
John Spurlock7340fc82014-04-24 18:50:12 -0400718 return;
719 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800720 } catch (SecurityException ex) {
721 Slog.e(TAG, "Unable to bind " + getCaption() + " service: " + intent, ex);
722 return;
John Spurlock7340fc82014-04-24 18:50:12 -0400723 }
724 }
725
726 /**
727 * Remove a service for the given user by ComponentName
728 */
729 private void unregisterService(ComponentName name, int userid) {
730 synchronized (mMutex) {
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800731 unregisterServiceLocked(name, userid);
732 }
733 }
734
735 private void unregisterServiceLocked(ComponentName name, int userid) {
736 final int N = mServices.size();
737 for (int i = N - 1; i >= 0; i--) {
738 final ManagedServiceInfo info = mServices.get(i);
739 if (name.equals(info.component)
740 && info.userid == userid) {
741 removeServiceLocked(i);
742 if (info.connection != null) {
743 try {
744 mContext.unbindService(info.connection);
745 } catch (IllegalArgumentException ex) {
746 // something happened to the service: we think we have a connection
747 // but it's bogus.
748 Slog.e(TAG, getCaption() + " " + name + " could not be unbound: " + ex);
John Spurlock7340fc82014-04-24 18:50:12 -0400749 }
750 }
751 }
752 }
753 }
754
755 /**
756 * Removes a service from the list but does not unbind
757 *
758 * @return the removed service.
759 */
760 private ManagedServiceInfo removeServiceImpl(IInterface service, final int userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400761 if (DEBUG) Slog.d(TAG, "removeServiceImpl service=" + service + " u=" + userid);
John Spurlock7340fc82014-04-24 18:50:12 -0400762 ManagedServiceInfo serviceInfo = null;
763 synchronized (mMutex) {
764 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200765 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400766 final ManagedServiceInfo info = mServices.get(i);
767 if (info.service.asBinder() == service.asBinder()
768 && info.userid == userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400769 if (DEBUG) Slog.d(TAG, "Removing active service " + info.component);
770 serviceInfo = removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400771 }
772 }
773 }
774 return serviceInfo;
775 }
776
John Spurlocke77bb362014-04-26 10:24:59 -0400777 private ManagedServiceInfo removeServiceLocked(int i) {
778 final ManagedServiceInfo info = mServices.remove(i);
779 onServiceRemovedLocked(info);
780 return info;
781 }
782
John Spurlock7340fc82014-04-24 18:50:12 -0400783 private void checkNotNull(IInterface service) {
784 if (service == null) {
785 throw new IllegalArgumentException(getCaption() + " must not be null");
786 }
787 }
788
Christoph Studer3e144d32014-05-22 16:48:40 +0200789 private ManagedServiceInfo registerServiceImpl(final IInterface service,
John Spurlock7340fc82014-04-24 18:50:12 -0400790 final ComponentName component, final int userid) {
Chris Wren51017d02015-12-15 15:34:46 -0500791 ManagedServiceInfo info = newServiceInfo(service, component, userid,
792 true /*isSystem*/, null /*connection*/, Build.VERSION_CODES.LOLLIPOP);
793 return registerServiceImpl(info);
794 }
795
796 private ManagedServiceInfo registerServiceImpl(ManagedServiceInfo info) {
John Spurlock7340fc82014-04-24 18:50:12 -0400797 synchronized (mMutex) {
798 try {
Chris Wren51017d02015-12-15 15:34:46 -0500799 info.service.asBinder().linkToDeath(info, 0);
John Spurlock7340fc82014-04-24 18:50:12 -0400800 mServices.add(info);
Christoph Studer3e144d32014-05-22 16:48:40 +0200801 return info;
John Spurlock7340fc82014-04-24 18:50:12 -0400802 } catch (RemoteException e) {
803 // already dead
804 }
805 }
Christoph Studer3e144d32014-05-22 16:48:40 +0200806 return null;
John Spurlock7340fc82014-04-24 18:50:12 -0400807 }
808
809 /**
810 * Removes a service from the list and unbinds.
811 */
812 private void unregisterServiceImpl(IInterface service, int userid) {
813 ManagedServiceInfo info = removeServiceImpl(service, userid);
Chris Wren51017d02015-12-15 15:34:46 -0500814 if (info != null && info.connection != null && !info.isGuest(this)) {
John Spurlock7340fc82014-04-24 18:50:12 -0400815 mContext.unbindService(info.connection);
816 }
817 }
818
819 private class SettingsObserver extends ContentObserver {
820 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(mConfig.secureSettingName);
Julia Reynolds6e839b02016-04-13 10:01:17 -0400821 private final Uri mSecondarySettingsUri;
John Spurlock7340fc82014-04-24 18:50:12 -0400822
823 private SettingsObserver(Handler handler) {
824 super(handler);
Julia Reynolds6e839b02016-04-13 10:01:17 -0400825 if (mConfig.secondarySettingName != null) {
826 mSecondarySettingsUri = Settings.Secure.getUriFor(mConfig.secondarySettingName);
827 } else {
828 mSecondarySettingsUri = null;
829 }
John Spurlock7340fc82014-04-24 18:50:12 -0400830 }
831
832 private void observe() {
833 ContentResolver resolver = mContext.getContentResolver();
834 resolver.registerContentObserver(mSecureSettingsUri,
835 false, this, UserHandle.USER_ALL);
Julia Reynolds6e839b02016-04-13 10:01:17 -0400836 if (mSecondarySettingsUri != null) {
837 resolver.registerContentObserver(mSecondarySettingsUri,
838 false, this, UserHandle.USER_ALL);
839 }
John Spurlock7340fc82014-04-24 18:50:12 -0400840 update(null);
841 }
842
843 @Override
844 public void onChange(boolean selfChange, Uri uri) {
845 update(uri);
846 }
847
848 private void update(Uri uri) {
Julia Reynolds6e839b02016-04-13 10:01:17 -0400849 if (uri == null || mSecureSettingsUri.equals(uri)
850 || uri.equals(mSecondarySettingsUri)) {
851 if (DEBUG) Slog.d(TAG, "Setting changed: uri=" + uri);
Julia Reynolds1c9bd422016-03-15 09:25:56 -0400852 rebindServices(false);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200853 rebuildRestoredPackages();
John Spurlock7340fc82014-04-24 18:50:12 -0400854 }
855 }
856 }
857
858 public class ManagedServiceInfo implements IBinder.DeathRecipient {
859 public IInterface service;
860 public ComponentName component;
861 public int userid;
862 public boolean isSystem;
863 public ServiceConnection connection;
864 public int targetSdkVersion;
865
866 public ManagedServiceInfo(IInterface service, ComponentName component,
867 int userid, boolean isSystem, ServiceConnection connection, int targetSdkVersion) {
868 this.service = service;
869 this.component = component;
870 this.userid = userid;
871 this.isSystem = isSystem;
872 this.connection = connection;
873 this.targetSdkVersion = targetSdkVersion;
874 }
875
Chris Wren51017d02015-12-15 15:34:46 -0500876 public boolean isGuest(ManagedServices host) {
877 return ManagedServices.this != host;
878 }
879
Chris Wrenab41eec2016-01-04 18:01:27 -0500880 public ManagedServices getOwner() {
881 return ManagedServices.this;
882 }
883
John Spurlocke77bb362014-04-26 10:24:59 -0400884 @Override
885 public String toString() {
886 return new StringBuilder("ManagedServiceInfo[")
887 .append("component=").append(component)
888 .append(",userid=").append(userid)
889 .append(",isSystem=").append(isSystem)
890 .append(",targetSdkVersion=").append(targetSdkVersion)
891 .append(",connection=").append(connection == null ? null : "<connection>")
892 .append(",service=").append(service)
893 .append(']').toString();
894 }
895
John Spurlock7340fc82014-04-24 18:50:12 -0400896 public boolean enabledAndUserMatches(int nid) {
897 if (!isEnabledForCurrentProfiles()) {
898 return false;
899 }
900 if (this.userid == UserHandle.USER_ALL) return true;
Chris Wren0c4eeb42016-05-12 13:21:08 -0400901 if (this.isSystem) return true;
John Spurlock7340fc82014-04-24 18:50:12 -0400902 if (nid == UserHandle.USER_ALL || nid == this.userid) return true;
Esteban Talavera9c6458d2017-03-30 17:59:50 +0100903 return supportsProfiles()
904 && mUserProfiles.isCurrentProfile(nid)
905 && isPermittedForProfile(nid);
John Spurlock7340fc82014-04-24 18:50:12 -0400906 }
907
908 public boolean supportsProfiles() {
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700909 return targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
John Spurlock7340fc82014-04-24 18:50:12 -0400910 }
911
912 @Override
913 public void binderDied() {
John Spurlocke77bb362014-04-26 10:24:59 -0400914 if (DEBUG) Slog.d(TAG, "binderDied");
John Spurlock7340fc82014-04-24 18:50:12 -0400915 // Remove the service, but don't unbind from the service. The system will bring the
Esteban Talavera9c6458d2017-03-30 17:59:50 +0100916 // service back up, and the onServiceConnected handler will read the service with the
John Spurlock7340fc82014-04-24 18:50:12 -0400917 // new binding. If this isn't a bound service, and is just a registered
918 // service, just removing it from the list is all we need to do anyway.
919 removeServiceImpl(this.service, this.userid);
920 }
921
922 /** convenience method for looking in mEnabledServicesForCurrentProfiles */
923 public boolean isEnabledForCurrentProfiles() {
924 if (this.isSystem) return true;
925 if (this.connection == null) return false;
926 return mEnabledServicesForCurrentProfiles.contains(this.component);
927 }
Esteban Talavera9c6458d2017-03-30 17:59:50 +0100928
929 /**
930 * Returns true if this service is allowed to receive events for the given userId. A
931 * managed profile owner can disallow non-system services running outside of the profile
932 * from receiving events from the profile.
933 */
934 public boolean isPermittedForProfile(int userId) {
935 if (!mUserProfiles.isManagedProfile(userId)) {
936 return true;
937 }
938 DevicePolicyManager dpm =
939 (DevicePolicyManager) mContext.getSystemService(DEVICE_POLICY_SERVICE);
940 final long identity = Binder.clearCallingIdentity();
941 try {
942 return dpm.isNotificationListenerServicePermitted(
943 component.getPackageName(), userId);
944 } finally {
945 Binder.restoreCallingIdentity(identity);
946 }
947 }
John Spurlock7340fc82014-04-24 18:50:12 -0400948 }
949
Chris Wrenab41eec2016-01-04 18:01:27 -0500950 /** convenience method for looking in mEnabledServicesForCurrentProfiles */
951 public boolean isComponentEnabledForCurrentProfiles(ComponentName component) {
952 return mEnabledServicesForCurrentProfiles.contains(component);
953 }
954
John Spurlock7340fc82014-04-24 18:50:12 -0400955 public static class UserProfiles {
956 // Profiles of the current user.
Ruben Brunke24b9a62016-02-16 21:38:24 -0800957 private final SparseArray<UserInfo> mCurrentProfiles = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400958
Ruben Brunke24b9a62016-02-16 21:38:24 -0800959 public void updateCache(@NonNull Context context) {
John Spurlock7340fc82014-04-24 18:50:12 -0400960 UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
961 if (userManager != null) {
962 int currentUserId = ActivityManager.getCurrentUser();
963 List<UserInfo> profiles = userManager.getProfiles(currentUserId);
964 synchronized (mCurrentProfiles) {
965 mCurrentProfiles.clear();
966 for (UserInfo user : profiles) {
967 mCurrentProfiles.put(user.id, user);
968 }
969 }
970 }
971 }
972
973 public int[] getCurrentProfileIds() {
974 synchronized (mCurrentProfiles) {
975 int[] users = new int[mCurrentProfiles.size()];
976 final int N = mCurrentProfiles.size();
977 for (int i = 0; i < N; ++i) {
978 users[i] = mCurrentProfiles.keyAt(i);
979 }
980 return users;
981 }
982 }
983
984 public boolean isCurrentProfile(int userId) {
985 synchronized (mCurrentProfiles) {
986 return mCurrentProfiles.get(userId) != null;
987 }
988 }
Esteban Talavera9c6458d2017-03-30 17:59:50 +0100989
990 public boolean isManagedProfile(int userId) {
991 synchronized (mCurrentProfiles) {
992 UserInfo user = mCurrentProfiles.get(userId);
993 return user != null && user.isManagedProfile();
994 }
995 }
John Spurlock7340fc82014-04-24 18:50:12 -0400996 }
997
Ruben Brunke24b9a62016-02-16 21:38:24 -0800998 public static class Config {
999 public String caption;
1000 public String serviceInterface;
1001 public String secureSettingName;
Julia Reynolds6e839b02016-04-13 10:01:17 -04001002 public String secondarySettingName;
Ruben Brunke24b9a62016-02-16 21:38:24 -08001003 public String bindPermission;
1004 public String settingsAction;
1005 public int clientLabel;
John Spurlock7340fc82014-04-24 18:50:12 -04001006 }
1007}