blob: f360dc2c4283072a60c3c47a726312b9abb653cd [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
19import android.app.ActivityManager;
20import android.app.PendingIntent;
Christopher Tate6597e342015-02-17 12:15:25 -080021import android.content.BroadcastReceiver;
John Spurlock7340fc82014-04-24 18:50:12 -040022import android.content.ComponentName;
23import android.content.ContentResolver;
24import android.content.Context;
25import android.content.Intent;
Christopher Tate6597e342015-02-17 12:15:25 -080026import android.content.IntentFilter;
John Spurlock7340fc82014-04-24 18:50:12 -040027import android.content.ServiceConnection;
28import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageManager;
30import android.content.pm.PackageManager.NameNotFoundException;
31import android.content.pm.ResolveInfo;
32import android.content.pm.ServiceInfo;
33import android.content.pm.UserInfo;
34import android.database.ContentObserver;
35import android.net.Uri;
36import android.os.Build;
37import android.os.Handler;
38import android.os.IBinder;
39import android.os.IInterface;
40import android.os.RemoteException;
41import android.os.UserHandle;
42import android.os.UserManager;
43import android.provider.Settings;
44import android.text.TextUtils;
Ruben Brunkdd18a0b2015-12-04 16:16:31 -080045import android.util.ArrayMap;
John Spurlock7340fc82014-04-24 18:50:12 -040046import android.util.ArraySet;
John Spurlock4db0d982014-08-13 09:19:03 -040047import android.util.Log;
John Spurlock7340fc82014-04-24 18:50:12 -040048import android.util.Slog;
49import android.util.SparseArray;
50
John Spurlock25e2d242014-06-27 13:58:23 -040051import com.android.server.notification.NotificationManagerService.DumpFilter;
52
John Spurlock7340fc82014-04-24 18:50:12 -040053import java.io.PrintWriter;
54import java.util.ArrayList;
John Spurlocke77bb362014-04-26 10:24:59 -040055import java.util.Arrays;
John Spurlock7340fc82014-04-24 18:50:12 -040056import java.util.List;
Ruben Brunkdd18a0b2015-12-04 16:16:31 -080057import java.util.Map.Entry;
Christopher Tate6597e342015-02-17 12:15:25 -080058import java.util.Objects;
John Spurlock7340fc82014-04-24 18:50:12 -040059import java.util.Set;
60
61/**
62 * Manages the lifecycle of application-provided services bound by system server.
63 *
64 * Services managed by this helper must have:
65 * - An associated system settings value with a list of enabled component names.
66 * - A well-known action for services to use in their intent-filter.
67 * - A system permission for services to require in order to ensure system has exclusive binding.
68 * - A settings page for user configuration of enabled services, and associated intent action.
69 * - A remote interface definition (aidl) provided by the service used for communication.
70 */
71abstract public class ManagedServices {
72 protected final String TAG = getClass().getSimpleName();
John Spurlock4db0d982014-08-13 09:19:03 -040073 protected final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
John Spurlock7340fc82014-04-24 18:50:12 -040074
Julia Reynoldsc279b992015-10-30 08:23:51 -040075 protected static final String ENABLED_SERVICES_SEPARATOR = ":";
John Spurlock7340fc82014-04-24 18:50:12 -040076
John Spurlockaf8d6c42014-05-07 17:49:08 -040077 protected final Context mContext;
John Spurlocke77bb362014-04-26 10:24:59 -040078 protected final Object mMutex;
John Spurlock7340fc82014-04-24 18:50:12 -040079 private final UserProfiles mUserProfiles;
80 private final SettingsObserver mSettingsObserver;
81 private final Config mConfig;
Christopher Tate6597e342015-02-17 12:15:25 -080082 private ArraySet<String> mRestored;
John Spurlock7340fc82014-04-24 18:50:12 -040083
84 // contains connections to all connected services, including app services
85 // and system services
86 protected final ArrayList<ManagedServiceInfo> mServices = new ArrayList<ManagedServiceInfo>();
87 // things that will be put into mServices as soon as they're ready
88 private final ArrayList<String> mServicesBinding = new ArrayList<String>();
Chris Wrenab41eec2016-01-04 18:01:27 -050089 // lists the component names of all enabled (and therefore potentially connected)
John Spurlock7340fc82014-04-24 18:50:12 -040090 // app services for current profiles.
91 private ArraySet<ComponentName> mEnabledServicesForCurrentProfiles
92 = new ArraySet<ComponentName>();
93 // Just the packages from mEnabledServicesForCurrentProfiles
94 private ArraySet<String> mEnabledServicesPackageNames = new ArraySet<String>();
Denis Kuznetsov76c02682015-09-17 19:57:00 +020095 // List of packages in restored setting across all mUserProfiles, for quick
96 // filtering upon package updates.
97 private ArraySet<String> mRestoredPackages = new ArraySet<>();
Ruben Brunkdd18a0b2015-12-04 16:16:31 -080098 // State of current service categories
99 private ArrayMap<String, Boolean> mCategoryEnabled = new ArrayMap<>();
Chris Wrenab41eec2016-01-04 18:01:27 -0500100 // List of enabled packages that have nevertheless asked not to be run
101 private ArraySet<ComponentName> mSnoozingForCurrentProfiles = new ArraySet<>();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200102
John Spurlock7340fc82014-04-24 18:50:12 -0400103
Christoph Studerb53dfd42014-09-12 14:45:59 +0200104 // Kept to de-dupe user change events (experienced after boot, when we receive a settings and a
105 // user change).
106 private int[] mLastSeenProfileIds;
107
Christopher Tate6597e342015-02-17 12:15:25 -0800108 private final BroadcastReceiver mRestoreReceiver;
109
John Spurlock7340fc82014-04-24 18:50:12 -0400110 public ManagedServices(Context context, Handler handler, Object mutex,
111 UserProfiles userProfiles) {
112 mContext = context;
113 mMutex = mutex;
114 mUserProfiles = userProfiles;
115 mConfig = getConfig();
116 mSettingsObserver = new SettingsObserver(handler);
Christopher Tate6597e342015-02-17 12:15:25 -0800117
118 mRestoreReceiver = new SettingRestoredReceiver();
119 IntentFilter filter = new IntentFilter(Intent.ACTION_SETTING_RESTORED);
120 context.registerReceiver(mRestoreReceiver, filter);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200121 rebuildRestoredPackages();
Christopher Tate6597e342015-02-17 12:15:25 -0800122 }
123
124 class SettingRestoredReceiver extends BroadcastReceiver {
125 @Override
126 public void onReceive(Context context, Intent intent) {
127 if (Intent.ACTION_SETTING_RESTORED.equals(intent.getAction())) {
128 String element = intent.getStringExtra(Intent.EXTRA_SETTING_NAME);
129 if (Objects.equals(element, mConfig.secureSettingName)) {
130 String prevValue = intent.getStringExtra(Intent.EXTRA_SETTING_PREVIOUS_VALUE);
131 String newValue = intent.getStringExtra(Intent.EXTRA_SETTING_NEW_VALUE);
132 settingRestored(element, prevValue, newValue, getSendingUserId());
133 }
134 }
135 }
John Spurlock7340fc82014-04-24 18:50:12 -0400136 }
137
138 abstract protected Config getConfig();
139
140 private String getCaption() {
141 return mConfig.caption;
142 }
143
144 abstract protected IInterface asInterface(IBinder binder);
145
Chris Wren51017d02015-12-15 15:34:46 -0500146 abstract protected boolean checkType(IInterface service);
147
John Spurlock3b98b3f2014-05-01 09:08:48 -0400148 abstract protected void onServiceAdded(ManagedServiceInfo info);
John Spurlock7340fc82014-04-24 18:50:12 -0400149
John Spurlocke77bb362014-04-26 10:24:59 -0400150 protected void onServiceRemovedLocked(ManagedServiceInfo removed) { }
151
John Spurlock7340fc82014-04-24 18:50:12 -0400152 private ManagedServiceInfo newServiceInfo(IInterface service,
153 ComponentName component, int userid, boolean isSystem, ServiceConnection connection,
154 int targetSdkVersion) {
155 return new ManagedServiceInfo(service, component, userid, isSystem, connection,
156 targetSdkVersion);
157 }
158
159 public void onBootPhaseAppsCanStart() {
160 mSettingsObserver.observe();
161 }
162
John Spurlock25e2d242014-06-27 13:58:23 -0400163 public void dump(PrintWriter pw, DumpFilter filter) {
John Spurlocke77bb362014-04-26 10:24:59 -0400164 pw.println(" All " + getCaption() + "s (" + mEnabledServicesForCurrentProfiles.size()
John Spurlock7340fc82014-04-24 18:50:12 -0400165 + ") enabled for current profiles:");
166 for (ComponentName cmpt : mEnabledServicesForCurrentProfiles) {
John Spurlock25e2d242014-06-27 13:58:23 -0400167 if (filter != null && !filter.matches(cmpt)) continue;
John Spurlocke77bb362014-04-26 10:24:59 -0400168 pw.println(" " + cmpt);
John Spurlock7340fc82014-04-24 18:50:12 -0400169 }
170
John Spurlocke77bb362014-04-26 10:24:59 -0400171 pw.println(" Live " + getCaption() + "s (" + mServices.size() + "):");
John Spurlock7340fc82014-04-24 18:50:12 -0400172 for (ManagedServiceInfo info : mServices) {
John Spurlock25e2d242014-06-27 13:58:23 -0400173 if (filter != null && !filter.matches(info.component)) continue;
John Spurlocke77bb362014-04-26 10:24:59 -0400174 pw.println(" " + info.component
John Spurlock7340fc82014-04-24 18:50:12 -0400175 + " (user " + info.userid + "): " + info.service
Chris Wren51017d02015-12-15 15:34:46 -0500176 + (info.isSystem?" SYSTEM":"")
177 + (info.isGuest(this)?" GUEST":""));
John Spurlock7340fc82014-04-24 18:50:12 -0400178 }
Chris Wrenab41eec2016-01-04 18:01:27 -0500179
180 pw.println(" Snoozed " + getCaption() + "s (" +
181 mSnoozingForCurrentProfiles.size() + "):");
182 for (ComponentName name : mSnoozingForCurrentProfiles) {
183 pw.println(" " + name.flattenToShortString());
184 }
John Spurlock7340fc82014-04-24 18:50:12 -0400185 }
186
Christopher Tate6597e342015-02-17 12:15:25 -0800187 // By convention, restored settings are replicated to another settings
188 // entry, named similarly but with a disambiguation suffix.
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200189 public static String restoredSettingName(Config config) {
Christopher Tate6597e342015-02-17 12:15:25 -0800190 return config.secureSettingName + ":restored";
191 }
192
193 // The OS has done a restore of this service's saved state. We clone it to the
194 // 'restored' reserve, and then once we return and the actual write to settings is
195 // performed, our observer will do the work of maintaining the restored vs live
196 // settings data.
197 public void settingRestored(String element, String oldValue, String newValue, int userid) {
198 if (DEBUG) Slog.d(TAG, "Restored managed service setting: " + element
199 + " ovalue=" + oldValue + " nvalue=" + newValue);
200 if (mConfig.secureSettingName.equals(element)) {
201 if (element != null) {
202 mRestored = null;
203 Settings.Secure.putStringForUser(mContext.getContentResolver(),
204 restoredSettingName(mConfig),
205 newValue,
206 userid);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200207 updateSettingsAccordingToInstalledServices(userid);
208 rebuildRestoredPackages();
Christopher Tate6597e342015-02-17 12:15:25 -0800209 }
210 }
211 }
212
John Spurlock80774932015-05-07 17:38:50 -0400213 public boolean isComponentEnabledForPackage(String pkg) {
214 return mEnabledServicesPackageNames.contains(pkg);
215 }
216
John Spurlock7340fc82014-04-24 18:50:12 -0400217 public void onPackagesChanged(boolean queryReplace, String[] pkgList) {
John Spurlocke77bb362014-04-26 10:24:59 -0400218 if (DEBUG) Slog.d(TAG, "onPackagesChanged queryReplace=" + queryReplace
219 + " pkgList=" + (pkgList == null ? null : Arrays.asList(pkgList))
220 + " mEnabledServicesPackageNames=" + mEnabledServicesPackageNames);
John Spurlock7340fc82014-04-24 18:50:12 -0400221 boolean anyServicesInvolved = false;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200222
John Spurlock7340fc82014-04-24 18:50:12 -0400223 if (pkgList != null && (pkgList.length > 0)) {
224 for (String pkgName : pkgList) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200225 if (mEnabledServicesPackageNames.contains(pkgName) ||
226 mRestoredPackages.contains(pkgName)) {
John Spurlock7340fc82014-04-24 18:50:12 -0400227 anyServicesInvolved = true;
228 }
229 }
230 }
231
232 if (anyServicesInvolved) {
233 // if we're not replacing a package, clean up orphaned bits
234 if (!queryReplace) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200235 updateSettingsAccordingToInstalledServices();
236 rebuildRestoredPackages();
John Spurlock7340fc82014-04-24 18:50:12 -0400237 }
238 // make sure we're still bound to any of our services who may have just upgraded
239 rebindServices();
240 }
241 }
242
John Spurlock1b8b22b2015-05-20 09:47:13 -0400243 public void onUserSwitched(int user) {
244 if (DEBUG) Slog.d(TAG, "onUserSwitched u=" + user);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200245 rebuildRestoredPackages();
Christoph Studerb53dfd42014-09-12 14:45:59 +0200246 if (Arrays.equals(mLastSeenProfileIds, mUserProfiles.getCurrentProfileIds())) {
247 if (DEBUG) Slog.d(TAG, "Current profile IDs didn't change, skipping rebindServices().");
248 return;
249 }
250 rebindServices();
251 }
252
Chris Wrenab41eec2016-01-04 18:01:27 -0500253 public ManagedServiceInfo getServiceFromTokenLocked(IInterface service) {
254 if (service == null) {
255 return null;
256 }
John Spurlock7340fc82014-04-24 18:50:12 -0400257 final IBinder token = service.asBinder();
258 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200259 for (int i = 0; i < N; i++) {
John Spurlock7340fc82014-04-24 18:50:12 -0400260 final ManagedServiceInfo info = mServices.get(i);
261 if (info.service.asBinder() == token) return info;
262 }
Chris Wrenab41eec2016-01-04 18:01:27 -0500263 return null;
264 }
265
266 public ManagedServiceInfo checkServiceTokenLocked(IInterface service) {
267 checkNotNull(service);
268 ManagedServiceInfo info = getServiceFromTokenLocked(service);
269 if (info != null) {
270 return info;
271 }
John Spurlock7340fc82014-04-24 18:50:12 -0400272 throw new SecurityException("Disallowed call from unknown " + getCaption() + ": "
273 + service);
274 }
275
276 public void unregisterService(IInterface service, int userid) {
277 checkNotNull(service);
278 // no need to check permissions; if your service binder is in the list,
279 // that's proof that you had permission to add it in the first place
280 unregisterServiceImpl(service, userid);
281 }
282
283 public void registerService(IInterface service, ComponentName component, int userid) {
284 checkNotNull(service);
Christoph Studer3e144d32014-05-22 16:48:40 +0200285 ManagedServiceInfo info = registerServiceImpl(service, component, userid);
286 if (info != null) {
287 onServiceAdded(info);
288 }
John Spurlock7340fc82014-04-24 18:50:12 -0400289 }
290
Chris Wren51017d02015-12-15 15:34:46 -0500291 /**
292 * Add a service to our callbacks. The lifecycle of this service is managed externally,
293 * but unlike a system service, it should not be considered privledged.
294 * */
295 public void registerGuestService(ManagedServiceInfo guest) {
296 checkNotNull(guest.service);
297 checkType(guest.service);
298 if (registerServiceImpl(guest) != null) {
299 onServiceAdded(guest);
Chris Wrenab41eec2016-01-04 18:01:27 -0500300 onServiceAdded(guest);
301 }
302 }
303
304 public void setComponentState(ComponentName component, boolean enabled) {
305 boolean previous = !mSnoozingForCurrentProfiles.contains(component);
306 if (previous == enabled) {
307 return;
308 }
309
310 if (enabled) {
311 mSnoozingForCurrentProfiles.remove(component);
312 } else {
313 mSnoozingForCurrentProfiles.add(component);
314 }
315
316 // State changed
317 if (DEBUG) {
318 Slog.d(TAG, ((enabled) ? "Enabling " : "Disabling ") + "component " +
319 component.flattenToShortString());
320 }
321
322 final int[] userIds = mUserProfiles.getCurrentProfileIds();
323 for (int userId : userIds) {
324 if (enabled) {
325 registerServiceLocked(component, userId);
326 } else {
327 unregisterServiceLocked(component, userId);
328 }
Chris Wren51017d02015-12-15 15:34:46 -0500329 }
330 }
331
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800332 public void setCategoryState(String category, boolean enabled) {
333 synchronized (mMutex) {
334 final Boolean previous = mCategoryEnabled.put(category, enabled);
335 if (!(previous == null || previous != enabled)) {
336 return;
337 }
338
339 // State changed
340 if (DEBUG) {
341 Slog.d(TAG, ((enabled) ? "Enabling " : "Disabling ") + "category " + category);
342 }
343
344 final int[] userIds = mUserProfiles.getCurrentProfileIds();
345 for (int userId : userIds) {
346 final Set<ComponentName> componentNames = queryPackageForServices(null,
347 userId, category);
348
349 // Disallow services not enabled in Settings
350 final ArraySet<ComponentName> userComponents =
351 loadComponentNamesFromSetting(mConfig.secureSettingName, userId);
352 if (userComponents == null) {
353 componentNames.clear();
354 } else {
355 componentNames.retainAll(userComponents);
356 }
357
358 if (DEBUG) {
359 Slog.d(TAG, "Components for category " + category + ": " + componentNames);
360 }
361 for (ComponentName c : componentNames) {
362 if (enabled) {
363 registerServiceLocked(c, userId);
364 } else {
365 unregisterServiceLocked(c, userId);
366 }
367 }
368 }
369
370 }
371 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200372
373 private void rebuildRestoredPackages() {
374 mRestoredPackages.clear();
Chris Wrenab41eec2016-01-04 18:01:27 -0500375 mSnoozingForCurrentProfiles.clear();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200376 String settingName = restoredSettingName(mConfig);
John Spurlock7340fc82014-04-24 18:50:12 -0400377 int[] userIds = mUserProfiles.getCurrentProfileIds();
378 final int N = userIds.length;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200379 for (int i = 0; i < N; ++i) {
380 ArraySet<ComponentName> names = loadComponentNamesFromSetting(settingName, userIds[i]);
381 if (names == null)
382 continue;
383 for (ComponentName name: names) {
384 mRestoredPackages.add(name.getPackageName());
385 }
John Spurlock7340fc82014-04-24 18:50:12 -0400386 }
387 }
388
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200389
Julia Reynoldsc279b992015-10-30 08:23:51 -0400390 protected ArraySet<ComponentName> loadComponentNamesFromSetting(String settingName,
391 int userId) {
Christopher Tate6597e342015-02-17 12:15:25 -0800392 final ContentResolver cr = mContext.getContentResolver();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200393 String settingValue = Settings.Secure.getStringForUser(
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800394 cr,
395 settingName,
396 userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200397 if (TextUtils.isEmpty(settingValue))
398 return null;
399 String[] restored = settingValue.split(ENABLED_SERVICES_SEPARATOR);
400 ArraySet<ComponentName> result = new ArraySet<>(restored.length);
401 for (int i = 0; i < restored.length; i++) {
402 ComponentName value = ComponentName.unflattenFromString(restored[i]);
403 if (null != value) {
404 result.add(value);
Christopher Tate6597e342015-02-17 12:15:25 -0800405 }
406 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200407 return result;
408 }
John Spurlock7340fc82014-04-24 18:50:12 -0400409
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200410 private void storeComponentsToSetting(Set<ComponentName> components,
411 String settingName,
412 int userId) {
413 String[] componentNames = null;
414 if (null != components) {
415 componentNames = new String[components.size()];
416 int index = 0;
417 for (ComponentName c: components) {
418 componentNames[index++] = c.flattenToString();
419 }
420 }
421 final String value = (componentNames == null) ? "" :
422 TextUtils.join(ENABLED_SERVICES_SEPARATOR, componentNames);
423 final ContentResolver cr = mContext.getContentResolver();
424 Settings.Secure.putStringForUser(
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800425 cr,
426 settingName,
427 value,
428 userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200429 }
430
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200431 /**
432 * Remove access for any services that no longer exist.
433 */
434 private void updateSettingsAccordingToInstalledServices() {
435 int[] userIds = mUserProfiles.getCurrentProfileIds();
436 final int N = userIds.length;
437 for (int i = 0; i < N; ++i) {
438 updateSettingsAccordingToInstalledServices(userIds[i]);
439 }
440 rebuildRestoredPackages();
441 }
442
Julia Reynoldsc279b992015-10-30 08:23:51 -0400443 protected Set<ComponentName> queryPackageForServices(String packageName, int userId) {
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800444 return queryPackageForServices(packageName, userId, null);
445 }
446
447 protected Set<ComponentName> queryPackageForServices(String packageName, int userId,
448 String category) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200449 Set<ComponentName> installed = new ArraySet<>();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200450 final PackageManager pm = mContext.getPackageManager();
Julia Reynoldsc279b992015-10-30 08:23:51 -0400451 Intent queryIntent = new Intent(mConfig.serviceInterface);
452 if (!TextUtils.isEmpty(packageName)) {
453 queryIntent.setPackage(packageName);
454 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800455 if (category != null) {
456 queryIntent.addCategory(category);
457 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200458 List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
Julia Reynoldsc279b992015-10-30 08:23:51 -0400459 queryIntent,
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200460 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
461 userId);
462 if (DEBUG)
463 Slog.v(TAG, mConfig.serviceInterface + " services: " + installedServices);
Julia Reynolds50f05142015-10-30 17:03:59 -0400464 if (installedServices != null) {
465 for (int i = 0, count = installedServices.size(); i < count; i++) {
466 ResolveInfo resolveInfo = installedServices.get(i);
467 ServiceInfo info = resolveInfo.serviceInfo;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200468
Julia Reynolds50f05142015-10-30 17:03:59 -0400469 ComponentName component = new ComponentName(info.packageName, info.name);
470 if (!mConfig.bindPermission.equals(info.permission)) {
471 Slog.w(TAG, "Skipping " + getCaption() + " service "
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800472 + info.packageName + "/" + info.name
473 + ": it does not require the permission "
474 + mConfig.bindPermission);
Julia Reynolds50f05142015-10-30 17:03:59 -0400475 continue;
476 }
477 installed.add(component);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200478 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200479 }
Julia Reynoldsc279b992015-10-30 08:23:51 -0400480 return installed;
481 }
482
483 private void updateSettingsAccordingToInstalledServices(int userId) {
484 boolean restoredChanged = false;
485 boolean currentChanged = false;
486 Set<ComponentName> restored =
487 loadComponentNamesFromSetting(restoredSettingName(mConfig), userId);
488 Set<ComponentName> current =
489 loadComponentNamesFromSetting(mConfig.secureSettingName, userId);
490 // Load all services for all packages.
491 Set<ComponentName> installed = queryPackageForServices(null, userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200492
493 ArraySet<ComponentName> retained = new ArraySet<>();
494
495 for (ComponentName component : installed) {
496 if (null != restored) {
497 boolean wasRestored = restored.remove(component);
498 if (wasRestored) {
499 // Freshly installed package has service that was mentioned in restored setting.
500 if (DEBUG)
501 Slog.v(TAG, "Restoring " + component + " for user " + userId);
502 restoredChanged = true;
503 currentChanged = true;
504 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400505 continue;
506 }
John Spurlock7340fc82014-04-24 18:50:12 -0400507 }
508
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200509 if (null != current) {
510 if (current.contains(component))
511 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400512 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200513 }
514
515 currentChanged |= ((current == null ? 0 : current.size()) != retained.size());
516
517 if (currentChanged) {
518 if (DEBUG) Slog.v(TAG, "List of " + getCaption() + " services was updated " + current);
519 storeComponentsToSetting(retained, mConfig.secureSettingName, userId);
520 }
521
522 if (restoredChanged) {
523 if (DEBUG) Slog.v(TAG,
524 "List of " + getCaption() + " restored services was updated " + restored);
525 storeComponentsToSetting(restored, restoredSettingName(mConfig), userId);
John Spurlock7340fc82014-04-24 18:50:12 -0400526 }
527 }
528
529 /**
530 * Called whenever packages change, the user switches, or the secure setting
531 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
532 */
533 private void rebindServices() {
534 if (DEBUG) Slog.d(TAG, "rebindServices");
535 final int[] userIds = mUserProfiles.getCurrentProfileIds();
536 final int nUserIds = userIds.length;
537
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200538 final SparseArray<ArraySet<ComponentName>> componentsByUser = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400539
540 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200541 componentsByUser.put(userIds[i],
542 loadComponentNamesFromSetting(mConfig.secureSettingName, userIds[i]));
John Spurlock7340fc82014-04-24 18:50:12 -0400543 }
544
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200545 final ArrayList<ManagedServiceInfo> toRemove = new ArrayList<>();
546 final SparseArray<ArrayList<ComponentName>> toAdd = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400547
548 synchronized (mMutex) {
Christoph Studer5d423842014-05-23 13:15:54 +0200549 // Unbind automatically bound services, retain system services.
550 for (ManagedServiceInfo service : mServices) {
Chris Wren51017d02015-12-15 15:34:46 -0500551 if (!service.isSystem && !service.isGuest(this)) {
Christoph Studer5d423842014-05-23 13:15:54 +0200552 toRemove.add(service);
553 }
554 }
John Spurlock7340fc82014-04-24 18:50:12 -0400555
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200556 final ArraySet<ComponentName> newEnabled = new ArraySet<>();
557 final ArraySet<String> newPackages = new ArraySet<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400558
559 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200560 // decode the list of components
561 final ArraySet<ComponentName> userComponents = componentsByUser.get(userIds[i]);
562 if (null == userComponents) {
563 toAdd.put(userIds[i], new ArrayList<ComponentName>());
564 continue;
565 }
566
567 final ArrayList<ComponentName> add = new ArrayList<>(userComponents);
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800568
569 // Remove components from disabled categories so that those services aren't run.
570 for (Entry<String, Boolean> e : mCategoryEnabled.entrySet()) {
571 if (!e.getValue()) {
572 Set<ComponentName> c = queryPackageForServices(null, userIds[i],
573 e.getKey());
574 add.removeAll(c);
575 }
576 }
Chris Wrenab41eec2016-01-04 18:01:27 -0500577 add.removeAll(mSnoozingForCurrentProfiles);
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800578
John Spurlock7340fc82014-04-24 18:50:12 -0400579 toAdd.put(userIds[i], add);
580
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200581 newEnabled.addAll(userComponents);
John Spurlock7340fc82014-04-24 18:50:12 -0400582
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200583 for (int j = 0; j < userComponents.size(); j++) {
Chris Wren083094c2015-12-15 16:25:07 -0500584 final ComponentName component = userComponents.valueAt(j);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200585 newPackages.add(component.getPackageName());
John Spurlock7340fc82014-04-24 18:50:12 -0400586 }
587 }
588 mEnabledServicesForCurrentProfiles = newEnabled;
589 mEnabledServicesPackageNames = newPackages;
590 }
591
592 for (ManagedServiceInfo info : toRemove) {
593 final ComponentName component = info.component;
594 final int oldUser = info.userid;
595 Slog.v(TAG, "disabling " + getCaption() + " for user "
596 + oldUser + ": " + component);
597 unregisterService(component, info.userid);
598 }
599
600 for (int i = 0; i < nUserIds; ++i) {
601 final ArrayList<ComponentName> add = toAdd.get(userIds[i]);
602 final int N = add.size();
603 for (int j = 0; j < N; j++) {
604 final ComponentName component = add.get(j);
605 Slog.v(TAG, "enabling " + getCaption() + " for user " + userIds[i] + ": "
606 + component);
607 registerService(component, userIds[i]);
608 }
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
623 private void registerServiceLocked(final ComponentName name, final int userid) {
John Spurlock7340fc82014-04-24 18:50:12 -0400624 if (DEBUG) Slog.v(TAG, "registerService: " + name + " u=" + userid);
625
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800626 final String servicesBindingTag = name.toString() + "/" + userid;
627 if (mServicesBinding.contains(servicesBindingTag)) {
628 // stop registering this thing already! we're working on it
629 return;
630 }
631 mServicesBinding.add(servicesBindingTag);
John Spurlock7340fc82014-04-24 18:50:12 -0400632
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800633 final int N = mServices.size();
634 for (int i = N - 1; i >= 0; i--) {
635 final ManagedServiceInfo info = mServices.get(i);
636 if (name.equals(info.component)
637 && info.userid == userid) {
638 // cut old connections
639 if (DEBUG) Slog.v(TAG, " disconnecting old " + getCaption() + ": "
640 + info.service);
641 removeServiceLocked(i);
642 if (info.connection != null) {
643 mContext.unbindService(info.connection);
John Spurlock7340fc82014-04-24 18:50:12 -0400644 }
645 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800646 }
John Spurlock7340fc82014-04-24 18:50:12 -0400647
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800648 Intent intent = new Intent(mConfig.serviceInterface);
649 intent.setComponent(name);
John Spurlock7340fc82014-04-24 18:50:12 -0400650
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800651 intent.putExtra(Intent.EXTRA_CLIENT_LABEL, mConfig.clientLabel);
John Spurlock7340fc82014-04-24 18:50:12 -0400652
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800653 final PendingIntent pendingIntent = PendingIntent.getActivity(
654 mContext, 0, new Intent(mConfig.settingsAction), 0);
655 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, pendingIntent);
John Spurlock7340fc82014-04-24 18:50:12 -0400656
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800657 ApplicationInfo appInfo = null;
658 try {
659 appInfo = mContext.getPackageManager().getApplicationInfo(
660 name.getPackageName(), 0);
661 } catch (NameNotFoundException e) {
662 // Ignore if the package doesn't exist we won't be able to bind to the service.
663 }
664 final int targetSdkVersion =
665 appInfo != null ? appInfo.targetSdkVersion : Build.VERSION_CODES.BASE;
John Spurlock7340fc82014-04-24 18:50:12 -0400666
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800667 try {
668 if (DEBUG) Slog.v(TAG, "binding: " + intent);
669 ServiceConnection serviceConnection = new ServiceConnection() {
670 IInterface mService;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200671
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800672 @Override
673 public void onServiceConnected(ComponentName name, IBinder binder) {
674 boolean added = false;
675 ManagedServiceInfo info = null;
676 synchronized (mMutex) {
677 mServicesBinding.remove(servicesBindingTag);
678 try {
679 mService = asInterface(binder);
680 info = newServiceInfo(mService, name,
681 userid, false /*isSystem*/, this, targetSdkVersion);
682 binder.linkToDeath(info, 0);
683 added = mServices.add(info);
684 } catch (RemoteException e) {
685 // already dead
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200686 }
687 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800688 if (added) {
689 onServiceAdded(info);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200690 }
John Spurlock7340fc82014-04-24 18:50:12 -0400691 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800692
693 @Override
694 public void onServiceDisconnected(ComponentName name) {
695 Slog.v(TAG, getCaption() + " connection lost: " + name);
696 }
697 };
698 if (!mContext.bindServiceAsUser(intent,
699 serviceConnection,
700 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
701 new UserHandle(userid))) {
702 mServicesBinding.remove(servicesBindingTag);
703 Slog.w(TAG, "Unable to bind " + getCaption() + " service: " + intent);
John Spurlock7340fc82014-04-24 18:50:12 -0400704 return;
705 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800706 } catch (SecurityException ex) {
707 Slog.e(TAG, "Unable to bind " + getCaption() + " service: " + intent, ex);
708 return;
John Spurlock7340fc82014-04-24 18:50:12 -0400709 }
710 }
711
712 /**
713 * Remove a service for the given user by ComponentName
714 */
715 private void unregisterService(ComponentName name, int userid) {
716 synchronized (mMutex) {
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800717 unregisterServiceLocked(name, userid);
718 }
719 }
720
721 private void unregisterServiceLocked(ComponentName name, int userid) {
722 final int N = mServices.size();
723 for (int i = N - 1; i >= 0; i--) {
724 final ManagedServiceInfo info = mServices.get(i);
725 if (name.equals(info.component)
726 && info.userid == userid) {
727 removeServiceLocked(i);
728 if (info.connection != null) {
729 try {
730 mContext.unbindService(info.connection);
731 } catch (IllegalArgumentException ex) {
732 // something happened to the service: we think we have a connection
733 // but it's bogus.
734 Slog.e(TAG, getCaption() + " " + name + " could not be unbound: " + ex);
John Spurlock7340fc82014-04-24 18:50:12 -0400735 }
736 }
737 }
738 }
739 }
740
741 /**
742 * Removes a service from the list but does not unbind
743 *
744 * @return the removed service.
745 */
746 private ManagedServiceInfo removeServiceImpl(IInterface service, final int userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400747 if (DEBUG) Slog.d(TAG, "removeServiceImpl service=" + service + " u=" + userid);
John Spurlock7340fc82014-04-24 18:50:12 -0400748 ManagedServiceInfo serviceInfo = null;
749 synchronized (mMutex) {
750 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200751 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400752 final ManagedServiceInfo info = mServices.get(i);
753 if (info.service.asBinder() == service.asBinder()
754 && info.userid == userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400755 if (DEBUG) Slog.d(TAG, "Removing active service " + info.component);
756 serviceInfo = removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400757 }
758 }
759 }
760 return serviceInfo;
761 }
762
John Spurlocke77bb362014-04-26 10:24:59 -0400763 private ManagedServiceInfo removeServiceLocked(int i) {
764 final ManagedServiceInfo info = mServices.remove(i);
765 onServiceRemovedLocked(info);
766 return info;
767 }
768
John Spurlock7340fc82014-04-24 18:50:12 -0400769 private void checkNotNull(IInterface service) {
770 if (service == null) {
771 throw new IllegalArgumentException(getCaption() + " must not be null");
772 }
773 }
774
Christoph Studer3e144d32014-05-22 16:48:40 +0200775 private ManagedServiceInfo registerServiceImpl(final IInterface service,
John Spurlock7340fc82014-04-24 18:50:12 -0400776 final ComponentName component, final int userid) {
Chris Wren51017d02015-12-15 15:34:46 -0500777 ManagedServiceInfo info = newServiceInfo(service, component, userid,
778 true /*isSystem*/, null /*connection*/, Build.VERSION_CODES.LOLLIPOP);
779 return registerServiceImpl(info);
780 }
781
782 private ManagedServiceInfo registerServiceImpl(ManagedServiceInfo info) {
John Spurlock7340fc82014-04-24 18:50:12 -0400783 synchronized (mMutex) {
784 try {
Chris Wren51017d02015-12-15 15:34:46 -0500785 info.service.asBinder().linkToDeath(info, 0);
John Spurlock7340fc82014-04-24 18:50:12 -0400786 mServices.add(info);
Christoph Studer3e144d32014-05-22 16:48:40 +0200787 return info;
John Spurlock7340fc82014-04-24 18:50:12 -0400788 } catch (RemoteException e) {
789 // already dead
790 }
791 }
Christoph Studer3e144d32014-05-22 16:48:40 +0200792 return null;
John Spurlock7340fc82014-04-24 18:50:12 -0400793 }
794
795 /**
796 * Removes a service from the list and unbinds.
797 */
798 private void unregisterServiceImpl(IInterface service, int userid) {
799 ManagedServiceInfo info = removeServiceImpl(service, userid);
Chris Wren51017d02015-12-15 15:34:46 -0500800 if (info != null && info.connection != null && !info.isGuest(this)) {
John Spurlock7340fc82014-04-24 18:50:12 -0400801 mContext.unbindService(info.connection);
802 }
803 }
804
805 private class SettingsObserver extends ContentObserver {
806 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(mConfig.secureSettingName);
807
808 private SettingsObserver(Handler handler) {
809 super(handler);
810 }
811
812 private void observe() {
813 ContentResolver resolver = mContext.getContentResolver();
814 resolver.registerContentObserver(mSecureSettingsUri,
815 false, this, UserHandle.USER_ALL);
816 update(null);
817 }
818
819 @Override
820 public void onChange(boolean selfChange, Uri uri) {
821 update(uri);
822 }
823
824 private void update(Uri uri) {
825 if (uri == null || mSecureSettingsUri.equals(uri)) {
Christoph Studerb53dfd42014-09-12 14:45:59 +0200826 if (DEBUG) Slog.d(TAG, "Setting changed: mSecureSettingsUri=" + mSecureSettingsUri +
827 " / uri=" + uri);
John Spurlock7340fc82014-04-24 18:50:12 -0400828 rebindServices();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200829 rebuildRestoredPackages();
John Spurlock7340fc82014-04-24 18:50:12 -0400830 }
831 }
832 }
833
834 public class ManagedServiceInfo implements IBinder.DeathRecipient {
835 public IInterface service;
836 public ComponentName component;
837 public int userid;
838 public boolean isSystem;
839 public ServiceConnection connection;
840 public int targetSdkVersion;
841
842 public ManagedServiceInfo(IInterface service, ComponentName component,
843 int userid, boolean isSystem, ServiceConnection connection, int targetSdkVersion) {
844 this.service = service;
845 this.component = component;
846 this.userid = userid;
847 this.isSystem = isSystem;
848 this.connection = connection;
849 this.targetSdkVersion = targetSdkVersion;
850 }
851
Chris Wren51017d02015-12-15 15:34:46 -0500852 public boolean isGuest(ManagedServices host) {
853 return ManagedServices.this != host;
854 }
855
Chris Wrenab41eec2016-01-04 18:01:27 -0500856 public ManagedServices getOwner() {
857 return ManagedServices.this;
858 }
859
John Spurlocke77bb362014-04-26 10:24:59 -0400860 @Override
861 public String toString() {
862 return new StringBuilder("ManagedServiceInfo[")
863 .append("component=").append(component)
864 .append(",userid=").append(userid)
865 .append(",isSystem=").append(isSystem)
866 .append(",targetSdkVersion=").append(targetSdkVersion)
867 .append(",connection=").append(connection == null ? null : "<connection>")
868 .append(",service=").append(service)
869 .append(']').toString();
870 }
871
John Spurlock7340fc82014-04-24 18:50:12 -0400872 public boolean enabledAndUserMatches(int nid) {
873 if (!isEnabledForCurrentProfiles()) {
874 return false;
875 }
876 if (this.userid == UserHandle.USER_ALL) return true;
877 if (nid == UserHandle.USER_ALL || nid == this.userid) return true;
878 return supportsProfiles() && mUserProfiles.isCurrentProfile(nid);
879 }
880
881 public boolean supportsProfiles() {
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700882 return targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
John Spurlock7340fc82014-04-24 18:50:12 -0400883 }
884
885 @Override
886 public void binderDied() {
John Spurlocke77bb362014-04-26 10:24:59 -0400887 if (DEBUG) Slog.d(TAG, "binderDied");
John Spurlock7340fc82014-04-24 18:50:12 -0400888 // Remove the service, but don't unbind from the service. The system will bring the
889 // service back up, and the onServiceConnected handler will readd the service with the
890 // new binding. If this isn't a bound service, and is just a registered
891 // service, just removing it from the list is all we need to do anyway.
892 removeServiceImpl(this.service, this.userid);
893 }
894
895 /** convenience method for looking in mEnabledServicesForCurrentProfiles */
896 public boolean isEnabledForCurrentProfiles() {
897 if (this.isSystem) return true;
898 if (this.connection == null) return false;
899 return mEnabledServicesForCurrentProfiles.contains(this.component);
900 }
901 }
902
Chris Wrenab41eec2016-01-04 18:01:27 -0500903 /** convenience method for looking in mEnabledServicesForCurrentProfiles */
904 public boolean isComponentEnabledForCurrentProfiles(ComponentName component) {
905 return mEnabledServicesForCurrentProfiles.contains(component);
906 }
907
John Spurlock7340fc82014-04-24 18:50:12 -0400908 public static class UserProfiles {
909 // Profiles of the current user.
910 private final SparseArray<UserInfo> mCurrentProfiles = new SparseArray<UserInfo>();
911
912 public void updateCache(Context context) {
913 UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
914 if (userManager != null) {
915 int currentUserId = ActivityManager.getCurrentUser();
916 List<UserInfo> profiles = userManager.getProfiles(currentUserId);
917 synchronized (mCurrentProfiles) {
918 mCurrentProfiles.clear();
919 for (UserInfo user : profiles) {
920 mCurrentProfiles.put(user.id, user);
921 }
922 }
923 }
924 }
925
926 public int[] getCurrentProfileIds() {
927 synchronized (mCurrentProfiles) {
928 int[] users = new int[mCurrentProfiles.size()];
929 final int N = mCurrentProfiles.size();
930 for (int i = 0; i < N; ++i) {
931 users[i] = mCurrentProfiles.keyAt(i);
932 }
933 return users;
934 }
935 }
936
937 public boolean isCurrentProfile(int userId) {
938 synchronized (mCurrentProfiles) {
939 return mCurrentProfiles.get(userId) != null;
940 }
941 }
942 }
943
944 protected static class Config {
945 String caption;
946 String serviceInterface;
947 String secureSettingName;
948 String bindPermission;
949 String settingsAction;
950 int clientLabel;
951 }
952}