blob: 9ccb2eaf1fb3a809b5754ee4209f90906dc9013b [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>();
93
Christoph Studerb53dfd42014-09-12 14:45:59 +020094 // Kept to de-dupe user change events (experienced after boot, when we receive a settings and a
95 // user change).
96 private int[] mLastSeenProfileIds;
97
Christopher Tate6597e342015-02-17 12:15:25 -080098 private final BroadcastReceiver mRestoreReceiver;
99
John Spurlock7340fc82014-04-24 18:50:12 -0400100 public ManagedServices(Context context, Handler handler, Object mutex,
101 UserProfiles userProfiles) {
102 mContext = context;
103 mMutex = mutex;
104 mUserProfiles = userProfiles;
105 mConfig = getConfig();
106 mSettingsObserver = new SettingsObserver(handler);
Christopher Tate6597e342015-02-17 12:15:25 -0800107
108 mRestoreReceiver = new SettingRestoredReceiver();
109 IntentFilter filter = new IntentFilter(Intent.ACTION_SETTING_RESTORED);
110 context.registerReceiver(mRestoreReceiver, filter);
111 }
112
113 class SettingRestoredReceiver extends BroadcastReceiver {
114 @Override
115 public void onReceive(Context context, Intent intent) {
116 if (Intent.ACTION_SETTING_RESTORED.equals(intent.getAction())) {
117 String element = intent.getStringExtra(Intent.EXTRA_SETTING_NAME);
118 if (Objects.equals(element, mConfig.secureSettingName)) {
119 String prevValue = intent.getStringExtra(Intent.EXTRA_SETTING_PREVIOUS_VALUE);
120 String newValue = intent.getStringExtra(Intent.EXTRA_SETTING_NEW_VALUE);
121 settingRestored(element, prevValue, newValue, getSendingUserId());
122 }
123 }
124 }
John Spurlock7340fc82014-04-24 18:50:12 -0400125 }
126
127 abstract protected Config getConfig();
128
129 private String getCaption() {
130 return mConfig.caption;
131 }
132
133 abstract protected IInterface asInterface(IBinder binder);
134
John Spurlock3b98b3f2014-05-01 09:08:48 -0400135 abstract protected void onServiceAdded(ManagedServiceInfo info);
John Spurlock7340fc82014-04-24 18:50:12 -0400136
John Spurlocke77bb362014-04-26 10:24:59 -0400137 protected void onServiceRemovedLocked(ManagedServiceInfo removed) { }
138
John Spurlock7340fc82014-04-24 18:50:12 -0400139 private ManagedServiceInfo newServiceInfo(IInterface service,
140 ComponentName component, int userid, boolean isSystem, ServiceConnection connection,
141 int targetSdkVersion) {
142 return new ManagedServiceInfo(service, component, userid, isSystem, connection,
143 targetSdkVersion);
144 }
145
146 public void onBootPhaseAppsCanStart() {
147 mSettingsObserver.observe();
148 }
149
John Spurlock25e2d242014-06-27 13:58:23 -0400150 public void dump(PrintWriter pw, DumpFilter filter) {
John Spurlocke77bb362014-04-26 10:24:59 -0400151 pw.println(" All " + getCaption() + "s (" + mEnabledServicesForCurrentProfiles.size()
John Spurlock7340fc82014-04-24 18:50:12 -0400152 + ") enabled for current profiles:");
153 for (ComponentName cmpt : mEnabledServicesForCurrentProfiles) {
John Spurlock25e2d242014-06-27 13:58:23 -0400154 if (filter != null && !filter.matches(cmpt)) continue;
John Spurlocke77bb362014-04-26 10:24:59 -0400155 pw.println(" " + cmpt);
John Spurlock7340fc82014-04-24 18:50:12 -0400156 }
157
John Spurlocke77bb362014-04-26 10:24:59 -0400158 pw.println(" Live " + getCaption() + "s (" + mServices.size() + "):");
John Spurlock7340fc82014-04-24 18:50:12 -0400159 for (ManagedServiceInfo info : mServices) {
John Spurlock25e2d242014-06-27 13:58:23 -0400160 if (filter != null && !filter.matches(info.component)) continue;
John Spurlocke77bb362014-04-26 10:24:59 -0400161 pw.println(" " + info.component
John Spurlock7340fc82014-04-24 18:50:12 -0400162 + " (user " + info.userid + "): " + info.service
163 + (info.isSystem?" SYSTEM":""));
164 }
165 }
166
Christopher Tate6597e342015-02-17 12:15:25 -0800167 // By convention, restored settings are replicated to another settings
168 // entry, named similarly but with a disambiguation suffix.
169 public static final String restoredSettingName(Config config) {
170 return config.secureSettingName + ":restored";
171 }
172
173 // The OS has done a restore of this service's saved state. We clone it to the
174 // 'restored' reserve, and then once we return and the actual write to settings is
175 // performed, our observer will do the work of maintaining the restored vs live
176 // settings data.
177 public void settingRestored(String element, String oldValue, String newValue, int userid) {
178 if (DEBUG) Slog.d(TAG, "Restored managed service setting: " + element
179 + " ovalue=" + oldValue + " nvalue=" + newValue);
180 if (mConfig.secureSettingName.equals(element)) {
181 if (element != null) {
182 mRestored = null;
183 Settings.Secure.putStringForUser(mContext.getContentResolver(),
184 restoredSettingName(mConfig),
185 newValue,
186 userid);
187 disableNonexistentServices(userid);
188 }
189 }
190 }
191
John Spurlock7340fc82014-04-24 18:50:12 -0400192 public void onPackagesChanged(boolean queryReplace, String[] pkgList) {
John Spurlocke77bb362014-04-26 10:24:59 -0400193 if (DEBUG) Slog.d(TAG, "onPackagesChanged queryReplace=" + queryReplace
194 + " pkgList=" + (pkgList == null ? null : Arrays.asList(pkgList))
195 + " mEnabledServicesPackageNames=" + mEnabledServicesPackageNames);
John Spurlock7340fc82014-04-24 18:50:12 -0400196 boolean anyServicesInvolved = false;
197 if (pkgList != null && (pkgList.length > 0)) {
198 for (String pkgName : pkgList) {
199 if (mEnabledServicesPackageNames.contains(pkgName)) {
200 anyServicesInvolved = true;
201 }
202 }
203 }
204
205 if (anyServicesInvolved) {
206 // if we're not replacing a package, clean up orphaned bits
207 if (!queryReplace) {
208 disableNonexistentServices();
209 }
210 // make sure we're still bound to any of our services who may have just upgraded
211 rebindServices();
212 }
213 }
214
Christoph Studerb53dfd42014-09-12 14:45:59 +0200215 public void onUserSwitched() {
216 if (DEBUG) Slog.d(TAG, "onUserSwitched");
217 if (Arrays.equals(mLastSeenProfileIds, mUserProfiles.getCurrentProfileIds())) {
218 if (DEBUG) Slog.d(TAG, "Current profile IDs didn't change, skipping rebindServices().");
219 return;
220 }
221 rebindServices();
222 }
223
John Spurlock7340fc82014-04-24 18:50:12 -0400224 public ManagedServiceInfo checkServiceTokenLocked(IInterface service) {
225 checkNotNull(service);
226 final IBinder token = service.asBinder();
227 final int N = mServices.size();
228 for (int i=0; i<N; i++) {
229 final ManagedServiceInfo info = mServices.get(i);
230 if (info.service.asBinder() == token) return info;
231 }
232 throw new SecurityException("Disallowed call from unknown " + getCaption() + ": "
233 + service);
234 }
235
236 public void unregisterService(IInterface service, int userid) {
237 checkNotNull(service);
238 // no need to check permissions; if your service binder is in the list,
239 // that's proof that you had permission to add it in the first place
240 unregisterServiceImpl(service, userid);
241 }
242
243 public void registerService(IInterface service, ComponentName component, int userid) {
244 checkNotNull(service);
Christoph Studer3e144d32014-05-22 16:48:40 +0200245 ManagedServiceInfo info = registerServiceImpl(service, component, userid);
246 if (info != null) {
247 onServiceAdded(info);
248 }
John Spurlock7340fc82014-04-24 18:50:12 -0400249 }
250
251 /**
252 * Remove access for any services that no longer exist.
253 */
254 private void disableNonexistentServices() {
255 int[] userIds = mUserProfiles.getCurrentProfileIds();
256 final int N = userIds.length;
257 for (int i = 0 ; i < N; ++i) {
258 disableNonexistentServices(userIds[i]);
259 }
260 }
261
262 private void disableNonexistentServices(int userId) {
Christopher Tate6597e342015-02-17 12:15:25 -0800263 final ContentResolver cr = mContext.getContentResolver();
264 boolean restoredChanged = false;
265 if (mRestored == null) {
266 String restoredSetting = Settings.Secure.getStringForUser(
267 cr,
268 restoredSettingName(mConfig),
269 userId);
270 if (!TextUtils.isEmpty(restoredSetting)) {
271 if (DEBUG) Slog.d(TAG, "restored: " + restoredSetting);
272 String[] restored = restoredSetting.split(ENABLED_SERVICES_SEPARATOR);
273 mRestored = new ArraySet<String>(Arrays.asList(restored));
274 } else {
275 mRestored = new ArraySet<String>();
276 }
277 }
John Spurlock7340fc82014-04-24 18:50:12 -0400278 String flatIn = Settings.Secure.getStringForUser(
Christopher Tate6597e342015-02-17 12:15:25 -0800279 cr,
John Spurlock7340fc82014-04-24 18:50:12 -0400280 mConfig.secureSettingName,
281 userId);
282 if (!TextUtils.isEmpty(flatIn)) {
283 if (DEBUG) Slog.v(TAG, "flat before: " + flatIn);
284 PackageManager pm = mContext.getPackageManager();
285 List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
286 new Intent(mConfig.serviceInterface),
287 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
288 userId);
John Spurlocke77bb362014-04-26 10:24:59 -0400289 if (DEBUG) Slog.v(TAG, mConfig.serviceInterface + " services: " + installedServices);
John Spurlock7340fc82014-04-24 18:50:12 -0400290 Set<ComponentName> installed = new ArraySet<ComponentName>();
291 for (int i = 0, count = installedServices.size(); i < count; i++) {
292 ResolveInfo resolveInfo = installedServices.get(i);
293 ServiceInfo info = resolveInfo.serviceInfo;
294
Christopher Tate6597e342015-02-17 12:15:25 -0800295 ComponentName component = new ComponentName(info.packageName, info.name);
John Spurlock7340fc82014-04-24 18:50:12 -0400296 if (!mConfig.bindPermission.equals(info.permission)) {
297 Slog.w(TAG, "Skipping " + getCaption() + " service "
298 + info.packageName + "/" + info.name
299 + ": it does not require the permission "
300 + mConfig.bindPermission);
Christopher Tate6597e342015-02-17 12:15:25 -0800301 restoredChanged |= mRestored.remove(component.flattenToString());
John Spurlock7340fc82014-04-24 18:50:12 -0400302 continue;
303 }
Christopher Tate6597e342015-02-17 12:15:25 -0800304 installed.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400305 }
306
307 String flatOut = "";
308 if (!installed.isEmpty()) {
309 String[] enabled = flatIn.split(ENABLED_SERVICES_SEPARATOR);
310 ArrayList<String> remaining = new ArrayList<String>(enabled.length);
311 for (int i = 0; i < enabled.length; i++) {
312 ComponentName enabledComponent = ComponentName.unflattenFromString(enabled[i]);
313 if (installed.contains(enabledComponent)) {
314 remaining.add(enabled[i]);
Christopher Tate6597e342015-02-17 12:15:25 -0800315 restoredChanged |= mRestored.remove(enabled[i]);
John Spurlock7340fc82014-04-24 18:50:12 -0400316 }
317 }
Christopher Tate6597e342015-02-17 12:15:25 -0800318 remaining.addAll(mRestored);
John Spurlock7340fc82014-04-24 18:50:12 -0400319 flatOut = TextUtils.join(ENABLED_SERVICES_SEPARATOR, remaining);
320 }
321 if (DEBUG) Slog.v(TAG, "flat after: " + flatOut);
322 if (!flatIn.equals(flatOut)) {
Christopher Tate6597e342015-02-17 12:15:25 -0800323 Settings.Secure.putStringForUser(cr,
John Spurlock7340fc82014-04-24 18:50:12 -0400324 mConfig.secureSettingName,
325 flatOut, userId);
326 }
Christopher Tate6597e342015-02-17 12:15:25 -0800327 if (restoredChanged) {
328 if (DEBUG) Slog.d(TAG, "restored changed; rewriting");
329 final String flatRestored = TextUtils.join(ENABLED_SERVICES_SEPARATOR,
330 mRestored.toArray());
331 Settings.Secure.putStringForUser(cr,
332 restoredSettingName(mConfig),
333 flatRestored,
334 userId);
335 }
John Spurlock7340fc82014-04-24 18:50:12 -0400336 }
337 }
338
339 /**
340 * Called whenever packages change, the user switches, or the secure setting
341 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
342 */
343 private void rebindServices() {
344 if (DEBUG) Slog.d(TAG, "rebindServices");
345 final int[] userIds = mUserProfiles.getCurrentProfileIds();
346 final int nUserIds = userIds.length;
347
348 final SparseArray<String> flat = new SparseArray<String>();
349
350 for (int i = 0; i < nUserIds; ++i) {
351 flat.put(userIds[i], Settings.Secure.getStringForUser(
352 mContext.getContentResolver(),
353 mConfig.secureSettingName,
354 userIds[i]));
355 }
356
Christoph Studer5d423842014-05-23 13:15:54 +0200357 ArrayList<ManagedServiceInfo> toRemove = new ArrayList<ManagedServiceInfo>();
John Spurlock7340fc82014-04-24 18:50:12 -0400358 final SparseArray<ArrayList<ComponentName>> toAdd
359 = new SparseArray<ArrayList<ComponentName>>();
360
361 synchronized (mMutex) {
Christoph Studer5d423842014-05-23 13:15:54 +0200362 // Unbind automatically bound services, retain system services.
363 for (ManagedServiceInfo service : mServices) {
364 if (!service.isSystem) {
365 toRemove.add(service);
366 }
367 }
John Spurlock7340fc82014-04-24 18:50:12 -0400368
369 final ArraySet<ComponentName> newEnabled = new ArraySet<ComponentName>();
370 final ArraySet<String> newPackages = new ArraySet<String>();
371
372 for (int i = 0; i < nUserIds; ++i) {
373 final ArrayList<ComponentName> add = new ArrayList<ComponentName>();
374 toAdd.put(userIds[i], add);
375
376 // decode the list of components
377 String toDecode = flat.get(userIds[i]);
378 if (toDecode != null) {
379 String[] components = toDecode.split(ENABLED_SERVICES_SEPARATOR);
380 for (int j = 0; j < components.length; j++) {
381 final ComponentName component
382 = ComponentName.unflattenFromString(components[j]);
383 if (component != null) {
384 newEnabled.add(component);
385 add.add(component);
386 newPackages.add(component.getPackageName());
387 }
388 }
389
390 }
391 }
392 mEnabledServicesForCurrentProfiles = newEnabled;
393 mEnabledServicesPackageNames = newPackages;
394 }
395
396 for (ManagedServiceInfo info : toRemove) {
397 final ComponentName component = info.component;
398 final int oldUser = info.userid;
399 Slog.v(TAG, "disabling " + getCaption() + " for user "
400 + oldUser + ": " + component);
401 unregisterService(component, info.userid);
402 }
403
404 for (int i = 0; i < nUserIds; ++i) {
405 final ArrayList<ComponentName> add = toAdd.get(userIds[i]);
406 final int N = add.size();
407 for (int j = 0; j < N; j++) {
408 final ComponentName component = add.get(j);
409 Slog.v(TAG, "enabling " + getCaption() + " for user " + userIds[i] + ": "
410 + component);
411 registerService(component, userIds[i]);
412 }
413 }
Christoph Studerb53dfd42014-09-12 14:45:59 +0200414
415 mLastSeenProfileIds = mUserProfiles.getCurrentProfileIds();
John Spurlock7340fc82014-04-24 18:50:12 -0400416 }
417
418 /**
419 * Version of registerService that takes the name of a service component to bind to.
420 */
421 private void registerService(final ComponentName name, final int userid) {
422 if (DEBUG) Slog.v(TAG, "registerService: " + name + " u=" + userid);
423
424 synchronized (mMutex) {
425 final String servicesBindingTag = name.toString() + "/" + userid;
426 if (mServicesBinding.contains(servicesBindingTag)) {
427 // stop registering this thing already! we're working on it
428 return;
429 }
430 mServicesBinding.add(servicesBindingTag);
431
432 final int N = mServices.size();
433 for (int i=N-1; i>=0; i--) {
434 final ManagedServiceInfo info = mServices.get(i);
435 if (name.equals(info.component)
436 && info.userid == userid) {
437 // cut old connections
438 if (DEBUG) Slog.v(TAG, " disconnecting old " + getCaption() + ": "
439 + info.service);
John Spurlocke77bb362014-04-26 10:24:59 -0400440 removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400441 if (info.connection != null) {
442 mContext.unbindService(info.connection);
443 }
444 }
445 }
446
447 Intent intent = new Intent(mConfig.serviceInterface);
448 intent.setComponent(name);
449
450 intent.putExtra(Intent.EXTRA_CLIENT_LABEL, mConfig.clientLabel);
451
452 final PendingIntent pendingIntent = PendingIntent.getActivity(
453 mContext, 0, new Intent(mConfig.settingsAction), 0);
454 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, pendingIntent);
455
456 ApplicationInfo appInfo = null;
457 try {
458 appInfo = mContext.getPackageManager().getApplicationInfo(
459 name.getPackageName(), 0);
460 } catch (NameNotFoundException e) {
461 // Ignore if the package doesn't exist we won't be able to bind to the service.
462 }
463 final int targetSdkVersion =
464 appInfo != null ? appInfo.targetSdkVersion : Build.VERSION_CODES.BASE;
465
466 try {
467 if (DEBUG) Slog.v(TAG, "binding: " + intent);
468 if (!mContext.bindServiceAsUser(intent,
469 new ServiceConnection() {
470 IInterface mService;
471
472 @Override
473 public void onServiceConnected(ComponentName name, IBinder binder) {
474 boolean added = false;
John Spurlock3b98b3f2014-05-01 09:08:48 -0400475 ManagedServiceInfo info = null;
John Spurlock7340fc82014-04-24 18:50:12 -0400476 synchronized (mMutex) {
477 mServicesBinding.remove(servicesBindingTag);
478 try {
479 mService = asInterface(binder);
John Spurlock3b98b3f2014-05-01 09:08:48 -0400480 info = newServiceInfo(mService, name,
John Spurlock7340fc82014-04-24 18:50:12 -0400481 userid, false /*isSystem*/, this, targetSdkVersion);
482 binder.linkToDeath(info, 0);
483 added = mServices.add(info);
484 } catch (RemoteException e) {
485 // already dead
486 }
487 }
488 if (added) {
John Spurlock3b98b3f2014-05-01 09:08:48 -0400489 onServiceAdded(info);
John Spurlock7340fc82014-04-24 18:50:12 -0400490 }
491 }
492
493 @Override
494 public void onServiceDisconnected(ComponentName name) {
495 Slog.v(TAG, getCaption() + " connection lost: " + name);
496 }
497 },
498 Context.BIND_AUTO_CREATE,
499 new UserHandle(userid)))
500 {
501 mServicesBinding.remove(servicesBindingTag);
502 Slog.w(TAG, "Unable to bind " + getCaption() + " service: " + intent);
503 return;
504 }
505 } catch (SecurityException ex) {
506 Slog.e(TAG, "Unable to bind " + getCaption() + " service: " + intent, ex);
507 return;
508 }
509 }
510 }
511
512 /**
513 * Remove a service for the given user by ComponentName
514 */
515 private void unregisterService(ComponentName name, int userid) {
516 synchronized (mMutex) {
517 final int N = mServices.size();
518 for (int i=N-1; i>=0; i--) {
519 final ManagedServiceInfo info = mServices.get(i);
520 if (name.equals(info.component)
521 && info.userid == userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400522 removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400523 if (info.connection != null) {
524 try {
525 mContext.unbindService(info.connection);
526 } catch (IllegalArgumentException ex) {
527 // something happened to the service: we think we have a connection
528 // but it's bogus.
529 Slog.e(TAG, getCaption() + " " + name + " could not be unbound: " + ex);
530 }
531 }
532 }
533 }
534 }
535 }
536
537 /**
538 * Removes a service from the list but does not unbind
539 *
540 * @return the removed service.
541 */
542 private ManagedServiceInfo removeServiceImpl(IInterface service, final int userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400543 if (DEBUG) Slog.d(TAG, "removeServiceImpl service=" + service + " u=" + userid);
John Spurlock7340fc82014-04-24 18:50:12 -0400544 ManagedServiceInfo serviceInfo = null;
545 synchronized (mMutex) {
546 final int N = mServices.size();
547 for (int i=N-1; i>=0; i--) {
548 final ManagedServiceInfo info = mServices.get(i);
549 if (info.service.asBinder() == service.asBinder()
550 && info.userid == userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400551 if (DEBUG) Slog.d(TAG, "Removing active service " + info.component);
552 serviceInfo = removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400553 }
554 }
555 }
556 return serviceInfo;
557 }
558
John Spurlocke77bb362014-04-26 10:24:59 -0400559 private ManagedServiceInfo removeServiceLocked(int i) {
560 final ManagedServiceInfo info = mServices.remove(i);
561 onServiceRemovedLocked(info);
562 return info;
563 }
564
John Spurlock7340fc82014-04-24 18:50:12 -0400565 private void checkNotNull(IInterface service) {
566 if (service == null) {
567 throw new IllegalArgumentException(getCaption() + " must not be null");
568 }
569 }
570
Christoph Studer3e144d32014-05-22 16:48:40 +0200571 private ManagedServiceInfo registerServiceImpl(final IInterface service,
John Spurlock7340fc82014-04-24 18:50:12 -0400572 final ComponentName component, final int userid) {
573 synchronized (mMutex) {
574 try {
575 ManagedServiceInfo info = newServiceInfo(service, component, userid,
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700576 true /*isSystem*/, null, Build.VERSION_CODES.LOLLIPOP);
John Spurlock7340fc82014-04-24 18:50:12 -0400577 service.asBinder().linkToDeath(info, 0);
578 mServices.add(info);
Christoph Studer3e144d32014-05-22 16:48:40 +0200579 return info;
John Spurlock7340fc82014-04-24 18:50:12 -0400580 } catch (RemoteException e) {
581 // already dead
582 }
583 }
Christoph Studer3e144d32014-05-22 16:48:40 +0200584 return null;
John Spurlock7340fc82014-04-24 18:50:12 -0400585 }
586
587 /**
588 * Removes a service from the list and unbinds.
589 */
590 private void unregisterServiceImpl(IInterface service, int userid) {
591 ManagedServiceInfo info = removeServiceImpl(service, userid);
592 if (info != null && info.connection != null) {
593 mContext.unbindService(info.connection);
594 }
595 }
596
597 private class SettingsObserver extends ContentObserver {
598 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(mConfig.secureSettingName);
599
600 private SettingsObserver(Handler handler) {
601 super(handler);
602 }
603
604 private void observe() {
605 ContentResolver resolver = mContext.getContentResolver();
606 resolver.registerContentObserver(mSecureSettingsUri,
607 false, this, UserHandle.USER_ALL);
608 update(null);
609 }
610
611 @Override
612 public void onChange(boolean selfChange, Uri uri) {
613 update(uri);
614 }
615
616 private void update(Uri uri) {
617 if (uri == null || mSecureSettingsUri.equals(uri)) {
Christoph Studerb53dfd42014-09-12 14:45:59 +0200618 if (DEBUG) Slog.d(TAG, "Setting changed: mSecureSettingsUri=" + mSecureSettingsUri +
619 " / uri=" + uri);
John Spurlock7340fc82014-04-24 18:50:12 -0400620 rebindServices();
621 }
622 }
623 }
624
625 public class ManagedServiceInfo implements IBinder.DeathRecipient {
626 public IInterface service;
627 public ComponentName component;
628 public int userid;
629 public boolean isSystem;
630 public ServiceConnection connection;
631 public int targetSdkVersion;
632
633 public ManagedServiceInfo(IInterface service, ComponentName component,
634 int userid, boolean isSystem, ServiceConnection connection, int targetSdkVersion) {
635 this.service = service;
636 this.component = component;
637 this.userid = userid;
638 this.isSystem = isSystem;
639 this.connection = connection;
640 this.targetSdkVersion = targetSdkVersion;
641 }
642
John Spurlocke77bb362014-04-26 10:24:59 -0400643 @Override
644 public String toString() {
645 return new StringBuilder("ManagedServiceInfo[")
646 .append("component=").append(component)
647 .append(",userid=").append(userid)
648 .append(",isSystem=").append(isSystem)
649 .append(",targetSdkVersion=").append(targetSdkVersion)
650 .append(",connection=").append(connection == null ? null : "<connection>")
651 .append(",service=").append(service)
652 .append(']').toString();
653 }
654
John Spurlock7340fc82014-04-24 18:50:12 -0400655 public boolean enabledAndUserMatches(int nid) {
656 if (!isEnabledForCurrentProfiles()) {
657 return false;
658 }
659 if (this.userid == UserHandle.USER_ALL) return true;
660 if (nid == UserHandle.USER_ALL || nid == this.userid) return true;
661 return supportsProfiles() && mUserProfiles.isCurrentProfile(nid);
662 }
663
664 public boolean supportsProfiles() {
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700665 return targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
John Spurlock7340fc82014-04-24 18:50:12 -0400666 }
667
668 @Override
669 public void binderDied() {
John Spurlocke77bb362014-04-26 10:24:59 -0400670 if (DEBUG) Slog.d(TAG, "binderDied");
John Spurlock7340fc82014-04-24 18:50:12 -0400671 // Remove the service, but don't unbind from the service. The system will bring the
672 // service back up, and the onServiceConnected handler will readd the service with the
673 // new binding. If this isn't a bound service, and is just a registered
674 // service, just removing it from the list is all we need to do anyway.
675 removeServiceImpl(this.service, this.userid);
676 }
677
678 /** convenience method for looking in mEnabledServicesForCurrentProfiles */
679 public boolean isEnabledForCurrentProfiles() {
680 if (this.isSystem) return true;
681 if (this.connection == null) return false;
682 return mEnabledServicesForCurrentProfiles.contains(this.component);
683 }
684 }
685
686 public static class UserProfiles {
687 // Profiles of the current user.
688 private final SparseArray<UserInfo> mCurrentProfiles = new SparseArray<UserInfo>();
689
690 public void updateCache(Context context) {
691 UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
692 if (userManager != null) {
693 int currentUserId = ActivityManager.getCurrentUser();
694 List<UserInfo> profiles = userManager.getProfiles(currentUserId);
695 synchronized (mCurrentProfiles) {
696 mCurrentProfiles.clear();
697 for (UserInfo user : profiles) {
698 mCurrentProfiles.put(user.id, user);
699 }
700 }
701 }
702 }
703
704 public int[] getCurrentProfileIds() {
705 synchronized (mCurrentProfiles) {
706 int[] users = new int[mCurrentProfiles.size()];
707 final int N = mCurrentProfiles.size();
708 for (int i = 0; i < N; ++i) {
709 users[i] = mCurrentProfiles.keyAt(i);
710 }
711 return users;
712 }
713 }
714
715 public boolean isCurrentProfile(int userId) {
716 synchronized (mCurrentProfiles) {
717 return mCurrentProfiles.get(userId) != null;
718 }
719 }
720 }
721
722 protected static class Config {
723 String caption;
724 String serviceInterface;
725 String secureSettingName;
726 String bindPermission;
727 String settingsAction;
728 int clientLabel;
729 }
730}