blob: c7551c50e9f061c36b6fb9dac73be20b64230930 [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);
Julia Reynolds50f05142015-10-30 17:03:59 -0400348 if (installedServices != null) {
349 for (int i = 0, count = installedServices.size(); i < count; i++) {
350 ResolveInfo resolveInfo = installedServices.get(i);
351 ServiceInfo info = resolveInfo.serviceInfo;
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200352
Julia Reynolds50f05142015-10-30 17:03:59 -0400353 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);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200362 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200363 }
Julia Reynoldsc279b992015-10-30 08:23:51 -0400364 return installed;
365 }
366
367 private void updateSettingsAccordingToInstalledServices(int userId) {
368 boolean restoredChanged = false;
369 boolean currentChanged = false;
370 Set<ComponentName> restored =
371 loadComponentNamesFromSetting(restoredSettingName(mConfig), userId);
372 Set<ComponentName> current =
373 loadComponentNamesFromSetting(mConfig.secureSettingName, userId);
374 // Load all services for all packages.
375 Set<ComponentName> installed = queryPackageForServices(null, userId);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200376
377 ArraySet<ComponentName> retained = new ArraySet<>();
378
379 for (ComponentName component : installed) {
380 if (null != restored) {
381 boolean wasRestored = restored.remove(component);
382 if (wasRestored) {
383 // Freshly installed package has service that was mentioned in restored setting.
384 if (DEBUG)
385 Slog.v(TAG, "Restoring " + component + " for user " + userId);
386 restoredChanged = true;
387 currentChanged = true;
388 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400389 continue;
390 }
John Spurlock7340fc82014-04-24 18:50:12 -0400391 }
392
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200393 if (null != current) {
394 if (current.contains(component))
395 retained.add(component);
John Spurlock7340fc82014-04-24 18:50:12 -0400396 }
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200397 }
398
399 currentChanged |= ((current == null ? 0 : current.size()) != retained.size());
400
401 if (currentChanged) {
402 if (DEBUG) Slog.v(TAG, "List of " + getCaption() + " services was updated " + current);
403 storeComponentsToSetting(retained, mConfig.secureSettingName, userId);
404 }
405
406 if (restoredChanged) {
407 if (DEBUG) Slog.v(TAG,
408 "List of " + getCaption() + " restored services was updated " + restored);
409 storeComponentsToSetting(restored, restoredSettingName(mConfig), userId);
John Spurlock7340fc82014-04-24 18:50:12 -0400410 }
411 }
412
413 /**
414 * Called whenever packages change, the user switches, or the secure setting
415 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
416 */
417 private void rebindServices() {
418 if (DEBUG) Slog.d(TAG, "rebindServices");
419 final int[] userIds = mUserProfiles.getCurrentProfileIds();
420 final int nUserIds = userIds.length;
421
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200422 final SparseArray<ArraySet<ComponentName>> componentsByUser = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400423
424 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200425 componentsByUser.put(userIds[i],
426 loadComponentNamesFromSetting(mConfig.secureSettingName, userIds[i]));
John Spurlock7340fc82014-04-24 18:50:12 -0400427 }
428
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200429 final ArrayList<ManagedServiceInfo> toRemove = new ArrayList<>();
430 final SparseArray<ArrayList<ComponentName>> toAdd = new SparseArray<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400431
432 synchronized (mMutex) {
Christoph Studer5d423842014-05-23 13:15:54 +0200433 // Unbind automatically bound services, retain system services.
434 for (ManagedServiceInfo service : mServices) {
435 if (!service.isSystem) {
436 toRemove.add(service);
437 }
438 }
John Spurlock7340fc82014-04-24 18:50:12 -0400439
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200440 final ArraySet<ComponentName> newEnabled = new ArraySet<>();
441 final ArraySet<String> newPackages = new ArraySet<>();
John Spurlock7340fc82014-04-24 18:50:12 -0400442
443 for (int i = 0; i < nUserIds; ++i) {
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200444 // decode the list of components
445 final ArraySet<ComponentName> userComponents = componentsByUser.get(userIds[i]);
446 if (null == userComponents) {
447 toAdd.put(userIds[i], new ArrayList<ComponentName>());
448 continue;
449 }
450
451 final ArrayList<ComponentName> add = new ArrayList<>(userComponents);
John Spurlock7340fc82014-04-24 18:50:12 -0400452 toAdd.put(userIds[i], add);
453
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200454 newEnabled.addAll(userComponents);
John Spurlock7340fc82014-04-24 18:50:12 -0400455
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200456 for (int j = 0; j < userComponents.size(); j++) {
457 final ComponentName component = userComponents.valueAt(i);
458 newPackages.add(component.getPackageName());
John Spurlock7340fc82014-04-24 18:50:12 -0400459 }
460 }
461 mEnabledServicesForCurrentProfiles = newEnabled;
462 mEnabledServicesPackageNames = newPackages;
463 }
464
465 for (ManagedServiceInfo info : toRemove) {
466 final ComponentName component = info.component;
467 final int oldUser = info.userid;
468 Slog.v(TAG, "disabling " + getCaption() + " for user "
469 + oldUser + ": " + component);
470 unregisterService(component, info.userid);
471 }
472
473 for (int i = 0; i < nUserIds; ++i) {
474 final ArrayList<ComponentName> add = toAdd.get(userIds[i]);
475 final int N = add.size();
476 for (int j = 0; j < N; j++) {
477 final ComponentName component = add.get(j);
478 Slog.v(TAG, "enabling " + getCaption() + " for user " + userIds[i] + ": "
479 + component);
480 registerService(component, userIds[i]);
481 }
482 }
Christoph Studerb53dfd42014-09-12 14:45:59 +0200483
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200484 mLastSeenProfileIds = userIds;
John Spurlock7340fc82014-04-24 18:50:12 -0400485 }
486
487 /**
488 * Version of registerService that takes the name of a service component to bind to.
489 */
490 private void registerService(final ComponentName name, final int userid) {
491 if (DEBUG) Slog.v(TAG, "registerService: " + name + " u=" + userid);
492
493 synchronized (mMutex) {
494 final String servicesBindingTag = name.toString() + "/" + userid;
495 if (mServicesBinding.contains(servicesBindingTag)) {
496 // stop registering this thing already! we're working on it
497 return;
498 }
499 mServicesBinding.add(servicesBindingTag);
500
501 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200502 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400503 final ManagedServiceInfo info = mServices.get(i);
504 if (name.equals(info.component)
505 && info.userid == userid) {
506 // cut old connections
507 if (DEBUG) Slog.v(TAG, " disconnecting old " + getCaption() + ": "
508 + info.service);
John Spurlocke77bb362014-04-26 10:24:59 -0400509 removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400510 if (info.connection != null) {
511 mContext.unbindService(info.connection);
512 }
513 }
514 }
515
516 Intent intent = new Intent(mConfig.serviceInterface);
517 intent.setComponent(name);
518
519 intent.putExtra(Intent.EXTRA_CLIENT_LABEL, mConfig.clientLabel);
520
521 final PendingIntent pendingIntent = PendingIntent.getActivity(
522 mContext, 0, new Intent(mConfig.settingsAction), 0);
523 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, pendingIntent);
524
525 ApplicationInfo appInfo = null;
526 try {
527 appInfo = mContext.getPackageManager().getApplicationInfo(
528 name.getPackageName(), 0);
529 } catch (NameNotFoundException e) {
530 // Ignore if the package doesn't exist we won't be able to bind to the service.
531 }
532 final int targetSdkVersion =
533 appInfo != null ? appInfo.targetSdkVersion : Build.VERSION_CODES.BASE;
534
535 try {
536 if (DEBUG) Slog.v(TAG, "binding: " + intent);
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200537 ServiceConnection serviceConnection = new ServiceConnection() {
538 IInterface mService;
539
540 @Override
541 public void onServiceConnected(ComponentName name, IBinder binder) {
542 boolean added = false;
543 ManagedServiceInfo info = null;
544 synchronized (mMutex) {
545 mServicesBinding.remove(servicesBindingTag);
546 try {
547 mService = asInterface(binder);
548 info = newServiceInfo(mService, name,
549 userid, false /*isSystem*/, this, targetSdkVersion);
550 binder.linkToDeath(info, 0);
551 added = mServices.add(info);
552 } catch (RemoteException e) {
553 // already dead
554 }
555 }
556 if (added) {
557 onServiceAdded(info);
558 }
559 }
560
561 @Override
562 public void onServiceDisconnected(ComponentName name) {
563 Slog.v(TAG, getCaption() + " connection lost: " + name);
564 }
565 };
John Spurlock7340fc82014-04-24 18:50:12 -0400566 if (!mContext.bindServiceAsUser(intent,
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200567 serviceConnection,
Dianne Hackbornd69e4c12015-04-24 09:54:54 -0700568 Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200569 new UserHandle(userid))) {
John Spurlock7340fc82014-04-24 18:50:12 -0400570 mServicesBinding.remove(servicesBindingTag);
571 Slog.w(TAG, "Unable to bind " + getCaption() + " service: " + intent);
572 return;
573 }
574 } catch (SecurityException ex) {
575 Slog.e(TAG, "Unable to bind " + getCaption() + " service: " + intent, ex);
576 return;
577 }
578 }
579 }
580
581 /**
582 * Remove a service for the given user by ComponentName
583 */
584 private void unregisterService(ComponentName name, int userid) {
585 synchronized (mMutex) {
586 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200587 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400588 final ManagedServiceInfo info = mServices.get(i);
589 if (name.equals(info.component)
590 && info.userid == userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400591 removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400592 if (info.connection != null) {
593 try {
594 mContext.unbindService(info.connection);
595 } catch (IllegalArgumentException ex) {
596 // something happened to the service: we think we have a connection
597 // but it's bogus.
598 Slog.e(TAG, getCaption() + " " + name + " could not be unbound: " + ex);
599 }
600 }
601 }
602 }
603 }
604 }
605
606 /**
607 * Removes a service from the list but does not unbind
608 *
609 * @return the removed service.
610 */
611 private ManagedServiceInfo removeServiceImpl(IInterface service, final int userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400612 if (DEBUG) Slog.d(TAG, "removeServiceImpl service=" + service + " u=" + userid);
John Spurlock7340fc82014-04-24 18:50:12 -0400613 ManagedServiceInfo serviceInfo = null;
614 synchronized (mMutex) {
615 final int N = mServices.size();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200616 for (int i = N - 1; i >= 0; i--) {
John Spurlock7340fc82014-04-24 18:50:12 -0400617 final ManagedServiceInfo info = mServices.get(i);
618 if (info.service.asBinder() == service.asBinder()
619 && info.userid == userid) {
John Spurlocke77bb362014-04-26 10:24:59 -0400620 if (DEBUG) Slog.d(TAG, "Removing active service " + info.component);
621 serviceInfo = removeServiceLocked(i);
John Spurlock7340fc82014-04-24 18:50:12 -0400622 }
623 }
624 }
625 return serviceInfo;
626 }
627
John Spurlocke77bb362014-04-26 10:24:59 -0400628 private ManagedServiceInfo removeServiceLocked(int i) {
629 final ManagedServiceInfo info = mServices.remove(i);
630 onServiceRemovedLocked(info);
631 return info;
632 }
633
John Spurlock7340fc82014-04-24 18:50:12 -0400634 private void checkNotNull(IInterface service) {
635 if (service == null) {
636 throw new IllegalArgumentException(getCaption() + " must not be null");
637 }
638 }
639
Christoph Studer3e144d32014-05-22 16:48:40 +0200640 private ManagedServiceInfo registerServiceImpl(final IInterface service,
John Spurlock7340fc82014-04-24 18:50:12 -0400641 final ComponentName component, final int userid) {
642 synchronized (mMutex) {
643 try {
644 ManagedServiceInfo info = newServiceInfo(service, component, userid,
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700645 true /*isSystem*/, null, Build.VERSION_CODES.LOLLIPOP);
John Spurlock7340fc82014-04-24 18:50:12 -0400646 service.asBinder().linkToDeath(info, 0);
647 mServices.add(info);
Christoph Studer3e144d32014-05-22 16:48:40 +0200648 return info;
John Spurlock7340fc82014-04-24 18:50:12 -0400649 } catch (RemoteException e) {
650 // already dead
651 }
652 }
Christoph Studer3e144d32014-05-22 16:48:40 +0200653 return null;
John Spurlock7340fc82014-04-24 18:50:12 -0400654 }
655
656 /**
657 * Removes a service from the list and unbinds.
658 */
659 private void unregisterServiceImpl(IInterface service, int userid) {
660 ManagedServiceInfo info = removeServiceImpl(service, userid);
661 if (info != null && info.connection != null) {
662 mContext.unbindService(info.connection);
663 }
664 }
665
666 private class SettingsObserver extends ContentObserver {
667 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(mConfig.secureSettingName);
668
669 private SettingsObserver(Handler handler) {
670 super(handler);
671 }
672
673 private void observe() {
674 ContentResolver resolver = mContext.getContentResolver();
675 resolver.registerContentObserver(mSecureSettingsUri,
676 false, this, UserHandle.USER_ALL);
677 update(null);
678 }
679
680 @Override
681 public void onChange(boolean selfChange, Uri uri) {
682 update(uri);
683 }
684
685 private void update(Uri uri) {
686 if (uri == null || mSecureSettingsUri.equals(uri)) {
Christoph Studerb53dfd42014-09-12 14:45:59 +0200687 if (DEBUG) Slog.d(TAG, "Setting changed: mSecureSettingsUri=" + mSecureSettingsUri +
688 " / uri=" + uri);
John Spurlock7340fc82014-04-24 18:50:12 -0400689 rebindServices();
Denis Kuznetsov76c02682015-09-17 19:57:00 +0200690 rebuildRestoredPackages();
John Spurlock7340fc82014-04-24 18:50:12 -0400691 }
692 }
693 }
694
695 public class ManagedServiceInfo implements IBinder.DeathRecipient {
696 public IInterface service;
697 public ComponentName component;
698 public int userid;
699 public boolean isSystem;
700 public ServiceConnection connection;
701 public int targetSdkVersion;
702
703 public ManagedServiceInfo(IInterface service, ComponentName component,
704 int userid, boolean isSystem, ServiceConnection connection, int targetSdkVersion) {
705 this.service = service;
706 this.component = component;
707 this.userid = userid;
708 this.isSystem = isSystem;
709 this.connection = connection;
710 this.targetSdkVersion = targetSdkVersion;
711 }
712
John Spurlocke77bb362014-04-26 10:24:59 -0400713 @Override
714 public String toString() {
715 return new StringBuilder("ManagedServiceInfo[")
716 .append("component=").append(component)
717 .append(",userid=").append(userid)
718 .append(",isSystem=").append(isSystem)
719 .append(",targetSdkVersion=").append(targetSdkVersion)
720 .append(",connection=").append(connection == null ? null : "<connection>")
721 .append(",service=").append(service)
722 .append(']').toString();
723 }
724
John Spurlock7340fc82014-04-24 18:50:12 -0400725 public boolean enabledAndUserMatches(int nid) {
726 if (!isEnabledForCurrentProfiles()) {
727 return false;
728 }
729 if (this.userid == UserHandle.USER_ALL) return true;
730 if (nid == UserHandle.USER_ALL || nid == this.userid) return true;
731 return supportsProfiles() && mUserProfiles.isCurrentProfile(nid);
732 }
733
734 public boolean supportsProfiles() {
Dianne Hackborn955d8d62014-10-07 20:17:19 -0700735 return targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
John Spurlock7340fc82014-04-24 18:50:12 -0400736 }
737
738 @Override
739 public void binderDied() {
John Spurlocke77bb362014-04-26 10:24:59 -0400740 if (DEBUG) Slog.d(TAG, "binderDied");
John Spurlock7340fc82014-04-24 18:50:12 -0400741 // Remove the service, but don't unbind from the service. The system will bring the
742 // service back up, and the onServiceConnected handler will readd the service with the
743 // new binding. If this isn't a bound service, and is just a registered
744 // service, just removing it from the list is all we need to do anyway.
745 removeServiceImpl(this.service, this.userid);
746 }
747
748 /** convenience method for looking in mEnabledServicesForCurrentProfiles */
749 public boolean isEnabledForCurrentProfiles() {
750 if (this.isSystem) return true;
751 if (this.connection == null) return false;
752 return mEnabledServicesForCurrentProfiles.contains(this.component);
753 }
754 }
755
756 public static class UserProfiles {
757 // Profiles of the current user.
758 private final SparseArray<UserInfo> mCurrentProfiles = new SparseArray<UserInfo>();
759
760 public void updateCache(Context context) {
761 UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
762 if (userManager != null) {
763 int currentUserId = ActivityManager.getCurrentUser();
764 List<UserInfo> profiles = userManager.getProfiles(currentUserId);
765 synchronized (mCurrentProfiles) {
766 mCurrentProfiles.clear();
767 for (UserInfo user : profiles) {
768 mCurrentProfiles.put(user.id, user);
769 }
770 }
771 }
772 }
773
774 public int[] getCurrentProfileIds() {
775 synchronized (mCurrentProfiles) {
776 int[] users = new int[mCurrentProfiles.size()];
777 final int N = mCurrentProfiles.size();
778 for (int i = 0; i < N; ++i) {
779 users[i] = mCurrentProfiles.keyAt(i);
780 }
781 return users;
782 }
783 }
784
785 public boolean isCurrentProfile(int userId) {
786 synchronized (mCurrentProfiles) {
787 return mCurrentProfiles.get(userId) != null;
788 }
789 }
790 }
791
792 protected static class Config {
793 String caption;
794 String serviceInterface;
795 String secureSettingName;
796 String bindPermission;
797 String settingsAction;
798 int clientLabel;
799 }
800}