1 /* 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 17 package com.android.server.telecom; 18 19 import android.content.ComponentName; 20 import android.content.Context; 21 import android.content.Intent; 22 import android.content.ServiceConnection; 23 import android.os.IBinder; 24 import android.os.RemoteException; 25 import android.os.UserHandle; 26 import android.telecom.Log; 27 import android.text.TextUtils; 28 import android.util.ArraySet; 29 30 import com.android.internal.annotations.VisibleForTesting; 31 import com.android.internal.util.Preconditions; 32 33 import java.util.Collections; 34 import java.util.Set; 35 import java.util.concurrent.ConcurrentHashMap; 36 37 /** 38 * Abstract class to perform the work of binding and unbinding to the specified service interface. 39 * Subclasses supply the service intent and component name and this class will invoke protected 40 * methods when the class is bound, unbound, or upon failure. 41 */ 42 public abstract class ServiceBinder { 43 44 /** 45 * Callback to notify after a binding succeeds or fails. 46 */ 47 interface BindCallback { onSuccess()48 void onSuccess(); onFailure()49 void onFailure(); 50 } 51 52 /** 53 * Listener for bind events on ServiceBinder. 54 */ 55 interface Listener<ServiceBinderClass extends ServiceBinder> { onUnbind(ServiceBinderClass serviceBinder)56 void onUnbind(ServiceBinderClass serviceBinder); 57 } 58 59 /** 60 * Helper class to perform on-demand binding. 61 */ 62 final class Binder2 { 63 /** 64 * Performs an asynchronous bind to the service (only if not already bound) and executes the 65 * specified callback. 66 * 67 * @param callback The callback to notify of the binding's success or failure. 68 * @param call The call for which we are being bound. 69 */ bind(BindCallback callback, Call call)70 void bind(BindCallback callback, Call call) { 71 Log.d(ServiceBinder.this, "bind()"); 72 73 // Reset any abort request if we're asked to bind again. 74 clearAbort(); 75 76 synchronized (mCallbacks) { 77 if (!mCallbacks.isEmpty()) { 78 // Binding already in progress, append to the list of callbacks and bail out. 79 mCallbacks.add(callback); 80 return; 81 } 82 mCallbacks.add(callback); 83 } 84 85 if (mServiceConnection == null) { 86 Intent serviceIntent = new Intent(mServiceAction).setComponent(mComponentName); 87 ServiceConnection connection = new ServiceBinderConnection(call); 88 89 Log.addEvent(call, LogUtils.Events.BIND_CS, mComponentName); 90 final int bindingFlags = Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE 91 | Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS; 92 final boolean isBound; 93 if (mUserHandle != null) { 94 isBound = mContext.bindServiceAsUser(serviceIntent, connection, bindingFlags, 95 mUserHandle); 96 } else { 97 isBound = mContext.bindService(serviceIntent, connection, bindingFlags); 98 } 99 if (!isBound) { 100 handleFailedConnection(); 101 return; 102 } 103 } else { 104 Log.d(ServiceBinder.this, "Service is already bound."); 105 Preconditions.checkNotNull(mBinder); 106 handleSuccessfulConnection(); 107 } 108 } 109 } 110 111 private class ServiceDeathRecipient implements IBinder.DeathRecipient { 112 113 private ComponentName mComponentName; 114 ServiceDeathRecipient(ComponentName name)115 ServiceDeathRecipient(ComponentName name) { 116 mComponentName = name; 117 } 118 119 @Override binderDied()120 public void binderDied() { 121 try { 122 synchronized (mLock) { 123 Log.startSession("SDR.bD"); 124 Log.i(this, "binderDied: ConnectionService %s died.", mComponentName); 125 logServiceDisconnected("binderDied"); 126 handleDisconnect(); 127 } 128 } finally { 129 Log.endSession(); 130 } 131 } 132 } 133 134 private final class ServiceBinderConnection implements ServiceConnection { 135 /** 136 * The initial call for which the service was bound. 137 */ 138 private Call mCall; 139 ServiceBinderConnection(Call call)140 ServiceBinderConnection(Call call) { 141 mCall = call; 142 } 143 144 @Override onServiceConnected(ComponentName componentName, IBinder binder)145 public void onServiceConnected(ComponentName componentName, IBinder binder) { 146 try { 147 Log.startSession("SBC.oSC"); 148 synchronized (mLock) { 149 Log.i(this, "Service bound %s", componentName); 150 151 Log.addEvent(mCall, LogUtils.Events.CS_BOUND, componentName); 152 mCall = null; 153 154 // Unbind request was queued so unbind immediately. 155 if (mIsBindingAborted) { 156 clearAbort(); 157 logServiceDisconnected("onServiceConnected"); 158 mContext.unbindService(this); 159 handleFailedConnection(); 160 return; 161 } 162 if (binder != null) { 163 mServiceDeathRecipient = new ServiceDeathRecipient(componentName); 164 try { 165 binder.linkToDeath(mServiceDeathRecipient, 0); 166 mServiceConnection = this; 167 setBinder(binder); 168 handleSuccessfulConnection(); 169 } catch (RemoteException e) { 170 Log.w(this, "onServiceConnected: %s died."); 171 if (mServiceDeathRecipient != null) { 172 mServiceDeathRecipient.binderDied(); 173 } 174 } 175 } 176 } 177 } finally { 178 Log.endSession(); 179 } 180 } 181 182 @Override onServiceDisconnected(ComponentName componentName)183 public void onServiceDisconnected(ComponentName componentName) { 184 try { 185 Log.startSession("SBC.oSD"); 186 synchronized (mLock) { 187 logServiceDisconnected("onServiceDisconnected"); 188 handleDisconnect(); 189 } 190 } finally { 191 Log.endSession(); 192 } 193 } 194 } 195 handleDisconnect()196 private void handleDisconnect() { 197 mServiceConnection = null; 198 clearAbort(); 199 200 handleServiceDisconnected(); 201 } 202 203 /** The application context. */ 204 private final Context mContext; 205 206 /** The Telecom lock object. */ 207 protected final TelecomSystem.SyncRoot mLock; 208 209 /** The intent action to use when binding through {@link Context#bindService}. */ 210 private final String mServiceAction; 211 212 /** The component name of the service to bind to. */ 213 protected final ComponentName mComponentName; 214 215 /** The set of callbacks waiting for notification of the binding's success or failure. */ 216 private final Set<BindCallback> mCallbacks = new ArraySet<>(); 217 218 /** Used to bind and unbind from the service. */ 219 private ServiceConnection mServiceConnection; 220 221 /** Used to handle death of the service. */ 222 private ServiceDeathRecipient mServiceDeathRecipient; 223 224 /** {@link UserHandle} to use for binding, to support work profiles and multi-user. */ 225 private UserHandle mUserHandle; 226 227 /** The binder provided by {@link ServiceConnection#onServiceConnected} */ 228 private IBinder mBinder; 229 230 private int mAssociatedCallCount = 0; 231 232 /** 233 * Indicates that an unbind request was made when the service was not yet bound. If the service 234 * successfully connects when this is true, it should be unbound immediately. 235 */ 236 private boolean mIsBindingAborted; 237 238 /** 239 * Set of currently registered listeners. 240 * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is 241 * load factor before resizing, 1 means we only expect a single thread to 242 * access the map so make only a single shard 243 */ 244 private final Set<Listener> mListeners = Collections.newSetFromMap( 245 new ConcurrentHashMap<Listener, Boolean>(8, 0.9f, 1)); 246 247 /** 248 * Persists the specified parameters and initializes the new instance. 249 * 250 * @param serviceAction The intent-action used with {@link Context#bindService}. 251 * @param componentName The component name of the service with which to bind. 252 * @param context The context. 253 * @param userHandle The {@link UserHandle} to use for binding. 254 */ ServiceBinder(String serviceAction, ComponentName componentName, Context context, TelecomSystem.SyncRoot lock, UserHandle userHandle)255 protected ServiceBinder(String serviceAction, ComponentName componentName, Context context, 256 TelecomSystem.SyncRoot lock, UserHandle userHandle) { 257 Preconditions.checkState(!TextUtils.isEmpty(serviceAction)); 258 Preconditions.checkNotNull(componentName); 259 260 mContext = context; 261 mLock = lock; 262 mServiceAction = serviceAction; 263 mComponentName = componentName; 264 mUserHandle = userHandle; 265 } 266 getUserHandle()267 final UserHandle getUserHandle() { 268 return mUserHandle; 269 } 270 incrementAssociatedCallCount()271 final void incrementAssociatedCallCount() { 272 mAssociatedCallCount++; 273 Log.v(this, "Call count increment %d, %s", mAssociatedCallCount, 274 mComponentName.flattenToShortString()); 275 } 276 decrementAssociatedCallCount()277 final void decrementAssociatedCallCount() { 278 decrementAssociatedCallCount(false /*isSuppressingUnbind*/); 279 } 280 decrementAssociatedCallCount(boolean isSuppressingUnbind)281 final void decrementAssociatedCallCount(boolean isSuppressingUnbind) { 282 if (mAssociatedCallCount > 0) { 283 mAssociatedCallCount--; 284 Log.v(this, "Call count decrement %d, %s", mAssociatedCallCount, 285 mComponentName.flattenToShortString()); 286 287 if (!isSuppressingUnbind && mAssociatedCallCount == 0) { 288 unbind(); 289 } 290 } else { 291 Log.wtf(this, "%s: ignoring a request to decrement mAssociatedCallCount below zero", 292 mComponentName.getClassName()); 293 } 294 } 295 getAssociatedCallCount()296 final int getAssociatedCallCount() { 297 return mAssociatedCallCount; 298 } 299 300 /** 301 * Unbinds from the service if already bound, no-op otherwise. 302 */ unbind()303 final void unbind() { 304 if (mServiceConnection == null) { 305 // We're not yet bound, so queue up an abort request. 306 mIsBindingAborted = true; 307 } else { 308 logServiceDisconnected("unbind"); 309 unlinkDeathRecipient(); 310 mContext.unbindService(mServiceConnection); 311 mServiceConnection = null; 312 setBinder(null); 313 } 314 } 315 getComponentName()316 public final ComponentName getComponentName() { 317 return mComponentName; 318 } 319 320 @VisibleForTesting isServiceValid(String actionName)321 public boolean isServiceValid(String actionName) { 322 if (mBinder == null) { 323 Log.w(this, "%s invoked while service is unbound", actionName); 324 return false; 325 } 326 327 return true; 328 } 329 addListener(Listener listener)330 final void addListener(Listener listener) { 331 mListeners.add(listener); 332 } 333 removeListener(Listener listener)334 final void removeListener(Listener listener) { 335 if (listener != null) { 336 mListeners.remove(listener); 337 } 338 } 339 340 /** 341 * Logs a standard message upon service disconnection. This method exists because there is no 342 * single method called whenever the service unbinds and we want to log the same string in all 343 * instances where that occurs. (Context.unbindService() does not cause onServiceDisconnected 344 * to execute). 345 * 346 * @param sourceTag Tag to disambiguate 347 */ logServiceDisconnected(String sourceTag)348 private void logServiceDisconnected(String sourceTag) { 349 Log.i(this, "Service unbound %s, from %s.", mComponentName, sourceTag); 350 } 351 352 /** 353 * Notifies all the outstanding callbacks that the service is successfully bound. The list of 354 * outstanding callbacks is cleared afterwards. 355 */ handleSuccessfulConnection()356 private void handleSuccessfulConnection() { 357 // Make a copy so that we don't have a deadlock inside one of the callbacks. 358 Set<BindCallback> callbacksCopy = new ArraySet<>(); 359 synchronized (mCallbacks) { 360 callbacksCopy.addAll(mCallbacks); 361 mCallbacks.clear(); 362 } 363 364 for (BindCallback callback : callbacksCopy) { 365 callback.onSuccess(); 366 } 367 } 368 369 /** 370 * Notifies all the outstanding callbacks that the service failed to bind. The list of 371 * outstanding callbacks is cleared afterwards. 372 */ handleFailedConnection()373 private void handleFailedConnection() { 374 // Make a copy so that we don't have a deadlock inside one of the callbacks. 375 Set<BindCallback> callbacksCopy = new ArraySet<>(); 376 synchronized (mCallbacks) { 377 callbacksCopy.addAll(mCallbacks); 378 mCallbacks.clear(); 379 } 380 381 for (BindCallback callback : callbacksCopy) { 382 callback.onFailure(); 383 } 384 } 385 386 /** 387 * Handles a service disconnection. 388 */ handleServiceDisconnected()389 private void handleServiceDisconnected() { 390 unlinkDeathRecipient(); 391 setBinder(null); 392 } 393 394 /** 395 * Handles un-linking the death recipient from the service's binder. 396 */ unlinkDeathRecipient()397 private void unlinkDeathRecipient() { 398 if (mServiceDeathRecipient != null && mBinder != null) { 399 boolean unlinked = mBinder.unlinkToDeath(mServiceDeathRecipient, 0); 400 if (!unlinked) { 401 Log.i(this, "unlinkDeathRecipient: failed to unlink %s", mComponentName); 402 } 403 mServiceDeathRecipient = null; 404 } else { 405 Log.w(this, "unlinkDeathRecipient: death recipient is null."); 406 } 407 } 408 clearAbort()409 private void clearAbort() { 410 mIsBindingAborted = false; 411 } 412 413 /** 414 * Sets the (private) binder and updates the child class. 415 * 416 * @param binder The new binder value. 417 */ setBinder(IBinder binder)418 private void setBinder(IBinder binder) { 419 if (mBinder != binder) { 420 if (binder == null) { 421 removeServiceInterface(); 422 mBinder = null; 423 for (Listener l : mListeners) { 424 l.onUnbind(this); 425 } 426 } else { 427 mBinder = binder; 428 setServiceInterface(binder); 429 } 430 } 431 } 432 433 /** 434 * Sets the service interface after the service is bound. 435 * 436 * @param binder The new binder interface that is being set. 437 */ setServiceInterface(IBinder binder)438 protected abstract void setServiceInterface(IBinder binder); 439 440 /** 441 * Removes the service interface before the service is unbound. 442 */ removeServiceInterface()443 protected abstract void removeServiceInterface(); 444 } 445