blob: a54a61a1c68a2e585d8e0186af050023db61cb71 [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
73 private static final String ENABLED_SERVICES_SEPARATOR = ":";
74
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
282 private ArraySet<ComponentName> loadComponentNamesFromSetting(String settingName, int userId) {
Christopher Tate6597e342015-02-17 12:15:25 -0800283 final ContentResolver cr = mContext.getContentResolver();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200284 String settingValue = Settings.Secure.getStringForUser(
285 cr,
286 settingName,
287 userId);
288 if (TextUtils.isEmpty(settingValue))
289 return null;
290 String[] restored = settingValue.split(ENABLED_SERVICES_SEPARATOR);
291 ArraySet<ComponentName> result = new ArraySet<>(restored.length);
292 for (int i = 0; i < restored.length; i++) {
293 ComponentName value = ComponentName.unflattenFromString(restored[i]);
294 if (null != value) {
295 result.add(value);
Christopher Tate6597e342015-02-17 12:15:25 -0800296 }
297 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200298 return result;
299 }
John Spurlock7340fc82014-04-24 18:50:12 -0400300
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200301 private void storeComponentsToSetting(Set<ComponentName> components,
302 String settingName,
303 int userId) {
304 String[] componentNames = null;
305 if (null != components) {
306 componentNames = new String[components.size()];
307 int index = 0;
308 for (ComponentName c: components) {
309 componentNames[index++] = c.flattenToString();
310 }
311 }
312 final String value = (componentNames == null) ? "" :
313 TextUtils.join(ENABLED_SERVICES_SEPARATOR, componentNames);
314 final ContentResolver cr = mContext.getContentResolver();
315 Settings.Secure.putStringForUser(
316 cr,
317 settingName,
318 value,
319 userId);
320 }
321
322
323 /**
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
335 private void updateSettingsAccordingToInstalledServices(int userId) {
336 boolean restoredChanged = false;
337 boolean currentChanged = false;
338 Set<ComponentName> restored =
339 loadComponentNamesFromSetting(restoredSettingName(mConfig), userId);
340 Set<ComponentName> current =
341 loadComponentNamesFromSetting(mConfig.secureSettingName, userId);
342 Set<ComponentName> installed = new ArraySet<>();
343
344 final PackageManager pm = mContext.getPackageManager();
345 List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
346 new Intent(mConfig.serviceInterface),
347 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
348 userId);
349 if (DEBUG)
350 Slog.v(TAG, mConfig.serviceInterface + " services: " + installedServices);
351
352 for (int i = 0, count = installedServices.size(); i < count; i++) {
353 ResolveInfo resolveInfo = installedServices.get(i);
354 ServiceInfo info = resolveInfo.serviceInfo;
355
356 ComponentName component = new ComponentName(info.packageName, info.name);
357 if (!mConfig.bindPermission.equals(info.permission)) {
358 Slog.w(TAG, "Skipping " + getCaption() + " service "
359 + info.packageName + "/" + info.name
360 + ": it does not require the permission "
361 + mConfig.bindPermission);
362 continue;
363 }
364 installed.add(component);
365 }
366
367 ArraySet<ComponentName> retained = new ArraySet<>();
368
369 for (ComponentName component : installed) {
370 if (null != restored) {
371 boolean wasRestored = restored.remove(component);
372 if (wasRestored) {
373 // Freshly installed package has service that was mentioned in restored setting.
374 if (DEBUG)
375 Slog.v(TAG, "Restoring " + component + " for user " + userId);
376 restoredChanged = true;
377 currentChanged = true;
378 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400379 continue;
380 }
John Spurlock7340fc82014-04-24 18:50:12 -0400381 }
382
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200383 if (null != current) {
384 if (current.contains(component))
385 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400386 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200387 }
388
389 currentChanged |= ((current == null ? 0 : current.size()) != retained.size());
390
391 if (currentChanged) {
392 if (DEBUG) Slog.v(TAG, "List of " + getCaption() + " services was updated " + current);
393 storeComponentsToSetting(retained, mConfig.secureSettingName, userId);
394 }
395
396 if (restoredChanged) {
397 if (DEBUG) Slog.v(TAG,
398 "List of " + getCaption() + " restored services was updated " + restored);
399 storeComponentsToSetting(restored, restoredSettingName(mConfig), userId);
John Spurlock7340fc82014-04-24 18:50:12 -0400400 }
401 }
402
403 /**
404 * Called whenever packages change, the user switches, or the secure setting
405 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
406 */
407 private void rebindServices() {
408 if (DEBUG) Slog.d(TAG, "rebindServices");
409 final int[] userIds = mUserProfiles.getCurrentProfileIds();
410 final int nUserIds = userIds.length;
411
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200412 final SparseArray<ArraySet<ComponentName>> componentsByUser = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400413
414 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200415 componentsByUser.put(userIds[i],
416 loadComponentNamesFromSetting(mConfig.secureSettingName, userIds[i]));
John Spurlock7340fc82014-04-24 18:50:12 -0400417 }
418
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200419 final ArrayList<ManagedServiceInfo> toRemove = new ArrayList<>();
420 final SparseArray<ArrayList<ComponentName>> toAdd = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400421
422 synchronized (mMutex) {
Christoph Studer5d423842014-05-23 13:15:54 +0200423 // Unbind automatically bound services, retain system services.
424 for (ManagedServiceInfo service : mServices) {
425 if (!service.isSystem) {
426 toRemove.add(service);
427 }
428 }
John Spurlock7340fc82014-04-24 18:50:12 -0400429
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200430 final ArraySet<ComponentName> newEnabled = new ArraySet<>();
431 final ArraySet<String> newPackages = new ArraySet<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400432
433 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200434 // decode the list of components
435 final ArraySet<ComponentName> userComponents = componentsByUser.get(userIds[i]);
436 if (null == userComponents) {
437 toAdd.put(userIds[i], new ArrayList<ComponentName>());
438 continue;
439 }
440
441 final ArrayList<ComponentName> add = new ArrayList<>(userComponents);
John Spurlock7340fc82014-04-24 18:50:12 -0400442 toAdd.put(userIds[i], add);
443
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200444 newEnabled.addAll(userComponents);
John Spurlock7340fc82014-04-24 18:50:12 -0400445
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200446 for (int j = 0; j < userComponents.size(); j++) {
447 final ComponentName component = userComponents.valueAt(i);
448 newPackages.add(component.getPackageName());
John Spurlock7340fc82014-04-24 18:50:12 -0400449 }
450 }
451 mEnabledServicesForCurrentProfiles = newEnabled;
452 mEnabledServicesPackageNames = newPackages;
453 }
454
455 for (ManagedServiceInfo info : toRemove) {
456 final ComponentName component = info.component;
457 final int oldUser = info.userid;
458 Slog.v(TAG, "disabling " + getCaption() + " for user "
459 + oldUser + ": " + component);
460 unregisterService(component, info.userid);
461 }
462
463 for (int i = 0; i < nUserIds; ++i) {
464 final ArrayList<ComponentName> add = toAdd.get(userIds[i]);
465 final int N = add.size();
466 for (int j = 0; j < N; j++) {
467 final ComponentName component = add.get(j);
468 Slog.v(TAG, "enabling " + getCaption() + " for user " + userIds[i] + ": "
469 + component);
470 registerService(component, userIds[i]);
471 }
472 }
Christoph Studerb53dfd42014-09-12 14:45:59 +0200473
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200474 mLastSeenProfileIds = userIds;
John Spurlock7340fc82014-04-24 18:50:12 -0400475 }
476
477 /**
478 * Version of registerService that takes the name of a service component to bind to.
479 */
480 private void registerService(final ComponentName name, final int userid) {
481 if (DEBUG) Slog.v(TAG, "registerService: " + name + " u=" + userid);
482
483 synchronized (mMutex) {
484 final String servicesBindingTag = name.toString() + "/" + userid;
485 if (mServicesBinding.contains(servicesBindingTag)) {
486 // stop registering this thing already! we're working on it
487 return;
488 }
489 mServicesBinding.add(servicesBindingTag);
490
491 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200492 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400493 final ManagedServiceInfo info = mServices.get(i);
494 if (name.equals(info.component)
495 && info.userid == userid) {
496 // cut old connections
497 if (DEBUG) Slog.v(TAG, " disconnecting old " + getCaption() + ": "
498 + info.service);
John Spurlocke77bb362014-04-26 10:24:59 -0400499 removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400500 if (info.connection != null) {
501 mContext.unbindService(info.connection);
502 }
503 }
504 }
505
506 Intent intent = new Intent(mConfig.serviceInterface);
507 intent.setComponent(name);
508
509 intent.putExtra(Intent.EXTRA_CLIENT_LABEL, mConfig.clientLabel);
510
511 final PendingIntent pendingIntent = PendingIntent.getActivity(
512 mContext, 0, new Intent(mConfig.settingsAction), 0);
513 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, pendingIntent);
514
515 ApplicationInfo appInfo = null;
516 try {
517 appInfo = mContext.getPackageManager().getApplicationInfo(
518 name.getPackageName(), 0);
519 } catch (NameNotFoundException e) {
520 // Ignore if the package doesn't exist we won't be able to bind to the service.
521 }
522 final int targetSdkVersion =
523 appInfo != null ? appInfo.targetSdkVersion : Build.VERSION_CODES.BASE;
524
525 try {
526 if (DEBUG) Slog.v(TAG, "binding: " + intent);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200527 ServiceConnection serviceConnection = new ServiceConnection() {
528 IInterface mService;
529
530 @Override
531 public void onServiceConnected(ComponentName name, IBinder binder) {
532 boolean added = false;
533 ManagedServiceInfo info = null;
534 synchronized (mMutex) {
535 mServicesBinding.remove(servicesBindingTag);
536 try {
537 mService = asInterface(binder);
538 info = newServiceInfo(mService, name,
539 userid, false /*isSystem*/, this, targetSdkVersion);
540 binder.linkToDeath(info, 0);
541 added = mServices.add(info);
542 } catch (RemoteException e) {
543 // already dead
544 }
545 }
546 if (added) {
547 onServiceAdded(info);
548 }
549 }
550
551 @Override
552 public void onServiceDisconnected(ComponentName name) {
553 Slog.v(TAG, getCaption() + " connection lost: " + name);
554 }
555 };
John Spurlock7340fc82014-04-24 18:50:12 -0400556 if (!mContext.bindServiceAsUser(intent,
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200557 serviceConnection,
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700558 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200559 new UserHandle(userid))) {
John Spurlock7340fc82014-04-24 18:50:12 -0400560 mServicesBinding.remove(servicesBindingTag);
561 Slog.w(TAG, "Unable to bind " + getCaption() + " service: " + intent);
562 return;
563 }
564 } catch (SecurityException ex) {
565 Slog.e(TAG, "Unable to bind " + getCaption() + " service: " + intent, ex);
566 return;
567 }
568 }
569 }
570
571 /**
572 * Remove a service for the given user by ComponentName
573 */
574 private void unregisterService(ComponentName name, int userid) {
575 synchronized (mMutex) {
576 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200577 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400578 final ManagedServiceInfo info = mServices.get(i);
579 if (name.equals(info.component)
580 && info.userid == userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400581 removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400582 if (info.connection != null) {
583 try {
584 mContext.unbindService(info.connection);
585 } catch (IllegalArgumentException ex) {
586 // something happened to the service: we think we have a connection
587 // but it's bogus.
588 Slog.e(TAG, getCaption() + " " + name + " could not be unbound: " + ex);
589 }
590 }
591 }
592 }
593 }
594 }
595
596 /**
597 * Removes a service from the list but does not unbind
598 *
599 * @return the removed service.
600 */
601 private ManagedServiceInfo removeServiceImpl(IInterface service, final int userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400602 if (DEBUG) Slog.d(TAG, "removeServiceImpl service=" + service + " u=" + userid);
John Spurlock7340fc82014-04-24 18:50:12 -0400603 ManagedServiceInfo serviceInfo = null;
604 synchronized (mMutex) {
605 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200606 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400607 final ManagedServiceInfo info = mServices.get(i);
608 if (info.service.asBinder() == service.asBinder()
609 && info.userid == userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400610 if (DEBUG) Slog.d(TAG, "Removing active service " + info.component);
611 serviceInfo = removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400612 }
613 }
614 }
615 return serviceInfo;
616 }
617
John Spurlocke77bb362014-04-26 10:24:59 -0400618 private ManagedServiceInfo removeServiceLocked(int i) {
619 final ManagedServiceInfo info = mServices.remove(i);
620 onServiceRemovedLocked(info);
621 return info;
622 }
623
John Spurlock7340fc82014-04-24 18:50:12 -0400624 private void checkNotNull(IInterface service) {
625 if (service == null) {
626 throw new IllegalArgumentException(getCaption() + " must not be null");
627 }
628 }
629
Christoph Studer3e144d32014-05-22 16:48:40 +0200630 private ManagedServiceInfo registerServiceImpl(final IInterface service,
John Spurlock7340fc82014-04-24 18:50:12 -0400631 final ComponentName component, final int userid) {
632 synchronized (mMutex) {
633 try {
634 ManagedServiceInfo info = newServiceInfo(service, component, userid,
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700635 true /*isSystem*/, null, Build.VERSION_CODES.LOLLIPOP);
John Spurlock7340fc82014-04-24 18:50:12 -0400636 service.asBinder().linkToDeath(info, 0);
637 mServices.add(info);
Christoph Studer3e144d32014-05-22 16:48:40 +0200638 return info;
John Spurlock7340fc82014-04-24 18:50:12 -0400639 } catch (RemoteException e) {
640 // already dead
641 }
642 }
Christoph Studer3e144d32014-05-22 16:48:40 +0200643 return null;
John Spurlock7340fc82014-04-24 18:50:12 -0400644 }
645
646 /**
647 * Removes a service from the list and unbinds.
648 */
649 private void unregisterServiceImpl(IInterface service, int userid) {
650 ManagedServiceInfo info = removeServiceImpl(service, userid);
651 if (info != null && info.connection != null) {
652 mContext.unbindService(info.connection);
653 }
654 }
655
656 private class SettingsObserver extends ContentObserver {
657 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(mConfig.secureSettingName);
658
659 private SettingsObserver(Handler handler) {
660 super(handler);
661 }
662
663 private void observe() {
664 ContentResolver resolver = mContext.getContentResolver();
665 resolver.registerContentObserver(mSecureSettingsUri,
666 false, this, UserHandle.USER_ALL);
667 update(null);
668 }
669
670 @Override
671 public void onChange(boolean selfChange, Uri uri) {
672 update(uri);
673 }
674
675 private void update(Uri uri) {
676 if (uri == null || mSecureSettingsUri.equals(uri)) {
Christoph Studerb53dfd42014-09-12 14:45:59 +0200677 if (DEBUG) Slog.d(TAG, "Setting changed: mSecureSettingsUri=" + mSecureSettingsUri +
678 " / uri=" + uri);
John Spurlock7340fc82014-04-24 18:50:12 -0400679 rebindServices();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200680 rebuildRestoredPackages();
John Spurlock7340fc82014-04-24 18:50:12 -0400681 }
682 }
683 }
684
685 public class ManagedServiceInfo implements IBinder.DeathRecipient {
686 public IInterface service;
687 public ComponentName component;
688 public int userid;
689 public boolean isSystem;
690 public ServiceConnection connection;
691 public int targetSdkVersion;
692
693 public ManagedServiceInfo(IInterface service, ComponentName component,
694 int userid, boolean isSystem, ServiceConnection connection, int targetSdkVersion) {
695 this.service = service;
696 this.component = component;
697 this.userid = userid;
698 this.isSystem = isSystem;
699 this.connection = connection;
700 this.targetSdkVersion = targetSdkVersion;
701 }
702
John Spurlocke77bb362014-04-26 10:24:59 -0400703 @Override
704 public String toString() {
705 return new StringBuilder("ManagedServiceInfo[")
706 .append("component=").append(component)
707 .append(",userid=").append(userid)
708 .append(",isSystem=").append(isSystem)
709 .append(",targetSdkVersion=").append(targetSdkVersion)
710 .append(",connection=").append(connection == null ? null : "<connection>")
711 .append(",service=").append(service)
712 .append(']').toString();
713 }
714
John Spurlock7340fc82014-04-24 18:50:12 -0400715 public boolean enabledAndUserMatches(int nid) {
716 if (!isEnabledForCurrentProfiles()) {
717 return false;
718 }
719 if (this.userid == UserHandle.USER_ALL) return true;
720 if (nid == UserHandle.USER_ALL || nid == this.userid) return true;
721 return supportsProfiles() && mUserProfiles.isCurrentProfile(nid);
722 }
723
724 public boolean supportsProfiles() {
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700725 return targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
John Spurlock7340fc82014-04-24 18:50:12 -0400726 }
727
728 @Override
729 public void binderDied() {
John Spurlocke77bb362014-04-26 10:24:59 -0400730 if (DEBUG) Slog.d(TAG, "binderDied");
John Spurlock7340fc82014-04-24 18:50:12 -0400731 // Remove the service, but don't unbind from the service. The system will bring the
732 // service back up, and the onServiceConnected handler will readd the service with the
733 // new binding. If this isn't a bound service, and is just a registered
734 // service, just removing it from the list is all we need to do anyway.
735 removeServiceImpl(this.service, this.userid);
736 }
737
738 /** convenience method for looking in mEnabledServicesForCurrentProfiles */
739 public boolean isEnabledForCurrentProfiles() {
740 if (this.isSystem) return true;
741 if (this.connection == null) return false;
742 return mEnabledServicesForCurrentProfiles.contains(this.component);
743 }
744 }
745
746 public static class UserProfiles {
747 // Profiles of the current user.
748 private final SparseArray<UserInfo> mCurrentProfiles = new SparseArray<UserInfo>();
749
750 public void updateCache(Context context) {
751 UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
752 if (userManager != null) {
753 int currentUserId = ActivityManager.getCurrentUser();
754 List<UserInfo> profiles = userManager.getProfiles(currentUserId);
755 synchronized (mCurrentProfiles) {
756 mCurrentProfiles.clear();
757 for (UserInfo user : profiles) {
758 mCurrentProfiles.put(user.id, user);
759 }
760 }
761 }
762 }
763
764 public int[] getCurrentProfileIds() {
765 synchronized (mCurrentProfiles) {
766 int[] users = new int[mCurrentProfiles.size()];
767 final int N = mCurrentProfiles.size();
768 for (int i = 0; i < N; ++i) {
769 users[i] = mCurrentProfiles.keyAt(i);
770 }
771 return users;
772 }
773 }
774
775 public boolean isCurrentProfile(int userId) {
776 synchronized (mCurrentProfiles) {
777 return mCurrentProfiles.get(userId) != null;
778 }
779 }
780 }
781
782 protected static class Config {
783 String caption;
784 String serviceInterface;
785 String secureSettingName;
786 String bindPermission;
787 String settingsAction;
788 int clientLabel;
789 }
790}