blob: d2a264d775bffaee784d03db62e310ed78d39307 [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;
45import android.util.ArraySet;
John Spurlock4db0d982014-08-13 09:19:03 -040046import android.util.Log;
John Spurlock7340fc82014-04-24 18:50:12 -040047import android.util.Slog;
48import android.util.SparseArray;
49
John Spurlock25e2d242014-06-27 13:58:23 -040050import com.android.server.notification.NotificationManagerService.DumpFilter;
51
John Spurlock7340fc82014-04-24 18:50:12 -040052import java.io.PrintWriter;
53import java.util.ArrayList;
John Spurlocke77bb362014-04-26 10:24:59 -040054import java.util.Arrays;
John Spurlock7340fc82014-04-24 18:50:12 -040055import java.util.List;
Christopher Tate6597e342015-02-17 12:15:25 -080056import java.util.Objects;
John Spurlock7340fc82014-04-24 18:50:12 -040057import java.util.Set;
58
59/**
60 * Manages the lifecycle of application-provided services bound by system server.
61 *
62 * Services managed by this helper must have:
63 * - An associated system settings value with a list of enabled component names.
64 * - A well-known action for services to use in their intent-filter.
65 * - A system permission for services to require in order to ensure system has exclusive binding.
66 * - A settings page for user configuration of enabled services, and associated intent action.
67 * - A remote interface definition (aidl) provided by the service used for communication.
68 */
69abstract public class ManagedServices {
70 protected final String TAG = getClass().getSimpleName();
John Spurlock4db0d982014-08-13 09:19:03 -040071 protected final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
John Spurlock7340fc82014-04-24 18:50:12 -040072
Julia Reynoldsc279b992015-10-30 08:23:51 -040073 protected static final String ENABLED_SERVICES_SEPARATOR = ":";
John Spurlock7340fc82014-04-24 18:50:12 -040074
John Spurlockaf8d6c42014-05-07 17:49:08 -040075 protected final Context mContext;
John Spurlocke77bb362014-04-26 10:24:59 -040076 protected final Object mMutex;
John Spurlock7340fc82014-04-24 18:50:12 -040077 private final UserProfiles mUserProfiles;
78 private final SettingsObserver mSettingsObserver;
79 private final Config mConfig;
Christopher Tate6597e342015-02-17 12:15:25 -080080 private ArraySet<String> mRestored;
John Spurlock7340fc82014-04-24 18:50:12 -040081
82 // contains connections to all connected services, including app services
83 // and system services
84 protected final ArrayList<ManagedServiceInfo> mServices = new ArrayList<ManagedServiceInfo>();
85 // things that will be put into mServices as soon as they're ready
86 private final ArrayList<String> mServicesBinding = new ArrayList<String>();
87 // lists the component names of all enabled (and therefore connected)
88 // app services for current profiles.
89 private ArraySet<ComponentName> mEnabledServicesForCurrentProfiles
90 = new ArraySet<ComponentName>();
91 // Just the packages from mEnabledServicesForCurrentProfiles
92 private ArraySet<String> mEnabledServicesPackageNames = new ArraySet<String>();
Denis Kuznetsov76c02682015-09-17 19:57:00 +020093 // List of packages in restored setting across all mUserProfiles, for quick
94 // filtering upon package updates.
95 private ArraySet<String> mRestoredPackages = new ArraySet<>();
96
John Spurlock7340fc82014-04-24 18:50:12 -040097
Christoph Studerb53dfd42014-09-12 14:45:59 +020098 // Kept to de-dupe user change events (experienced after boot, when we receive a settings and a
99 // user change).
100 private int[] mLastSeenProfileIds;
101
Christopher Tate6597e342015-02-17 12:15:25 -0800102 private final BroadcastReceiver mRestoreReceiver;
103
John Spurlock7340fc82014-04-24 18:50:12 -0400104 public ManagedServices(Context context, Handler handler, Object mutex,
105 UserProfiles userProfiles) {
106 mContext = context;
107 mMutex = mutex;
108 mUserProfiles = userProfiles;
109 mConfig = getConfig();
110 mSettingsObserver = new SettingsObserver(handler);
Christopher Tate6597e342015-02-17 12:15:25 -0800111
112 mRestoreReceiver = new SettingRestoredReceiver();
113 IntentFilter filter = new IntentFilter(Intent.ACTION_SETTING_RESTORED);
114 context.registerReceiver(mRestoreReceiver, filter);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200115 rebuildRestoredPackages();
Christopher Tate6597e342015-02-17 12:15:25 -0800116 }
117
118 class SettingRestoredReceiver extends BroadcastReceiver {
119 @Override
120 public void onReceive(Context context, Intent intent) {
121 if (Intent.ACTION_SETTING_RESTORED.equals(intent.getAction())) {
122 String element = intent.getStringExtra(Intent.EXTRA_SETTING_NAME);
123 if (Objects.equals(element, mConfig.secureSettingName)) {
124 String prevValue = intent.getStringExtra(Intent.EXTRA_SETTING_PREVIOUS_VALUE);
125 String newValue = intent.getStringExtra(Intent.EXTRA_SETTING_NEW_VALUE);
126 settingRestored(element, prevValue, newValue, getSendingUserId());
127 }
128 }
129 }
John Spurlock7340fc82014-04-24 18:50:12 -0400130 }
131
132 abstract protected Config getConfig();
133
134 private String getCaption() {
135 return mConfig.caption;
136 }
137
138 abstract protected IInterface asInterface(IBinder binder);
139
John Spurlock3b98b3f2014-05-01 09:08:48 -0400140 abstract protected void onServiceAdded(ManagedServiceInfo info);
John Spurlock7340fc82014-04-24 18:50:12 -0400141
John Spurlocke77bb362014-04-26 10:24:59 -0400142 protected void onServiceRemovedLocked(ManagedServiceInfo removed) { }
143
John Spurlock7340fc82014-04-24 18:50:12 -0400144 private ManagedServiceInfo newServiceInfo(IInterface service,
145 ComponentName component, int userid, boolean isSystem, ServiceConnection connection,
146 int targetSdkVersion) {
147 return new ManagedServiceInfo(service, component, userid, isSystem, connection,
148 targetSdkVersion);
149 }
150
151 public void onBootPhaseAppsCanStart() {
152 mSettingsObserver.observe();
153 }
154
John Spurlock25e2d242014-06-27 13:58:23 -0400155 public void dump(PrintWriter pw, DumpFilter filter) {
John Spurlocke77bb362014-04-26 10:24:59 -0400156 pw.println(" All " + getCaption() + "s (" + mEnabledServicesForCurrentProfiles.size()
John Spurlock7340fc82014-04-24 18:50:12 -0400157 + ") enabled for current profiles:");
158 for (ComponentName cmpt : mEnabledServicesForCurrentProfiles) {
John Spurlock25e2d242014-06-27 13:58:23 -0400159 if (filter != null && !filter.matches(cmpt)) continue;
John Spurlocke77bb362014-04-26 10:24:59 -0400160 pw.println(" " + cmpt);
John Spurlock7340fc82014-04-24 18:50:12 -0400161 }
162
John Spurlocke77bb362014-04-26 10:24:59 -0400163 pw.println(" Live " + getCaption() + "s (" + mServices.size() + "):");
John Spurlock7340fc82014-04-24 18:50:12 -0400164 for (ManagedServiceInfo info : mServices) {
John Spurlock25e2d242014-06-27 13:58:23 -0400165 if (filter != null && !filter.matches(info.component)) continue;
John Spurlocke77bb362014-04-26 10:24:59 -0400166 pw.println(" " + info.component
John Spurlock7340fc82014-04-24 18:50:12 -0400167 + " (user " + info.userid + "): " + info.service
168 + (info.isSystem?" SYSTEM":""));
169 }
170 }
171
Christopher Tate6597e342015-02-17 12:15:25 -0800172 // By convention, restored settings are replicated to another settings
173 // entry, named similarly but with a disambiguation suffix.
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200174 public static String restoredSettingName(Config config) {
Christopher Tate6597e342015-02-17 12:15:25 -0800175 return config.secureSettingName + ":restored";
176 }
177
178 // The OS has done a restore of this service's saved state. We clone it to the
179 // 'restored' reserve, and then once we return and the actual write to settings is
180 // performed, our observer will do the work of maintaining the restored vs live
181 // settings data.
182 public void settingRestored(String element, String oldValue, String newValue, int userid) {
183 if (DEBUG) Slog.d(TAG, "Restored managed service setting: " + element
184 + " ovalue=" + oldValue + " nvalue=" + newValue);
185 if (mConfig.secureSettingName.equals(element)) {
186 if (element != null) {
187 mRestored = null;
188 Settings.Secure.putStringForUser(mContext.getContentResolver(),
189 restoredSettingName(mConfig),
190 newValue,
191 userid);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200192 updateSettingsAccordingToInstalledServices(userid);
193 rebuildRestoredPackages();
Christopher Tate6597e342015-02-17 12:15:25 -0800194 }
195 }
196 }
197
John Spurlock80774932015-05-07 17:38:50 -0400198 public boolean isComponentEnabledForPackage(String pkg) {
199 return mEnabledServicesPackageNames.contains(pkg);
200 }
201
John Spurlock7340fc82014-04-24 18:50:12 -0400202 public void onPackagesChanged(boolean queryReplace, String[] pkgList) {
John Spurlocke77bb362014-04-26 10:24:59 -0400203 if (DEBUG) Slog.d(TAG, "onPackagesChanged queryReplace=" + queryReplace
204 + " pkgList=" + (pkgList == null ? null : Arrays.asList(pkgList))
205 + " mEnabledServicesPackageNames=" + mEnabledServicesPackageNames);
John Spurlock7340fc82014-04-24 18:50:12 -0400206 boolean anyServicesInvolved = false;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200207
John Spurlock7340fc82014-04-24 18:50:12 -0400208 if (pkgList != null && (pkgList.length > 0)) {
209 for (String pkgName : pkgList) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200210 if (mEnabledServicesPackageNames.contains(pkgName) ||
211 mRestoredPackages.contains(pkgName)) {
John Spurlock7340fc82014-04-24 18:50:12 -0400212 anyServicesInvolved = true;
213 }
214 }
215 }
216
217 if (anyServicesInvolved) {
218 // if we're not replacing a package, clean up orphaned bits
219 if (!queryReplace) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200220 updateSettingsAccordingToInstalledServices();
221 rebuildRestoredPackages();
John Spurlock7340fc82014-04-24 18:50:12 -0400222 }
223 // make sure we're still bound to any of our services who may have just upgraded
224 rebindServices();
225 }
226 }
227
John Spurlock1b8b22b2015-05-20 09:47:13 -0400228 public void onUserSwitched(int user) {
229 if (DEBUG) Slog.d(TAG, "onUserSwitched u=" + user);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200230 rebuildRestoredPackages();
Christoph Studerb53dfd42014-09-12 14:45:59 +0200231 if (Arrays.equals(mLastSeenProfileIds, mUserProfiles.getCurrentProfileIds())) {
232 if (DEBUG) Slog.d(TAG, "Current profile IDs didn't change, skipping rebindServices().");
233 return;
234 }
235 rebindServices();
236 }
237
John Spurlock7340fc82014-04-24 18:50:12 -0400238 public ManagedServiceInfo checkServiceTokenLocked(IInterface service) {
239 checkNotNull(service);
240 final IBinder token = service.asBinder();
241 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200242 for (int i = 0; i < N; i++) {
John Spurlock7340fc82014-04-24 18:50:12 -0400243 final ManagedServiceInfo info = mServices.get(i);
244 if (info.service.asBinder() == token) return info;
245 }
246 throw new SecurityException("Disallowed call from unknown " + getCaption() + ": "
247 + service);
248 }
249
250 public void unregisterService(IInterface service, int userid) {
251 checkNotNull(service);
252 // no need to check permissions; if your service binder is in the list,
253 // that's proof that you had permission to add it in the first place
254 unregisterServiceImpl(service, userid);
255 }
256
257 public void registerService(IInterface service, ComponentName component, int userid) {
258 checkNotNull(service);
Christoph Studer3e144d32014-05-22 16:48:40 +0200259 ManagedServiceInfo info = registerServiceImpl(service, component, userid);
260 if (info != null) {
261 onServiceAdded(info);
262 }
John Spurlock7340fc82014-04-24 18:50:12 -0400263 }
264
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200265
266 private void rebuildRestoredPackages() {
267 mRestoredPackages.clear();
268 String settingName = restoredSettingName(mConfig);
John Spurlock7340fc82014-04-24 18:50:12 -0400269 int[] userIds = mUserProfiles.getCurrentProfileIds();
270 final int N = userIds.length;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200271 for (int i = 0; i < N; ++i) {
272 ArraySet<ComponentName> names = loadComponentNamesFromSetting(settingName, userIds[i]);
273 if (names == null)
274 continue;
275 for (ComponentName name: names) {
276 mRestoredPackages.add(name.getPackageName());
277 }
John Spurlock7340fc82014-04-24 18:50:12 -0400278 }
279 }
280
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200281
Julia Reynoldsc279b992015-10-30 08:23:51 -0400282 protected ArraySet<ComponentName> loadComponentNamesFromSetting(String settingName,
283 int userId) {
Christopher Tate6597e342015-02-17 12:15:25 -0800284 final ContentResolver cr = mContext.getContentResolver();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200285 String settingValue = Settings.Secure.getStringForUser(
286 cr,
287 settingName,
288 userId);
289 if (TextUtils.isEmpty(settingValue))
290 return null;
291 String[] restored = settingValue.split(ENABLED_SERVICES_SEPARATOR);
292 ArraySet<ComponentName> result = new ArraySet<>(restored.length);
293 for (int i = 0; i < restored.length; i++) {
294 ComponentName value = ComponentName.unflattenFromString(restored[i]);
295 if (null != value) {
296 result.add(value);
Christopher Tate6597e342015-02-17 12:15:25 -0800297 }
298 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200299 return result;
300 }
John Spurlock7340fc82014-04-24 18:50:12 -0400301
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200302 private void storeComponentsToSetting(Set<ComponentName> components,
303 String settingName,
304 int userId) {
305 String[] componentNames = null;
306 if (null != components) {
307 componentNames = new String[components.size()];
308 int index = 0;
309 for (ComponentName c: components) {
310 componentNames[index++] = c.flattenToString();
311 }
312 }
313 final String value = (componentNames == null) ? "" :
314 TextUtils.join(ENABLED_SERVICES_SEPARATOR, componentNames);
315 final ContentResolver cr = mContext.getContentResolver();
316 Settings.Secure.putStringForUser(
317 cr,
318 settingName,
319 value,
320 userId);
321 }
322
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200323 /**
324 * Remove access for any services that no longer exist.
325 */
326 private void updateSettingsAccordingToInstalledServices() {
327 int[] userIds = mUserProfiles.getCurrentProfileIds();
328 final int N = userIds.length;
329 for (int i = 0; i < N; ++i) {
330 updateSettingsAccordingToInstalledServices(userIds[i]);
331 }
332 rebuildRestoredPackages();
333 }
334
Julia Reynoldsc279b992015-10-30 08:23:51 -0400335 protected Set<ComponentName> queryPackageForServices(String packageName, int userId) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200336 Set<ComponentName> installed = new ArraySet<>();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200337 final PackageManager pm = mContext.getPackageManager();
Julia Reynoldsc279b992015-10-30 08:23:51 -0400338 Intent queryIntent = new Intent(mConfig.serviceInterface);
339 if (!TextUtils.isEmpty(packageName)) {
340 queryIntent.setPackage(packageName);
341 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200342 List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
Julia Reynoldsc279b992015-10-30 08:23:51 -0400343 queryIntent,
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200344 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
345 userId);
346 if (DEBUG)
347 Slog.v(TAG, mConfig.serviceInterface + " services: " + installedServices);
348
349 for (int i = 0, count = installedServices.size(); i < count; i++) {
350 ResolveInfo resolveInfo = installedServices.get(i);
351 ServiceInfo info = resolveInfo.serviceInfo;
352
353 ComponentName component = new ComponentName(info.packageName, info.name);
354 if (!mConfig.bindPermission.equals(info.permission)) {
355 Slog.w(TAG, "Skipping " + getCaption() + " service "
356 + info.packageName + "/" + info.name
357 + ": it does not require the permission "
358 + mConfig.bindPermission);
359 continue;
360 }
361 installed.add(component);
362 }
Julia Reynoldsc279b992015-10-30 08:23:51 -0400363 return installed;
364 }
365
366 private void updateSettingsAccordingToInstalledServices(int userId) {
367 boolean restoredChanged = false;
368 boolean currentChanged = false;
369 Set<ComponentName> restored =
370 loadComponentNamesFromSetting(restoredSettingName(mConfig), userId);
371 Set<ComponentName> current =
372 loadComponentNamesFromSetting(mConfig.secureSettingName, userId);
373 // Load all services for all packages.
374 Set<ComponentName> installed = queryPackageForServices(null, userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200375
376 ArraySet<ComponentName> retained = new ArraySet<>();
377
378 for (ComponentName component : installed) {
379 if (null != restored) {
380 boolean wasRestored = restored.remove(component);
381 if (wasRestored) {
382 // Freshly installed package has service that was mentioned in restored setting.
383 if (DEBUG)
384 Slog.v(TAG, "Restoring " + component + " for user " + userId);
385 restoredChanged = true;
386 currentChanged = true;
387 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400388 continue;
389 }
John Spurlock7340fc82014-04-24 18:50:12 -0400390 }
391
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200392 if (null != current) {
393 if (current.contains(component))
394 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400395 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200396 }
397
398 currentChanged |= ((current == null ? 0 : current.size()) != retained.size());
399
400 if (currentChanged) {
401 if (DEBUG) Slog.v(TAG, "List of " + getCaption() + " services was updated " + current);
402 storeComponentsToSetting(retained, mConfig.secureSettingName, userId);
403 }
404
405 if (restoredChanged) {
406 if (DEBUG) Slog.v(TAG,
407 "List of " + getCaption() + " restored services was updated " + restored);
408 storeComponentsToSetting(restored, restoredSettingName(mConfig), userId);
John Spurlock7340fc82014-04-24 18:50:12 -0400409 }
410 }
411
412 /**
413 * Called whenever packages change, the user switches, or the secure setting
414 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
415 */
416 private void rebindServices() {
417 if (DEBUG) Slog.d(TAG, "rebindServices");
418 final int[] userIds = mUserProfiles.getCurrentProfileIds();
419 final int nUserIds = userIds.length;
420
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200421 final SparseArray<ArraySet<ComponentName>> componentsByUser = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400422
423 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200424 componentsByUser.put(userIds[i],
425 loadComponentNamesFromSetting(mConfig.secureSettingName, userIds[i]));
John Spurlock7340fc82014-04-24 18:50:12 -0400426 }
427
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200428 final ArrayList<ManagedServiceInfo> toRemove = new ArrayList<>();
429 final SparseArray<ArrayList<ComponentName>> toAdd = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400430
431 synchronized (mMutex) {
Christoph Studer5d423842014-05-23 13:15:54 +0200432 // Unbind automatically bound services, retain system services.
433 for (ManagedServiceInfo service : mServices) {
434 if (!service.isSystem) {
435 toRemove.add(service);
436 }
437 }
John Spurlock7340fc82014-04-24 18:50:12 -0400438
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200439 final ArraySet<ComponentName> newEnabled = new ArraySet<>();
440 final ArraySet<String> newPackages = new ArraySet<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400441
442 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200443 // decode the list of components
444 final ArraySet<ComponentName> userComponents = componentsByUser.get(userIds[i]);
445 if (null == userComponents) {
446 toAdd.put(userIds[i], new ArrayList<ComponentName>());
447 continue;
448 }
449
450 final ArrayList<ComponentName> add = new ArrayList<>(userComponents);
John Spurlock7340fc82014-04-24 18:50:12 -0400451 toAdd.put(userIds[i], add);
452
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200453 newEnabled.addAll(userComponents);
John Spurlock7340fc82014-04-24 18:50:12 -0400454
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200455 for (int j = 0; j < userComponents.size(); j++) {
456 final ComponentName component = userComponents.valueAt(i);
457 newPackages.add(component.getPackageName());
John Spurlock7340fc82014-04-24 18:50:12 -0400458 }
459 }
460 mEnabledServicesForCurrentProfiles = newEnabled;
461 mEnabledServicesPackageNames = newPackages;
462 }
463
464 for (ManagedServiceInfo info : toRemove) {
465 final ComponentName component = info.component;
466 final int oldUser = info.userid;
467 Slog.v(TAG, "disabling " + getCaption() + " for user "
468 + oldUser + ": " + component);
469 unregisterService(component, info.userid);
470 }
471
472 for (int i = 0; i < nUserIds; ++i) {
473 final ArrayList<ComponentName> add = toAdd.get(userIds[i]);
474 final int N = add.size();
475 for (int j = 0; j < N; j++) {
476 final ComponentName component = add.get(j);
477 Slog.v(TAG, "enabling " + getCaption() + " for user " + userIds[i] + ": "
478 + component);
479 registerService(component, userIds[i]);
480 }
481 }
Christoph Studerb53dfd42014-09-12 14:45:59 +0200482
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200483 mLastSeenProfileIds = userIds;
John Spurlock7340fc82014-04-24 18:50:12 -0400484 }
485
486 /**
487 * Version of registerService that takes the name of a service component to bind to.
488 */
489 private void registerService(final ComponentName name, final int userid) {
490 if (DEBUG) Slog.v(TAG, "registerService: " + name + " u=" + userid);
491
492 synchronized (mMutex) {
493 final String servicesBindingTag = name.toString() + "/" + userid;
494 if (mServicesBinding.contains(servicesBindingTag)) {
495 // stop registering this thing already! we're working on it
496 return;
497 }
498 mServicesBinding.add(servicesBindingTag);
499
500 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200501 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400502 final ManagedServiceInfo info = mServices.get(i);
503 if (name.equals(info.component)
504 && info.userid == userid) {
505 // cut old connections
506 if (DEBUG) Slog.v(TAG, " disconnecting old " + getCaption() + ": "
507 + info.service);
John Spurlocke77bb362014-04-26 10:24:59 -0400508 removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400509 if (info.connection != null) {
510 mContext.unbindService(info.connection);
511 }
512 }
513 }
514
515 Intent intent = new Intent(mConfig.serviceInterface);
516 intent.setComponent(name);
517
518 intent.putExtra(Intent.EXTRA_CLIENT_LABEL, mConfig.clientLabel);
519
520 final PendingIntent pendingIntent = PendingIntent.getActivity(
521 mContext, 0, new Intent(mConfig.settingsAction), 0);
522 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, pendingIntent);
523
524 ApplicationInfo appInfo = null;
525 try {
526 appInfo = mContext.getPackageManager().getApplicationInfo(
527 name.getPackageName(), 0);
528 } catch (NameNotFoundException e) {
529 // Ignore if the package doesn't exist we won't be able to bind to the service.
530 }
531 final int targetSdkVersion =
532 appInfo != null ? appInfo.targetSdkVersion : Build.VERSION_CODES.BASE;
533
534 try {
535 if (DEBUG) Slog.v(TAG, "binding: " + intent);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200536 ServiceConnection serviceConnection = new ServiceConnection() {
537 IInterface mService;
538
539 @Override
540 public void onServiceConnected(ComponentName name, IBinder binder) {
541 boolean added = false;
542 ManagedServiceInfo info = null;
543 synchronized (mMutex) {
544 mServicesBinding.remove(servicesBindingTag);
545 try {
546 mService = asInterface(binder);
547 info = newServiceInfo(mService, name,
548 userid, false /*isSystem*/, this, targetSdkVersion);
549 binder.linkToDeath(info, 0);
550 added = mServices.add(info);
551 } catch (RemoteException e) {
552 // already dead
553 }
554 }
555 if (added) {
556 onServiceAdded(info);
557 }
558 }
559
560 @Override
561 public void onServiceDisconnected(ComponentName name) {
562 Slog.v(TAG, getCaption() + " connection lost: " + name);
563 }
564 };
John Spurlock7340fc82014-04-24 18:50:12 -0400565 if (!mContext.bindServiceAsUser(intent,
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200566 serviceConnection,
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700567 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200568 new UserHandle(userid))) {
John Spurlock7340fc82014-04-24 18:50:12 -0400569 mServicesBinding.remove(servicesBindingTag);
570 Slog.w(TAG, "Unable to bind " + getCaption() + " service: " + intent);
571 return;
572 }
573 } catch (SecurityException ex) {
574 Slog.e(TAG, "Unable to bind " + getCaption() + " service: " + intent, ex);
575 return;
576 }
577 }
578 }
579
580 /**
581 * Remove a service for the given user by ComponentName
582 */
583 private void unregisterService(ComponentName name, int userid) {
584 synchronized (mMutex) {
585 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200586 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400587 final ManagedServiceInfo info = mServices.get(i);
588 if (name.equals(info.component)
589 && info.userid == userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400590 removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400591 if (info.connection != null) {
592 try {
593 mContext.unbindService(info.connection);
594 } catch (IllegalArgumentException ex) {
595 // something happened to the service: we think we have a connection
596 // but it's bogus.
597 Slog.e(TAG, getCaption() + " " + name + " could not be unbound: " + ex);
598 }
599 }
600 }
601 }
602 }
603 }
604
605 /**
606 * Removes a service from the list but does not unbind
607 *
608 * @return the removed service.
609 */
610 private ManagedServiceInfo removeServiceImpl(IInterface service, final int userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400611 if (DEBUG) Slog.d(TAG, "removeServiceImpl service=" + service + " u=" + userid);
John Spurlock7340fc82014-04-24 18:50:12 -0400612 ManagedServiceInfo serviceInfo = null;
613 synchronized (mMutex) {
614 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200615 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400616 final ManagedServiceInfo info = mServices.get(i);
617 if (info.service.asBinder() == service.asBinder()
618 && info.userid == userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400619 if (DEBUG) Slog.d(TAG, "Removing active service " + info.component);
620 serviceInfo = removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400621 }
622 }
623 }
624 return serviceInfo;
625 }
626
John Spurlocke77bb362014-04-26 10:24:59 -0400627 private ManagedServiceInfo removeServiceLocked(int i) {
628 final ManagedServiceInfo info = mServices.remove(i);
629 onServiceRemovedLocked(info);
630 return info;
631 }
632
John Spurlock7340fc82014-04-24 18:50:12 -0400633 private void checkNotNull(IInterface service) {
634 if (service == null) {
635 throw new IllegalArgumentException(getCaption() + " must not be null");
636 }
637 }
638
Christoph Studer3e144d32014-05-22 16:48:40 +0200639 private ManagedServiceInfo registerServiceImpl(final IInterface service,
John Spurlock7340fc82014-04-24 18:50:12 -0400640 final ComponentName component, final int userid) {
641 synchronized (mMutex) {
642 try {
643 ManagedServiceInfo info = newServiceInfo(service, component, userid,
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700644 true /*isSystem*/, null, Build.VERSION_CODES.LOLLIPOP);
John Spurlock7340fc82014-04-24 18:50:12 -0400645 service.asBinder().linkToDeath(info, 0);
646 mServices.add(info);
Christoph Studer3e144d32014-05-22 16:48:40 +0200647 return info;
John Spurlock7340fc82014-04-24 18:50:12 -0400648 } catch (RemoteException e) {
649 // already dead
650 }
651 }
Christoph Studer3e144d32014-05-22 16:48:40 +0200652 return null;
John Spurlock7340fc82014-04-24 18:50:12 -0400653 }
654
655 /**
656 * Removes a service from the list and unbinds.
657 */
658 private void unregisterServiceImpl(IInterface service, int userid) {
659 ManagedServiceInfo info = removeServiceImpl(service, userid);
660 if (info != null && info.connection != null) {
661 mContext.unbindService(info.connection);
662 }
663 }
664
665 private class SettingsObserver extends ContentObserver {
666 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(mConfig.secureSettingName);
667
668 private SettingsObserver(Handler handler) {
669 super(handler);
670 }
671
672 private void observe() {
673 ContentResolver resolver = mContext.getContentResolver();
674 resolver.registerContentObserver(mSecureSettingsUri,
675 false, this, UserHandle.USER_ALL);
676 update(null);
677 }
678
679 @Override
680 public void onChange(boolean selfChange, Uri uri) {
681 update(uri);
682 }
683
684 private void update(Uri uri) {
685 if (uri == null || mSecureSettingsUri.equals(uri)) {
Christoph Studerb53dfd42014-09-12 14:45:59 +0200686 if (DEBUG) Slog.d(TAG, "Setting changed: mSecureSettingsUri=" + mSecureSettingsUri +
687 " / uri=" + uri);
John Spurlock7340fc82014-04-24 18:50:12 -0400688 rebindServices();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200689 rebuildRestoredPackages();
John Spurlock7340fc82014-04-24 18:50:12 -0400690 }
691 }
692 }
693
694 public class ManagedServiceInfo implements IBinder.DeathRecipient {
695 public IInterface service;
696 public ComponentName component;
697 public int userid;
698 public boolean isSystem;
699 public ServiceConnection connection;
700 public int targetSdkVersion;
701
702 public ManagedServiceInfo(IInterface service, ComponentName component,
703 int userid, boolean isSystem, ServiceConnection connection, int targetSdkVersion) {
704 this.service = service;
705 this.component = component;
706 this.userid = userid;
707 this.isSystem = isSystem;
708 this.connection = connection;
709 this.targetSdkVersion = targetSdkVersion;
710 }
711
John Spurlocke77bb362014-04-26 10:24:59 -0400712 @Override
713 public String toString() {
714 return new StringBuilder("ManagedServiceInfo[")
715 .append("component=").append(component)
716 .append(",userid=").append(userid)
717 .append(",isSystem=").append(isSystem)
718 .append(",targetSdkVersion=").append(targetSdkVersion)
719 .append(",connection=").append(connection == null ? null : "<connection>")
720 .append(",service=").append(service)
721 .append(']').toString();
722 }
723
John Spurlock7340fc82014-04-24 18:50:12 -0400724 public boolean enabledAndUserMatches(int nid) {
725 if (!isEnabledForCurrentProfiles()) {
726 return false;
727 }
728 if (this.userid == UserHandle.USER_ALL) return true;
729 if (nid == UserHandle.USER_ALL || nid == this.userid) return true;
730 return supportsProfiles() && mUserProfiles.isCurrentProfile(nid);
731 }
732
733 public boolean supportsProfiles() {
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700734 return targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
John Spurlock7340fc82014-04-24 18:50:12 -0400735 }
736
737 @Override
738 public void binderDied() {
John Spurlocke77bb362014-04-26 10:24:59 -0400739 if (DEBUG) Slog.d(TAG, "binderDied");
John Spurlock7340fc82014-04-24 18:50:12 -0400740 // Remove the service, but don't unbind from the service. The system will bring the
741 // service back up, and the onServiceConnected handler will readd the service with the
742 // new binding. If this isn't a bound service, and is just a registered
743 // service, just removing it from the list is all we need to do anyway.
744 removeServiceImpl(this.service, this.userid);
745 }
746
747 /** convenience method for looking in mEnabledServicesForCurrentProfiles */
748 public boolean isEnabledForCurrentProfiles() {
749 if (this.isSystem) return true;
750 if (this.connection == null) return false;
751 return mEnabledServicesForCurrentProfiles.contains(this.component);
752 }
753 }
754
755 public static class UserProfiles {
756 // Profiles of the current user.
757 private final SparseArray<UserInfo> mCurrentProfiles = new SparseArray<UserInfo>();
758
759 public void updateCache(Context context) {
760 UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
761 if (userManager != null) {
762 int currentUserId = ActivityManager.getCurrentUser();
763 List<UserInfo> profiles = userManager.getProfiles(currentUserId);
764 synchronized (mCurrentProfiles) {
765 mCurrentProfiles.clear();
766 for (UserInfo user : profiles) {
767 mCurrentProfiles.put(user.id, user);
768 }
769 }
770 }
771 }
772
773 public int[] getCurrentProfileIds() {
774 synchronized (mCurrentProfiles) {
775 int[] users = new int[mCurrentProfiles.size()];
776 final int N = mCurrentProfiles.size();
777 for (int i = 0; i < N; ++i) {
778 users[i] = mCurrentProfiles.keyAt(i);
779 }
780 return users;
781 }
782 }
783
784 public boolean isCurrentProfile(int userId) {
785 synchronized (mCurrentProfiles) {
786 return mCurrentProfiles.get(userId) != null;
787 }
788 }
789 }
790
791 protected static class Config {
792 String caption;
793 String serviceInterface;
794 String secureSettingName;
795 String bindPermission;
796 String settingsAction;
797 int clientLabel;
798 }
799}