blob: 81b28e807464e30d5ba2b3016217823138b762c8 [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;
21import android.content.ComponentName;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
25import android.content.ServiceConnection;
26import android.content.pm.ApplicationInfo;
27import android.content.pm.PackageManager;
28import android.content.pm.PackageManager.NameNotFoundException;
29import android.content.pm.ResolveInfo;
30import android.content.pm.ServiceInfo;
31import android.content.pm.UserInfo;
32import android.database.ContentObserver;
33import android.net.Uri;
34import android.os.Build;
35import android.os.Handler;
36import android.os.IBinder;
37import android.os.IInterface;
38import android.os.RemoteException;
39import android.os.UserHandle;
40import android.os.UserManager;
41import android.provider.Settings;
42import android.text.TextUtils;
43import android.util.ArraySet;
44import android.util.Slog;
45import android.util.SparseArray;
46
47import java.io.PrintWriter;
48import java.util.ArrayList;
49import java.util.List;
50import java.util.Set;
51
52/**
53 * Manages the lifecycle of application-provided services bound by system server.
54 *
55 * Services managed by this helper must have:
56 * - An associated system settings value with a list of enabled component names.
57 * - A well-known action for services to use in their intent-filter.
58 * - A system permission for services to require in order to ensure system has exclusive binding.
59 * - A settings page for user configuration of enabled services, and associated intent action.
60 * - A remote interface definition (aidl) provided by the service used for communication.
61 */
62abstract public class ManagedServices {
63 protected final String TAG = getClass().getSimpleName();
64 protected static final boolean DEBUG = true;
65
66 private static final String ENABLED_SERVICES_SEPARATOR = ":";
67
68 private final Context mContext;
69 private final Object mMutex;
70 private final UserProfiles mUserProfiles;
71 private final SettingsObserver mSettingsObserver;
72 private final Config mConfig;
73
74 // contains connections to all connected services, including app services
75 // and system services
76 protected final ArrayList<ManagedServiceInfo> mServices = new ArrayList<ManagedServiceInfo>();
77 // things that will be put into mServices as soon as they're ready
78 private final ArrayList<String> mServicesBinding = new ArrayList<String>();
79 // lists the component names of all enabled (and therefore connected)
80 // app services for current profiles.
81 private ArraySet<ComponentName> mEnabledServicesForCurrentProfiles
82 = new ArraySet<ComponentName>();
83 // Just the packages from mEnabledServicesForCurrentProfiles
84 private ArraySet<String> mEnabledServicesPackageNames = new ArraySet<String>();
85
86 public ManagedServices(Context context, Handler handler, Object mutex,
87 UserProfiles userProfiles) {
88 mContext = context;
89 mMutex = mutex;
90 mUserProfiles = userProfiles;
91 mConfig = getConfig();
92 mSettingsObserver = new SettingsObserver(handler);
93 }
94
95 abstract protected Config getConfig();
96
97 private String getCaption() {
98 return mConfig.caption;
99 }
100
101 abstract protected IInterface asInterface(IBinder binder);
102
103 abstract protected void onServiceAdded(IInterface service);
104
105 private ManagedServiceInfo newServiceInfo(IInterface service,
106 ComponentName component, int userid, boolean isSystem, ServiceConnection connection,
107 int targetSdkVersion) {
108 return new ManagedServiceInfo(service, component, userid, isSystem, connection,
109 targetSdkVersion);
110 }
111
112 public void onBootPhaseAppsCanStart() {
113 mSettingsObserver.observe();
114 }
115
116 public void dump(PrintWriter pw) {
117 pw.println(" All " + getCaption() + "s (" + mEnabledServicesForCurrentProfiles.size()
118 + ") enabled for current profiles:");
119 for (ComponentName cmpt : mEnabledServicesForCurrentProfiles) {
120 pw.println(" " + cmpt);
121 }
122
123 pw.println(" Live " + getCaption() + "s (" + mServices.size() + "):");
124 for (ManagedServiceInfo info : mServices) {
125 pw.println(" " + info.component
126 + " (user " + info.userid + "): " + info.service
127 + (info.isSystem?" SYSTEM":""));
128 }
129 }
130
131 public void onPackagesChanged(boolean queryReplace, String[] pkgList) {
132 boolean anyServicesInvolved = false;
133 if (pkgList != null && (pkgList.length > 0)) {
134 for (String pkgName : pkgList) {
135 if (mEnabledServicesPackageNames.contains(pkgName)) {
136 anyServicesInvolved = true;
137 }
138 }
139 }
140
141 if (anyServicesInvolved) {
142 // if we're not replacing a package, clean up orphaned bits
143 if (!queryReplace) {
144 disableNonexistentServices();
145 }
146 // make sure we're still bound to any of our services who may have just upgraded
147 rebindServices();
148 }
149 }
150
151 public ManagedServiceInfo checkServiceTokenLocked(IInterface service) {
152 checkNotNull(service);
153 final IBinder token = service.asBinder();
154 final int N = mServices.size();
155 for (int i=0; i<N; i++) {
156 final ManagedServiceInfo info = mServices.get(i);
157 if (info.service.asBinder() == token) return info;
158 }
159 throw new SecurityException("Disallowed call from unknown " + getCaption() + ": "
160 + service);
161 }
162
163 public void unregisterService(IInterface service, int userid) {
164 checkNotNull(service);
165 // no need to check permissions; if your service binder is in the list,
166 // that's proof that you had permission to add it in the first place
167 unregisterServiceImpl(service, userid);
168 }
169
170 public void registerService(IInterface service, ComponentName component, int userid) {
171 checkNotNull(service);
172 registerServiceImpl(service, component, userid);
173 }
174
175 /**
176 * Remove access for any services that no longer exist.
177 */
178 private void disableNonexistentServices() {
179 int[] userIds = mUserProfiles.getCurrentProfileIds();
180 final int N = userIds.length;
181 for (int i = 0 ; i < N; ++i) {
182 disableNonexistentServices(userIds[i]);
183 }
184 }
185
186 private void disableNonexistentServices(int userId) {
187 String flatIn = Settings.Secure.getStringForUser(
188 mContext.getContentResolver(),
189 mConfig.secureSettingName,
190 userId);
191 if (!TextUtils.isEmpty(flatIn)) {
192 if (DEBUG) Slog.v(TAG, "flat before: " + flatIn);
193 PackageManager pm = mContext.getPackageManager();
194 List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
195 new Intent(mConfig.serviceInterface),
196 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
197 userId);
198
199 Set<ComponentName> installed = new ArraySet<ComponentName>();
200 for (int i = 0, count = installedServices.size(); i < count; i++) {
201 ResolveInfo resolveInfo = installedServices.get(i);
202 ServiceInfo info = resolveInfo.serviceInfo;
203
204 if (!mConfig.bindPermission.equals(info.permission)) {
205 Slog.w(TAG, "Skipping " + getCaption() + " service "
206 + info.packageName + "/" + info.name
207 + ": it does not require the permission "
208 + mConfig.bindPermission);
209 continue;
210 }
211 installed.add(new ComponentName(info.packageName, info.name));
212 }
213
214 String flatOut = "";
215 if (!installed.isEmpty()) {
216 String[] enabled = flatIn.split(ENABLED_SERVICES_SEPARATOR);
217 ArrayList<String> remaining = new ArrayList<String>(enabled.length);
218 for (int i = 0; i < enabled.length; i++) {
219 ComponentName enabledComponent = ComponentName.unflattenFromString(enabled[i]);
220 if (installed.contains(enabledComponent)) {
221 remaining.add(enabled[i]);
222 }
223 }
224 flatOut = TextUtils.join(ENABLED_SERVICES_SEPARATOR, remaining);
225 }
226 if (DEBUG) Slog.v(TAG, "flat after: " + flatOut);
227 if (!flatIn.equals(flatOut)) {
228 Settings.Secure.putStringForUser(mContext.getContentResolver(),
229 mConfig.secureSettingName,
230 flatOut, userId);
231 }
232 }
233 }
234
235 /**
236 * Called whenever packages change, the user switches, or the secure setting
237 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
238 */
239 private void rebindServices() {
240 if (DEBUG) Slog.d(TAG, "rebindServices");
241 final int[] userIds = mUserProfiles.getCurrentProfileIds();
242 final int nUserIds = userIds.length;
243
244 final SparseArray<String> flat = new SparseArray<String>();
245
246 for (int i = 0; i < nUserIds; ++i) {
247 flat.put(userIds[i], Settings.Secure.getStringForUser(
248 mContext.getContentResolver(),
249 mConfig.secureSettingName,
250 userIds[i]));
251 }
252
253 ManagedServiceInfo[] toRemove = new ManagedServiceInfo[mServices.size()];
254 final SparseArray<ArrayList<ComponentName>> toAdd
255 = new SparseArray<ArrayList<ComponentName>>();
256
257 synchronized (mMutex) {
258 // unbind and remove all existing services
259 toRemove = mServices.toArray(toRemove);
260
261 final ArraySet<ComponentName> newEnabled = new ArraySet<ComponentName>();
262 final ArraySet<String> newPackages = new ArraySet<String>();
263
264 for (int i = 0; i < nUserIds; ++i) {
265 final ArrayList<ComponentName> add = new ArrayList<ComponentName>();
266 toAdd.put(userIds[i], add);
267
268 // decode the list of components
269 String toDecode = flat.get(userIds[i]);
270 if (toDecode != null) {
271 String[] components = toDecode.split(ENABLED_SERVICES_SEPARATOR);
272 for (int j = 0; j < components.length; j++) {
273 final ComponentName component
274 = ComponentName.unflattenFromString(components[j]);
275 if (component != null) {
276 newEnabled.add(component);
277 add.add(component);
278 newPackages.add(component.getPackageName());
279 }
280 }
281
282 }
283 }
284 mEnabledServicesForCurrentProfiles = newEnabled;
285 mEnabledServicesPackageNames = newPackages;
286 }
287
288 for (ManagedServiceInfo info : toRemove) {
289 final ComponentName component = info.component;
290 final int oldUser = info.userid;
291 Slog.v(TAG, "disabling " + getCaption() + " for user "
292 + oldUser + ": " + component);
293 unregisterService(component, info.userid);
294 }
295
296 for (int i = 0; i < nUserIds; ++i) {
297 final ArrayList<ComponentName> add = toAdd.get(userIds[i]);
298 final int N = add.size();
299 for (int j = 0; j < N; j++) {
300 final ComponentName component = add.get(j);
301 Slog.v(TAG, "enabling " + getCaption() + " for user " + userIds[i] + ": "
302 + component);
303 registerService(component, userIds[i]);
304 }
305 }
306 }
307
308 /**
309 * Version of registerService that takes the name of a service component to bind to.
310 */
311 private void registerService(final ComponentName name, final int userid) {
312 if (DEBUG) Slog.v(TAG, "registerService: " + name + " u=" + userid);
313
314 synchronized (mMutex) {
315 final String servicesBindingTag = name.toString() + "/" + userid;
316 if (mServicesBinding.contains(servicesBindingTag)) {
317 // stop registering this thing already! we're working on it
318 return;
319 }
320 mServicesBinding.add(servicesBindingTag);
321
322 final int N = mServices.size();
323 for (int i=N-1; i>=0; i--) {
324 final ManagedServiceInfo info = mServices.get(i);
325 if (name.equals(info.component)
326 && info.userid == userid) {
327 // cut old connections
328 if (DEBUG) Slog.v(TAG, " disconnecting old " + getCaption() + ": "
329 + info.service);
330 mServices.remove(i);
331 if (info.connection != null) {
332 mContext.unbindService(info.connection);
333 }
334 }
335 }
336
337 Intent intent = new Intent(mConfig.serviceInterface);
338 intent.setComponent(name);
339
340 intent.putExtra(Intent.EXTRA_CLIENT_LABEL, mConfig.clientLabel);
341
342 final PendingIntent pendingIntent = PendingIntent.getActivity(
343 mContext, 0, new Intent(mConfig.settingsAction), 0);
344 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, pendingIntent);
345
346 ApplicationInfo appInfo = null;
347 try {
348 appInfo = mContext.getPackageManager().getApplicationInfo(
349 name.getPackageName(), 0);
350 } catch (NameNotFoundException e) {
351 // Ignore if the package doesn't exist we won't be able to bind to the service.
352 }
353 final int targetSdkVersion =
354 appInfo != null ? appInfo.targetSdkVersion : Build.VERSION_CODES.BASE;
355
356 try {
357 if (DEBUG) Slog.v(TAG, "binding: " + intent);
358 if (!mContext.bindServiceAsUser(intent,
359 new ServiceConnection() {
360 IInterface mService;
361
362 @Override
363 public void onServiceConnected(ComponentName name, IBinder binder) {
364 boolean added = false;
365 synchronized (mMutex) {
366 mServicesBinding.remove(servicesBindingTag);
367 try {
368 mService = asInterface(binder);
369 ManagedServiceInfo info = newServiceInfo(mService, name,
370 userid, false /*isSystem*/, this, targetSdkVersion);
371 binder.linkToDeath(info, 0);
372 added = mServices.add(info);
373 } catch (RemoteException e) {
374 // already dead
375 }
376 }
377 if (added) {
378 onServiceAdded(mService);
379 }
380 }
381
382 @Override
383 public void onServiceDisconnected(ComponentName name) {
384 Slog.v(TAG, getCaption() + " connection lost: " + name);
385 }
386 },
387 Context.BIND_AUTO_CREATE,
388 new UserHandle(userid)))
389 {
390 mServicesBinding.remove(servicesBindingTag);
391 Slog.w(TAG, "Unable to bind " + getCaption() + " service: " + intent);
392 return;
393 }
394 } catch (SecurityException ex) {
395 Slog.e(TAG, "Unable to bind " + getCaption() + " service: " + intent, ex);
396 return;
397 }
398 }
399 }
400
401 /**
402 * Remove a service for the given user by ComponentName
403 */
404 private void unregisterService(ComponentName name, int userid) {
405 synchronized (mMutex) {
406 final int N = mServices.size();
407 for (int i=N-1; i>=0; i--) {
408 final ManagedServiceInfo info = mServices.get(i);
409 if (name.equals(info.component)
410 && info.userid == userid) {
411 mServices.remove(i);
412 if (info.connection != null) {
413 try {
414 mContext.unbindService(info.connection);
415 } catch (IllegalArgumentException ex) {
416 // something happened to the service: we think we have a connection
417 // but it's bogus.
418 Slog.e(TAG, getCaption() + " " + name + " could not be unbound: " + ex);
419 }
420 }
421 }
422 }
423 }
424 }
425
426 /**
427 * Removes a service from the list but does not unbind
428 *
429 * @return the removed service.
430 */
431 private ManagedServiceInfo removeServiceImpl(IInterface service, final int userid) {
432 ManagedServiceInfo serviceInfo = null;
433 synchronized (mMutex) {
434 final int N = mServices.size();
435 for (int i=N-1; i>=0; i--) {
436 final ManagedServiceInfo info = mServices.get(i);
437 if (info.service.asBinder() == service.asBinder()
438 && info.userid == userid) {
439 serviceInfo = mServices.remove(i);
440 }
441 }
442 }
443 return serviceInfo;
444 }
445
446 private void checkNotNull(IInterface service) {
447 if (service == null) {
448 throw new IllegalArgumentException(getCaption() + " must not be null");
449 }
450 }
451
452 private void registerServiceImpl(final IInterface service,
453 final ComponentName component, final int userid) {
454 synchronized (mMutex) {
455 try {
456 ManagedServiceInfo info = newServiceInfo(service, component, userid,
457 true /*isSystem*/, null, Build.VERSION_CODES.L);
458 service.asBinder().linkToDeath(info, 0);
459 mServices.add(info);
460 } catch (RemoteException e) {
461 // already dead
462 }
463 }
464 }
465
466 /**
467 * Removes a service from the list and unbinds.
468 */
469 private void unregisterServiceImpl(IInterface service, int userid) {
470 ManagedServiceInfo info = removeServiceImpl(service, userid);
471 if (info != null && info.connection != null) {
472 mContext.unbindService(info.connection);
473 }
474 }
475
476 private class SettingsObserver extends ContentObserver {
477 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(mConfig.secureSettingName);
478
479 private SettingsObserver(Handler handler) {
480 super(handler);
481 }
482
483 private void observe() {
484 ContentResolver resolver = mContext.getContentResolver();
485 resolver.registerContentObserver(mSecureSettingsUri,
486 false, this, UserHandle.USER_ALL);
487 update(null);
488 }
489
490 @Override
491 public void onChange(boolean selfChange, Uri uri) {
492 update(uri);
493 }
494
495 private void update(Uri uri) {
496 if (uri == null || mSecureSettingsUri.equals(uri)) {
497 rebindServices();
498 }
499 }
500 }
501
502 public class ManagedServiceInfo implements IBinder.DeathRecipient {
503 public IInterface service;
504 public ComponentName component;
505 public int userid;
506 public boolean isSystem;
507 public ServiceConnection connection;
508 public int targetSdkVersion;
509
510 public ManagedServiceInfo(IInterface service, ComponentName component,
511 int userid, boolean isSystem, ServiceConnection connection, int targetSdkVersion) {
512 this.service = service;
513 this.component = component;
514 this.userid = userid;
515 this.isSystem = isSystem;
516 this.connection = connection;
517 this.targetSdkVersion = targetSdkVersion;
518 }
519
520 public boolean enabledAndUserMatches(int nid) {
521 if (!isEnabledForCurrentProfiles()) {
522 return false;
523 }
524 if (this.userid == UserHandle.USER_ALL) return true;
525 if (nid == UserHandle.USER_ALL || nid == this.userid) return true;
526 return supportsProfiles() && mUserProfiles.isCurrentProfile(nid);
527 }
528
529 public boolean supportsProfiles() {
530 return targetSdkVersion >= Build.VERSION_CODES.L;
531 }
532
533 @Override
534 public void binderDied() {
535 // Remove the service, but don't unbind from the service. The system will bring the
536 // service back up, and the onServiceConnected handler will readd the service with the
537 // new binding. If this isn't a bound service, and is just a registered
538 // service, just removing it from the list is all we need to do anyway.
539 removeServiceImpl(this.service, this.userid);
540 }
541
542 /** convenience method for looking in mEnabledServicesForCurrentProfiles */
543 public boolean isEnabledForCurrentProfiles() {
544 if (this.isSystem) return true;
545 if (this.connection == null) return false;
546 return mEnabledServicesForCurrentProfiles.contains(this.component);
547 }
548 }
549
550 public static class UserProfiles {
551 // Profiles of the current user.
552 private final SparseArray<UserInfo> mCurrentProfiles = new SparseArray<UserInfo>();
553
554 public void updateCache(Context context) {
555 UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
556 if (userManager != null) {
557 int currentUserId = ActivityManager.getCurrentUser();
558 List<UserInfo> profiles = userManager.getProfiles(currentUserId);
559 synchronized (mCurrentProfiles) {
560 mCurrentProfiles.clear();
561 for (UserInfo user : profiles) {
562 mCurrentProfiles.put(user.id, user);
563 }
564 }
565 }
566 }
567
568 public int[] getCurrentProfileIds() {
569 synchronized (mCurrentProfiles) {
570 int[] users = new int[mCurrentProfiles.size()];
571 final int N = mCurrentProfiles.size();
572 for (int i = 0; i < N; ++i) {
573 users[i] = mCurrentProfiles.keyAt(i);
574 }
575 return users;
576 }
577 }
578
579 public boolean isCurrentProfile(int userId) {
580 synchronized (mCurrentProfiles) {
581 return mCurrentProfiles.get(userId) != null;
582 }
583 }
584 }
585
586 protected static class Config {
587 String caption;
588 String serviceInterface;
589 String secureSettingName;
590 String bindPermission;
591 String settingsAction;
592 int clientLabel;
593 }
594}