blob: 29d52c1739ba7a1dfb03a7ceef9641c20c927e4d [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
Julia Reynoldsa3dcaff2016-02-03 15:04:05 -0500253 public void onUserUnlocked(int user) {
254 if (DEBUG) Slog.d(TAG, "onUserUnlocked u=" + user);
255 rebuildRestoredPackages();
256 rebindServices();
257 }
258
Chris Wrenab41eec2016-01-04 18:01:27 -0500259 public ManagedServiceInfo getServiceFromTokenLocked(IInterface service) {
260 if (service == null) {
261 return null;
262 }
John Spurlock7340fc82014-04-24 18:50:12 -0400263 final IBinder token = service.asBinder();
264 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200265 for (int i = 0; i < N; i++) {
John Spurlock7340fc82014-04-24 18:50:12 -0400266 final ManagedServiceInfo info = mServices.get(i);
267 if (info.service.asBinder() == token) return info;
268 }
Chris Wrenab41eec2016-01-04 18:01:27 -0500269 return null;
270 }
271
272 public ManagedServiceInfo checkServiceTokenLocked(IInterface service) {
273 checkNotNull(service);
274 ManagedServiceInfo info = getServiceFromTokenLocked(service);
275 if (info != null) {
276 return info;
277 }
John Spurlock7340fc82014-04-24 18:50:12 -0400278 throw new SecurityException("Disallowed call from unknown " + getCaption() + ": "
279 + service);
280 }
281
282 public void unregisterService(IInterface service, int userid) {
283 checkNotNull(service);
284 // no need to check permissions; if your service binder is in the list,
285 // that's proof that you had permission to add it in the first place
286 unregisterServiceImpl(service, userid);
287 }
288
289 public void registerService(IInterface service, ComponentName component, int userid) {
290 checkNotNull(service);
Christoph Studer3e144d32014-05-22 16:48:40 +0200291 ManagedServiceInfo info = registerServiceImpl(service, component, userid);
292 if (info != null) {
293 onServiceAdded(info);
294 }
John Spurlock7340fc82014-04-24 18:50:12 -0400295 }
296
Chris Wren51017d02015-12-15 15:34:46 -0500297 /**
298 * Add a service to our callbacks. The lifecycle of this service is managed externally,
299 * but unlike a system service, it should not be considered privledged.
300 * */
301 public void registerGuestService(ManagedServiceInfo guest) {
302 checkNotNull(guest.service);
303 checkType(guest.service);
304 if (registerServiceImpl(guest) != null) {
305 onServiceAdded(guest);
Chris Wrenab41eec2016-01-04 18:01:27 -0500306 }
307 }
308
309 public void setComponentState(ComponentName component, boolean enabled) {
310 boolean previous = !mSnoozingForCurrentProfiles.contains(component);
311 if (previous == enabled) {
312 return;
313 }
314
315 if (enabled) {
316 mSnoozingForCurrentProfiles.remove(component);
317 } else {
318 mSnoozingForCurrentProfiles.add(component);
319 }
320
321 // State changed
322 if (DEBUG) {
323 Slog.d(TAG, ((enabled) ? "Enabling " : "Disabling ") + "component " +
324 component.flattenToShortString());
325 }
326
327 final int[] userIds = mUserProfiles.getCurrentProfileIds();
328 for (int userId : userIds) {
329 if (enabled) {
330 registerServiceLocked(component, userId);
331 } else {
332 unregisterServiceLocked(component, userId);
333 }
Chris Wren51017d02015-12-15 15:34:46 -0500334 }
335 }
336
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800337 public void setCategoryState(String category, boolean enabled) {
338 synchronized (mMutex) {
339 final Boolean previous = mCategoryEnabled.put(category, enabled);
340 if (!(previous == null || previous != enabled)) {
341 return;
342 }
343
344 // State changed
345 if (DEBUG) {
346 Slog.d(TAG, ((enabled) ? "Enabling " : "Disabling ") + "category " + category);
347 }
348
349 final int[] userIds = mUserProfiles.getCurrentProfileIds();
350 for (int userId : userIds) {
351 final Set<ComponentName> componentNames = queryPackageForServices(null,
352 userId, category);
353
354 // Disallow services not enabled in Settings
355 final ArraySet<ComponentName> userComponents =
356 loadComponentNamesFromSetting(mConfig.secureSettingName, userId);
357 if (userComponents == null) {
358 componentNames.clear();
359 } else {
360 componentNames.retainAll(userComponents);
361 }
362
363 if (DEBUG) {
364 Slog.d(TAG, "Components for category " + category + ": " + componentNames);
365 }
366 for (ComponentName c : componentNames) {
367 if (enabled) {
368 registerServiceLocked(c, userId);
369 } else {
370 unregisterServiceLocked(c, userId);
371 }
372 }
373 }
374
375 }
376 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200377
378 private void rebuildRestoredPackages() {
379 mRestoredPackages.clear();
Chris Wrenab41eec2016-01-04 18:01:27 -0500380 mSnoozingForCurrentProfiles.clear();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200381 String settingName = restoredSettingName(mConfig);
John Spurlock7340fc82014-04-24 18:50:12 -0400382 int[] userIds = mUserProfiles.getCurrentProfileIds();
383 final int N = userIds.length;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200384 for (int i = 0; i < N; ++i) {
385 ArraySet<ComponentName> names = loadComponentNamesFromSetting(settingName, userIds[i]);
386 if (names == null)
387 continue;
388 for (ComponentName name: names) {
389 mRestoredPackages.add(name.getPackageName());
390 }
John Spurlock7340fc82014-04-24 18:50:12 -0400391 }
392 }
393
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200394
Julia Reynoldsc279b992015-10-30 08:23:51 -0400395 protected ArraySet<ComponentName> loadComponentNamesFromSetting(String settingName,
396 int userId) {
Christopher Tate6597e342015-02-17 12:15:25 -0800397 final ContentResolver cr = mContext.getContentResolver();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200398 String settingValue = Settings.Secure.getStringForUser(
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800399 cr,
400 settingName,
401 userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200402 if (TextUtils.isEmpty(settingValue))
403 return null;
404 String[] restored = settingValue.split(ENABLED_SERVICES_SEPARATOR);
405 ArraySet<ComponentName> result = new ArraySet<>(restored.length);
406 for (int i = 0; i < restored.length; i++) {
407 ComponentName value = ComponentName.unflattenFromString(restored[i]);
408 if (null != value) {
409 result.add(value);
Christopher Tate6597e342015-02-17 12:15:25 -0800410 }
411 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200412 return result;
413 }
John Spurlock7340fc82014-04-24 18:50:12 -0400414
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200415 private void storeComponentsToSetting(Set<ComponentName> components,
416 String settingName,
417 int userId) {
418 String[] componentNames = null;
419 if (null != components) {
420 componentNames = new String[components.size()];
421 int index = 0;
422 for (ComponentName c: components) {
423 componentNames[index++] = c.flattenToString();
424 }
425 }
426 final String value = (componentNames == null) ? "" :
427 TextUtils.join(ENABLED_SERVICES_SEPARATOR, componentNames);
428 final ContentResolver cr = mContext.getContentResolver();
429 Settings.Secure.putStringForUser(
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800430 cr,
431 settingName,
432 value,
433 userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200434 }
435
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200436 /**
437 * Remove access for any services that no longer exist.
438 */
439 private void updateSettingsAccordingToInstalledServices() {
440 int[] userIds = mUserProfiles.getCurrentProfileIds();
441 final int N = userIds.length;
442 for (int i = 0; i < N; ++i) {
443 updateSettingsAccordingToInstalledServices(userIds[i]);
444 }
445 rebuildRestoredPackages();
446 }
447
Julia Reynoldsc279b992015-10-30 08:23:51 -0400448 protected Set<ComponentName> queryPackageForServices(String packageName, int userId) {
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800449 return queryPackageForServices(packageName, userId, null);
450 }
451
452 protected Set<ComponentName> queryPackageForServices(String packageName, int userId,
453 String category) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200454 Set<ComponentName> installed = new ArraySet<>();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200455 final PackageManager pm = mContext.getPackageManager();
Julia Reynoldsc279b992015-10-30 08:23:51 -0400456 Intent queryIntent = new Intent(mConfig.serviceInterface);
457 if (!TextUtils.isEmpty(packageName)) {
458 queryIntent.setPackage(packageName);
459 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800460 if (category != null) {
461 queryIntent.addCategory(category);
462 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200463 List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
Julia Reynoldsc279b992015-10-30 08:23:51 -0400464 queryIntent,
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200465 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
466 userId);
467 if (DEBUG)
468 Slog.v(TAG, mConfig.serviceInterface + " services: " + installedServices);
Julia Reynolds50f05142015-10-30 17:03:59 -0400469 if (installedServices != null) {
470 for (int i = 0, count = installedServices.size(); i < count; i++) {
471 ResolveInfo resolveInfo = installedServices.get(i);
472 ServiceInfo info = resolveInfo.serviceInfo;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200473
Julia Reynolds50f05142015-10-30 17:03:59 -0400474 ComponentName component = new ComponentName(info.packageName, info.name);
475 if (!mConfig.bindPermission.equals(info.permission)) {
476 Slog.w(TAG, "Skipping " + getCaption() + " service "
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800477 + info.packageName + "/" + info.name
478 + ": it does not require the permission "
479 + mConfig.bindPermission);
Julia Reynolds50f05142015-10-30 17:03:59 -0400480 continue;
481 }
482 installed.add(component);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200483 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200484 }
Julia Reynoldsc279b992015-10-30 08:23:51 -0400485 return installed;
486 }
487
488 private void updateSettingsAccordingToInstalledServices(int userId) {
489 boolean restoredChanged = false;
490 boolean currentChanged = false;
491 Set<ComponentName> restored =
492 loadComponentNamesFromSetting(restoredSettingName(mConfig), userId);
493 Set<ComponentName> current =
494 loadComponentNamesFromSetting(mConfig.secureSettingName, userId);
495 // Load all services for all packages.
496 Set<ComponentName> installed = queryPackageForServices(null, userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200497
498 ArraySet<ComponentName> retained = new ArraySet<>();
499
500 for (ComponentName component : installed) {
501 if (null != restored) {
502 boolean wasRestored = restored.remove(component);
503 if (wasRestored) {
504 // Freshly installed package has service that was mentioned in restored setting.
505 if (DEBUG)
506 Slog.v(TAG, "Restoring " + component + " for user " + userId);
507 restoredChanged = true;
508 currentChanged = true;
509 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400510 continue;
511 }
John Spurlock7340fc82014-04-24 18:50:12 -0400512 }
513
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200514 if (null != current) {
515 if (current.contains(component))
516 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400517 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200518 }
519
520 currentChanged |= ((current == null ? 0 : current.size()) != retained.size());
521
522 if (currentChanged) {
523 if (DEBUG) Slog.v(TAG, "List of " + getCaption() + " services was updated " + current);
524 storeComponentsToSetting(retained, mConfig.secureSettingName, userId);
525 }
526
527 if (restoredChanged) {
528 if (DEBUG) Slog.v(TAG,
529 "List of " + getCaption() + " restored services was updated " + restored);
530 storeComponentsToSetting(restored, restoredSettingName(mConfig), userId);
John Spurlock7340fc82014-04-24 18:50:12 -0400531 }
532 }
533
534 /**
535 * Called whenever packages change, the user switches, or the secure setting
536 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
537 */
538 private void rebindServices() {
539 if (DEBUG) Slog.d(TAG, "rebindServices");
540 final int[] userIds = mUserProfiles.getCurrentProfileIds();
541 final int nUserIds = userIds.length;
542
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200543 final SparseArray<ArraySet<ComponentName>> componentsByUser = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400544
545 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200546 componentsByUser.put(userIds[i],
547 loadComponentNamesFromSetting(mConfig.secureSettingName, userIds[i]));
John Spurlock7340fc82014-04-24 18:50:12 -0400548 }
549
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200550 final ArrayList<ManagedServiceInfo> toRemove = new ArrayList<>();
551 final SparseArray<ArrayList<ComponentName>> toAdd = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400552
553 synchronized (mMutex) {
Christoph Studer5d423842014-05-23 13:15:54 +0200554 // Unbind automatically bound services, retain system services.
555 for (ManagedServiceInfo service : mServices) {
Chris Wren51017d02015-12-15 15:34:46 -0500556 if (!service.isSystem && !service.isGuest(this)) {
Christoph Studer5d423842014-05-23 13:15:54 +0200557 toRemove.add(service);
558 }
559 }
John Spurlock7340fc82014-04-24 18:50:12 -0400560
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200561 final ArraySet<ComponentName> newEnabled = new ArraySet<>();
562 final ArraySet<String> newPackages = new ArraySet<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400563
564 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200565 // decode the list of components
566 final ArraySet<ComponentName> userComponents = componentsByUser.get(userIds[i]);
567 if (null == userComponents) {
568 toAdd.put(userIds[i], new ArrayList<ComponentName>());
569 continue;
570 }
571
572 final ArrayList<ComponentName> add = new ArrayList<>(userComponents);
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800573
574 // Remove components from disabled categories so that those services aren't run.
575 for (Entry<String, Boolean> e : mCategoryEnabled.entrySet()) {
576 if (!e.getValue()) {
577 Set<ComponentName> c = queryPackageForServices(null, userIds[i],
578 e.getKey());
579 add.removeAll(c);
580 }
581 }
Chris Wrenab41eec2016-01-04 18:01:27 -0500582 add.removeAll(mSnoozingForCurrentProfiles);
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800583
John Spurlock7340fc82014-04-24 18:50:12 -0400584 toAdd.put(userIds[i], add);
585
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200586 newEnabled.addAll(userComponents);
John Spurlock7340fc82014-04-24 18:50:12 -0400587
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200588 for (int j = 0; j < userComponents.size(); j++) {
Chris Wren083094c2015-12-15 16:25:07 -0500589 final ComponentName component = userComponents.valueAt(j);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200590 newPackages.add(component.getPackageName());
John Spurlock7340fc82014-04-24 18:50:12 -0400591 }
592 }
593 mEnabledServicesForCurrentProfiles = newEnabled;
594 mEnabledServicesPackageNames = newPackages;
595 }
596
597 for (ManagedServiceInfo info : toRemove) {
598 final ComponentName component = info.component;
599 final int oldUser = info.userid;
600 Slog.v(TAG, "disabling " + getCaption() + " for user "
601 + oldUser + ": " + component);
602 unregisterService(component, info.userid);
603 }
604
605 for (int i = 0; i < nUserIds; ++i) {
606 final ArrayList<ComponentName> add = toAdd.get(userIds[i]);
607 final int N = add.size();
608 for (int j = 0; j < N; j++) {
609 final ComponentName component = add.get(j);
610 Slog.v(TAG, "enabling " + getCaption() + " for user " + userIds[i] + ": "
611 + component);
612 registerService(component, userIds[i]);
613 }
614 }
Christoph Studerb53dfd42014-09-12 14:45:59 +0200615
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200616 mLastSeenProfileIds = userIds;
John Spurlock7340fc82014-04-24 18:50:12 -0400617 }
618
619 /**
620 * Version of registerService that takes the name of a service component to bind to.
621 */
622 private void registerService(final ComponentName name, final int userid) {
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800623 synchronized (mMutex) {
624 registerServiceLocked(name, userid);
625 }
626 }
627
628 private void registerServiceLocked(final ComponentName name, final int userid) {
John Spurlock7340fc82014-04-24 18:50:12 -0400629 if (DEBUG) Slog.v(TAG, "registerService: " + name + " u=" + userid);
630
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800631 final String servicesBindingTag = name.toString() + "/" + userid;
632 if (mServicesBinding.contains(servicesBindingTag)) {
633 // stop registering this thing already! we're working on it
634 return;
635 }
636 mServicesBinding.add(servicesBindingTag);
John Spurlock7340fc82014-04-24 18:50:12 -0400637
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800638 final int N = mServices.size();
639 for (int i = N - 1; i >= 0; i--) {
640 final ManagedServiceInfo info = mServices.get(i);
641 if (name.equals(info.component)
642 && info.userid == userid) {
643 // cut old connections
644 if (DEBUG) Slog.v(TAG, " disconnecting old " + getCaption() + ": "
645 + info.service);
646 removeServiceLocked(i);
647 if (info.connection != null) {
648 mContext.unbindService(info.connection);
John Spurlock7340fc82014-04-24 18:50:12 -0400649 }
650 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800651 }
John Spurlock7340fc82014-04-24 18:50:12 -0400652
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800653 Intent intent = new Intent(mConfig.serviceInterface);
654 intent.setComponent(name);
John Spurlock7340fc82014-04-24 18:50:12 -0400655
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800656 intent.putExtra(Intent.EXTRA_CLIENT_LABEL, mConfig.clientLabel);
John Spurlock7340fc82014-04-24 18:50:12 -0400657
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800658 final PendingIntent pendingIntent = PendingIntent.getActivity(
659 mContext, 0, new Intent(mConfig.settingsAction), 0);
660 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, pendingIntent);
John Spurlock7340fc82014-04-24 18:50:12 -0400661
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800662 ApplicationInfo appInfo = null;
663 try {
664 appInfo = mContext.getPackageManager().getApplicationInfo(
665 name.getPackageName(), 0);
666 } catch (NameNotFoundException e) {
667 // Ignore if the package doesn't exist we won't be able to bind to the service.
668 }
669 final int targetSdkVersion =
670 appInfo != null ? appInfo.targetSdkVersion : Build.VERSION_CODES.BASE;
John Spurlock7340fc82014-04-24 18:50:12 -0400671
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800672 try {
673 if (DEBUG) Slog.v(TAG, "binding: " + intent);
674 ServiceConnection serviceConnection = new ServiceConnection() {
675 IInterface mService;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200676
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800677 @Override
678 public void onServiceConnected(ComponentName name, IBinder binder) {
679 boolean added = false;
680 ManagedServiceInfo info = null;
681 synchronized (mMutex) {
682 mServicesBinding.remove(servicesBindingTag);
683 try {
684 mService = asInterface(binder);
685 info = newServiceInfo(mService, name,
686 userid, false /*isSystem*/, this, targetSdkVersion);
687 binder.linkToDeath(info, 0);
688 added = mServices.add(info);
689 } catch (RemoteException e) {
690 // already dead
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200691 }
692 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800693 if (added) {
694 onServiceAdded(info);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200695 }
John Spurlock7340fc82014-04-24 18:50:12 -0400696 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800697
698 @Override
699 public void onServiceDisconnected(ComponentName name) {
700 Slog.v(TAG, getCaption() + " connection lost: " + name);
701 }
702 };
703 if (!mContext.bindServiceAsUser(intent,
704 serviceConnection,
705 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
706 new UserHandle(userid))) {
707 mServicesBinding.remove(servicesBindingTag);
708 Slog.w(TAG, "Unable to bind " + getCaption() + " service: " + intent);
John Spurlock7340fc82014-04-24 18:50:12 -0400709 return;
710 }
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800711 } catch (SecurityException ex) {
712 Slog.e(TAG, "Unable to bind " + getCaption() + " service: " + intent, ex);
713 return;
John Spurlock7340fc82014-04-24 18:50:12 -0400714 }
715 }
716
717 /**
718 * Remove a service for the given user by ComponentName
719 */
720 private void unregisterService(ComponentName name, int userid) {
721 synchronized (mMutex) {
Ruben Brunkdd18a0b2015-12-04 16:16:31 -0800722 unregisterServiceLocked(name, userid);
723 }
724 }
725
726 private void unregisterServiceLocked(ComponentName name, int userid) {
727 final int N = mServices.size();
728 for (int i = N - 1; i >= 0; i--) {
729 final ManagedServiceInfo info = mServices.get(i);
730 if (name.equals(info.component)
731 && info.userid == userid) {
732 removeServiceLocked(i);
733 if (info.connection != null) {
734 try {
735 mContext.unbindService(info.connection);
736 } catch (IllegalArgumentException ex) {
737 // something happened to the service: we think we have a connection
738 // but it's bogus.
739 Slog.e(TAG, getCaption() + " " + name + " could not be unbound: " + ex);
John Spurlock7340fc82014-04-24 18:50:12 -0400740 }
741 }
742 }
743 }
744 }
745
746 /**
747 * Removes a service from the list but does not unbind
748 *
749 * @return the removed service.
750 */
751 private ManagedServiceInfo removeServiceImpl(IInterface service, final int userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400752 if (DEBUG) Slog.d(TAG, "removeServiceImpl service=" + service + " u=" + userid);
John Spurlock7340fc82014-04-24 18:50:12 -0400753 ManagedServiceInfo serviceInfo = null;
754 synchronized (mMutex) {
755 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200756 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400757 final ManagedServiceInfo info = mServices.get(i);
758 if (info.service.asBinder() == service.asBinder()
759 && info.userid == userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400760 if (DEBUG) Slog.d(TAG, "Removing active service " + info.component);
761 serviceInfo = removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400762 }
763 }
764 }
765 return serviceInfo;
766 }
767
John Spurlocke77bb362014-04-26 10:24:59 -0400768 private ManagedServiceInfo removeServiceLocked(int i) {
769 final ManagedServiceInfo info = mServices.remove(i);
770 onServiceRemovedLocked(info);
771 return info;
772 }
773
John Spurlock7340fc82014-04-24 18:50:12 -0400774 private void checkNotNull(IInterface service) {
775 if (service == null) {
776 throw new IllegalArgumentException(getCaption() + " must not be null");
777 }
778 }
779
Christoph Studer3e144d32014-05-22 16:48:40 +0200780 private ManagedServiceInfo registerServiceImpl(final IInterface service,
John Spurlock7340fc82014-04-24 18:50:12 -0400781 final ComponentName component, final int userid) {
Chris Wren51017d02015-12-15 15:34:46 -0500782 ManagedServiceInfo info = newServiceInfo(service, component, userid,
783 true /*isSystem*/, null /*connection*/, Build.VERSION_CODES.LOLLIPOP);
784 return registerServiceImpl(info);
785 }
786
787 private ManagedServiceInfo registerServiceImpl(ManagedServiceInfo info) {
John Spurlock7340fc82014-04-24 18:50:12 -0400788 synchronized (mMutex) {
789 try {
Chris Wren51017d02015-12-15 15:34:46 -0500790 info.service.asBinder().linkToDeath(info, 0);
John Spurlock7340fc82014-04-24 18:50:12 -0400791 mServices.add(info);
Christoph Studer3e144d32014-05-22 16:48:40 +0200792 return info;
John Spurlock7340fc82014-04-24 18:50:12 -0400793 } catch (RemoteException e) {
794 // already dead
795 }
796 }
Christoph Studer3e144d32014-05-22 16:48:40 +0200797 return null;
John Spurlock7340fc82014-04-24 18:50:12 -0400798 }
799
800 /**
801 * Removes a service from the list and unbinds.
802 */
803 private void unregisterServiceImpl(IInterface service, int userid) {
804 ManagedServiceInfo info = removeServiceImpl(service, userid);
Chris Wren51017d02015-12-15 15:34:46 -0500805 if (info != null && info.connection != null && !info.isGuest(this)) {
John Spurlock7340fc82014-04-24 18:50:12 -0400806 mContext.unbindService(info.connection);
807 }
808 }
809
810 private class SettingsObserver extends ContentObserver {
811 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(mConfig.secureSettingName);
812
813 private SettingsObserver(Handler handler) {
814 super(handler);
815 }
816
817 private void observe() {
818 ContentResolver resolver = mContext.getContentResolver();
819 resolver.registerContentObserver(mSecureSettingsUri,
820 false, this, UserHandle.USER_ALL);
821 update(null);
822 }
823
824 @Override
825 public void onChange(boolean selfChange, Uri uri) {
826 update(uri);
827 }
828
829 private void update(Uri uri) {
830 if (uri == null || mSecureSettingsUri.equals(uri)) {
Christoph Studerb53dfd42014-09-12 14:45:59 +0200831 if (DEBUG) Slog.d(TAG, "Setting changed: mSecureSettingsUri=" + mSecureSettingsUri +
832 " / uri=" + uri);
John Spurlock7340fc82014-04-24 18:50:12 -0400833 rebindServices();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200834 rebuildRestoredPackages();
John Spurlock7340fc82014-04-24 18:50:12 -0400835 }
836 }
837 }
838
839 public class ManagedServiceInfo implements IBinder.DeathRecipient {
840 public IInterface service;
841 public ComponentName component;
842 public int userid;
843 public boolean isSystem;
844 public ServiceConnection connection;
845 public int targetSdkVersion;
846
847 public ManagedServiceInfo(IInterface service, ComponentName component,
848 int userid, boolean isSystem, ServiceConnection connection, int targetSdkVersion) {
849 this.service = service;
850 this.component = component;
851 this.userid = userid;
852 this.isSystem = isSystem;
853 this.connection = connection;
854 this.targetSdkVersion = targetSdkVersion;
855 }
856
Chris Wren51017d02015-12-15 15:34:46 -0500857 public boolean isGuest(ManagedServices host) {
858 return ManagedServices.this != host;
859 }
860
Chris Wrenab41eec2016-01-04 18:01:27 -0500861 public ManagedServices getOwner() {
862 return ManagedServices.this;
863 }
864
John Spurlocke77bb362014-04-26 10:24:59 -0400865 @Override
866 public String toString() {
867 return new StringBuilder("ManagedServiceInfo[")
868 .append("component=").append(component)
869 .append(",userid=").append(userid)
870 .append(",isSystem=").append(isSystem)
871 .append(",targetSdkVersion=").append(targetSdkVersion)
872 .append(",connection=").append(connection == null ? null : "<connection>")
873 .append(",service=").append(service)
874 .append(']').toString();
875 }
876
John Spurlock7340fc82014-04-24 18:50:12 -0400877 public boolean enabledAndUserMatches(int nid) {
878 if (!isEnabledForCurrentProfiles()) {
879 return false;
880 }
881 if (this.userid == UserHandle.USER_ALL) return true;
882 if (nid == UserHandle.USER_ALL || nid == this.userid) return true;
883 return supportsProfiles() && mUserProfiles.isCurrentProfile(nid);
884 }
885
886 public boolean supportsProfiles() {
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700887 return targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
John Spurlock7340fc82014-04-24 18:50:12 -0400888 }
889
890 @Override
891 public void binderDied() {
John Spurlocke77bb362014-04-26 10:24:59 -0400892 if (DEBUG) Slog.d(TAG, "binderDied");
John Spurlock7340fc82014-04-24 18:50:12 -0400893 // Remove the service, but don't unbind from the service. The system will bring the
894 // service back up, and the onServiceConnected handler will readd the service with the
895 // new binding. If this isn't a bound service, and is just a registered
896 // service, just removing it from the list is all we need to do anyway.
897 removeServiceImpl(this.service, this.userid);
898 }
899
900 /** convenience method for looking in mEnabledServicesForCurrentProfiles */
901 public boolean isEnabledForCurrentProfiles() {
902 if (this.isSystem) return true;
903 if (this.connection == null) return false;
904 return mEnabledServicesForCurrentProfiles.contains(this.component);
905 }
906 }
907
Chris Wrenab41eec2016-01-04 18:01:27 -0500908 /** convenience method for looking in mEnabledServicesForCurrentProfiles */
909 public boolean isComponentEnabledForCurrentProfiles(ComponentName component) {
910 return mEnabledServicesForCurrentProfiles.contains(component);
911 }
912
John Spurlock7340fc82014-04-24 18:50:12 -0400913 public static class UserProfiles {
914 // Profiles of the current user.
915 private final SparseArray<UserInfo> mCurrentProfiles = new SparseArray<UserInfo>();
916
917 public void updateCache(Context context) {
918 UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
919 if (userManager != null) {
920 int currentUserId = ActivityManager.getCurrentUser();
921 List<UserInfo> profiles = userManager.getProfiles(currentUserId);
922 synchronized (mCurrentProfiles) {
923 mCurrentProfiles.clear();
924 for (UserInfo user : profiles) {
925 mCurrentProfiles.put(user.id, user);
926 }
927 }
928 }
929 }
930
931 public int[] getCurrentProfileIds() {
932 synchronized (mCurrentProfiles) {
933 int[] users = new int[mCurrentProfiles.size()];
934 final int N = mCurrentProfiles.size();
935 for (int i = 0; i < N; ++i) {
936 users[i] = mCurrentProfiles.keyAt(i);
937 }
938 return users;
939 }
940 }
941
942 public boolean isCurrentProfile(int userId) {
943 synchronized (mCurrentProfiles) {
944 return mCurrentProfiles.get(userId) != null;
945 }
946 }
947 }
948
949 protected static class Config {
950 String caption;
951 String serviceInterface;
952 String secureSettingName;
953 String bindPermission;
954 String settingsAction;
955 int clientLabel;
956 }
957}