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 static android.Manifest.permission.CALL_PHONE; 20 import static android.Manifest.permission.CALL_PRIVILEGED; 21 import static android.Manifest.permission.DUMP; 22 import static android.Manifest.permission.MANAGE_OWN_CALLS; 23 import static android.Manifest.permission.MODIFY_PHONE_STATE; 24 import static android.Manifest.permission.READ_PHONE_NUMBERS; 25 import static android.Manifest.permission.READ_PHONE_STATE; 26 import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE; 27 import static android.Manifest.permission.READ_SMS; 28 import static android.Manifest.permission.REGISTER_SIM_SUBSCRIPTION; 29 import static android.Manifest.permission.WRITE_SECURE_SETTINGS; 30 import static android.telecom.CallAttributes.DIRECTION_INCOMING; 31 import static android.telecom.CallAttributes.DIRECTION_OUTGOING; 32 import static android.telecom.CallException.CODE_ERROR_UNKNOWN; 33 import static android.telecom.TelecomManager.TELECOM_TRANSACTION_SUCCESS; 34 35 import android.Manifest; 36 import android.app.ActivityManager; 37 import android.app.AppOpsManager; 38 import android.app.UiModeManager; 39 import android.app.compat.CompatChanges; 40 import android.content.AttributionSource; 41 import android.content.ComponentName; 42 import android.content.ContentResolver; 43 import android.content.Context; 44 import android.content.Intent; 45 import android.content.PermissionChecker; 46 import android.content.pm.ApplicationInfo; 47 import android.content.pm.PackageManager; 48 import android.content.pm.ParceledListSlice; 49 import android.content.pm.ResolveInfo; 50 import android.graphics.drawable.Icon; 51 import android.net.Uri; 52 import android.os.Binder; 53 import android.os.Build; 54 import android.os.Bundle; 55 import android.os.OutcomeReceiver; 56 import android.os.ParcelFileDescriptor; 57 import android.os.Process; 58 import android.os.RemoteException; 59 import android.os.ResultReceiver; 60 import android.os.ShellCallback; 61 import android.os.UserHandle; 62 import android.provider.BlockedNumberContract; 63 import android.provider.BlockedNumbersManager; 64 import android.provider.Settings; 65 import android.telecom.CallAttributes; 66 import android.telecom.CallException; 67 import android.telecom.DisconnectCause; 68 import android.telecom.Log; 69 import android.telecom.PhoneAccount; 70 import android.telecom.PhoneAccountHandle; 71 import android.telecom.TelecomAnalytics; 72 import android.telecom.TelecomManager; 73 import android.telecom.VideoProfile; 74 import android.telephony.SubscriptionManager; 75 import android.telephony.TelephonyManager; 76 import android.text.TextUtils; 77 import android.util.EventLog; 78 79 import androidx.annotation.NonNull; 80 import androidx.annotation.Nullable; 81 82 import com.android.internal.annotations.VisibleForTesting; 83 import com.android.internal.telecom.ICallControl; 84 import com.android.internal.telecom.ICallEventCallback; 85 import com.android.internal.telecom.ITelecomService; 86 import com.android.internal.util.IndentingPrintWriter; 87 import com.android.modules.utils.BasicShellCommandHandler; 88 import com.android.server.telecom.components.UserCallIntentProcessorFactory; 89 import com.android.server.telecom.flags.FeatureFlags; 90 import com.android.server.telecom.settings.BlockedNumbersActivity; 91 import com.android.server.telecom.voip.IncomingCallTransaction; 92 import com.android.server.telecom.voip.OutgoingCallTransaction; 93 import com.android.server.telecom.voip.TransactionManager; 94 import com.android.server.telecom.voip.VoipCallTransaction; 95 import com.android.server.telecom.voip.VoipCallTransactionResult; 96 97 import java.io.FileDescriptor; 98 import java.io.PrintWriter; 99 import java.lang.reflect.Method; 100 import java.util.Arrays; 101 import java.util.HashSet; 102 import java.util.List; 103 import java.util.Locale; 104 import java.util.Objects; 105 import java.util.Set; 106 import java.util.UUID; 107 108 // TODO: Needed for move to system service: import com.android.internal.R; 109 110 /** 111 * Implementation of the ITelecom interface. 112 */ 113 public class TelecomServiceImpl { 114 115 public interface SubscriptionManagerAdapter { getDefaultVoiceSubId()116 int getDefaultVoiceSubId(); 117 } 118 119 static class SubscriptionManagerAdapterImpl implements SubscriptionManagerAdapter { 120 @Override getDefaultVoiceSubId()121 public int getDefaultVoiceSubId() { 122 return SubscriptionManager.getDefaultVoiceSubscriptionId(); 123 } 124 } 125 126 public interface SettingsSecureAdapter { putStringForUser(ContentResolver resolver, String name, String value, int userHandle)127 void putStringForUser(ContentResolver resolver, String name, String value, int userHandle); 128 getStringForUser(ContentResolver resolver, String name, int userHandle)129 String getStringForUser(ContentResolver resolver, String name, int userHandle); 130 } 131 132 static class SettingsSecureAdapterImpl implements SettingsSecureAdapter { 133 @Override putStringForUser(ContentResolver resolver, String name, String value, int userHandle)134 public void putStringForUser(ContentResolver resolver, String name, String value, 135 int userHandle) { 136 Settings.Secure.putStringForUser(resolver, name, value, userHandle); 137 } 138 139 @Override getStringForUser(ContentResolver resolver, String name, int userHandle)140 public String getStringForUser(ContentResolver resolver, String name, int userHandle) { 141 return Settings.Secure.getStringForUser(resolver, name, userHandle); 142 } 143 } 144 145 private static final String TAG = "TelecomServiceImpl"; 146 private static final String TIME_LINE_ARG = "timeline"; 147 private static final int DEFAULT_VIDEO_STATE = -1; 148 private static final String PERMISSION_HANDLE_CALL_INTENT = 149 "android.permission.HANDLE_CALL_INTENT"; 150 private static final String ADD_CALL_ERR_MSG = "Call could not be created or found. " 151 + "Retry operation."; 152 private AnomalyReporterAdapter mAnomalyReporter = new AnomalyReporterAdapterImpl(); 153 154 /** 155 * Anomaly Report UUIDs and corresponding error descriptions specific to TelecomServiceImpl. 156 */ 157 public static final UUID REGISTER_PHONE_ACCOUNT_ERROR_UUID = 158 UUID.fromString("0e49f82e-6acc-48a9-b088-66c8296c1eb5"); 159 public static final String REGISTER_PHONE_ACCOUNT_ERROR_MSG = 160 "Exception thrown while registering phone account."; 161 public static final UUID SET_USER_PHONE_ACCOUNT_ERROR_UUID = 162 UUID.fromString("80866066-7818-4869-bd44-1f7f689543e2"); 163 public static final String SET_USER_PHONE_ACCOUNT_ERROR_MSG = 164 "Exception thrown while setting the user selected outgoing phone account."; 165 public static final UUID GET_CALL_CAPABLE_ACCOUNTS_ERROR_UUID = 166 UUID.fromString("4f39b865-01f2-4c1f-83a5-37ce52807e83"); 167 public static final String GET_CALL_CAPABLE_ACCOUNTS_ERROR_MSG = 168 "Exception thrown while getting the call capable phone accounts"; 169 public static final UUID GET_PHONE_ACCOUNT_ERROR_UUID = 170 UUID.fromString("b653c1f0-91b4-45c8-ad05-3ee4d1006c7f"); 171 public static final String GET_PHONE_ACCOUNT_ERROR_MSG = 172 "Exception thrown while retrieving the phone account."; 173 public static final UUID GET_SIM_MANAGER_ERROR_UUID = 174 UUID.fromString("4244cb3f-bd02-4cc5-9f90-f41ea62ce0bb"); 175 public static final String GET_SIM_MANAGER_ERROR_MSG = 176 "Exception thrown while retrieving the SIM CallManager."; 177 public static final UUID GET_SIM_MANAGER_FOR_USER_ERROR_UUID = 178 UUID.fromString("5d347ce7-7527-40d3-b98a-09b423ad031c"); 179 public static final String GET_SIM_MANAGER_FOR_USER_ERROR_MSG = 180 "Exception thrown while retrieving the SIM CallManager based on the provided user."; 181 public static final UUID PLACE_CALL_SECURITY_EXCEPTION_ERROR_UUID = 182 UUID.fromString("4edf6c8d-1e43-4c94-b0fc-a40c8d80cfe8"); 183 public static final String PLACE_CALL_SECURITY_EXCEPTION_ERROR_MSG = 184 "Security exception thrown while placing an outgoing call."; 185 186 @VisibleForTesting setAnomalyReporterAdapter(AnomalyReporterAdapter mAnomalyReporterAdapter)187 public void setAnomalyReporterAdapter(AnomalyReporterAdapter mAnomalyReporterAdapter){ 188 mAnomalyReporter = mAnomalyReporterAdapter; 189 } 190 191 private final ITelecomService.Stub mBinderImpl = new ITelecomService.Stub() { 192 193 @Override 194 public void addCall(CallAttributes callAttributes, ICallEventCallback callEventCallback, 195 String callId, String callingPackage) { 196 try { 197 Log.startSession("TSI.aC", Log.getPackageAbbreviation(callingPackage)); 198 Log.i(TAG, "addCall: id=[%s], attributes=[%s]", callId, callAttributes); 199 PhoneAccountHandle handle = callAttributes.getPhoneAccountHandle(); 200 201 // enforce permissions and arguments 202 enforcePermission(android.Manifest.permission.MANAGE_OWN_CALLS); 203 enforceUserHandleMatchesCaller(handle); 204 enforcePhoneAccountIsNotManaged(handle);// only allow self-managed packages (temp.) 205 enforcePhoneAccountIsRegisteredEnabled(handle, handle.getUserHandle()); 206 enforceCallingPackage(callingPackage, "addCall"); 207 208 // add extras about info used for FGS delegation 209 Bundle extras = new Bundle(); 210 extras.putInt(CallAttributes.CALLER_UID_KEY, Binder.getCallingUid()); 211 extras.putInt(CallAttributes.CALLER_PID_KEY, Binder.getCallingPid()); 212 213 VoipCallTransaction transaction = null; 214 // create transaction based on the call direction 215 switch (callAttributes.getDirection()) { 216 case DIRECTION_OUTGOING: 217 transaction = new OutgoingCallTransaction(callId, mContext, callAttributes, 218 mCallsManager, extras, mFeatureFlags); 219 break; 220 case DIRECTION_INCOMING: 221 transaction = new IncomingCallTransaction(callId, callAttributes, 222 mCallsManager, extras, mFeatureFlags); 223 break; 224 default: 225 throw new IllegalArgumentException(String.format("Invalid Call Direction. " 226 + "Was [%d] but should be within [%d,%d]", 227 callAttributes.getDirection(), DIRECTION_INCOMING, 228 DIRECTION_OUTGOING)); 229 } 230 231 mTransactionManager.addTransaction(transaction, new OutcomeReceiver<>() { 232 @Override 233 public void onResult(VoipCallTransactionResult result) { 234 Log.d(TAG, "addCall: onResult"); 235 Call call = result.getCall(); 236 237 if (call == null || !call.getId().equals(callId)) { 238 Log.i(TAG, "addCall: onResult: call is null or id mismatch"); 239 onAddCallControl(callId, callEventCallback, null, 240 new CallException(ADD_CALL_ERR_MSG, CODE_ERROR_UNKNOWN)); 241 return; 242 } 243 244 TransactionalServiceWrapper serviceWrapper = 245 mTransactionalServiceRepository 246 .addNewCallForTransactionalServiceWrapper(handle, 247 callEventCallback, mCallsManager, call); 248 249 call.setTransactionServiceWrapper(serviceWrapper); 250 251 if (mFeatureFlags.transactionalVideoState()) { 252 call.setTransactionalCallSupportsVideoCalling(callAttributes); 253 } 254 ICallControl clientCallControl = serviceWrapper.getICallControl(); 255 256 if (clientCallControl == null) { 257 throw new IllegalStateException("TransactionalServiceWrapper" 258 + "#ICallControl is null."); 259 } 260 261 // finally, send objects back to the client 262 onAddCallControl(callId, callEventCallback, clientCallControl, null); 263 } 264 265 @Override 266 public void onError(@NonNull CallException exception) { 267 Log.d(TAG, "addCall: onError: e=[%s]", exception.toString()); 268 onAddCallControl(callId, callEventCallback, null, exception); 269 } 270 }); 271 } finally { 272 Log.endSession(); 273 } 274 } 275 276 private void onAddCallControl(String callId, ICallEventCallback callEventCallback, 277 ICallControl callControl, CallException callException) { 278 try { 279 if (callException == null) { 280 callEventCallback.onAddCallControl(callId, TELECOM_TRANSACTION_SUCCESS, 281 callControl, null); 282 } else { 283 callEventCallback.onAddCallControl(callId, 284 CallException.CODE_ERROR_UNKNOWN, 285 null, callException); 286 } 287 } catch (RemoteException remoteException) { 288 throw remoteException.rethrowAsRuntimeException(); 289 } 290 } 291 292 @Override 293 public PhoneAccountHandle getDefaultOutgoingPhoneAccount(String uriScheme, 294 String callingPackage, String callingFeatureId) { 295 try { 296 Log.startSession("TSI.gDOPA", Log.getPackageAbbreviation(callingPackage)); 297 synchronized (mLock) { 298 PhoneAccountHandle phoneAccountHandle = null; 299 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 300 long token = Binder.clearCallingIdentity(); 301 try { 302 phoneAccountHandle = mPhoneAccountRegistrar 303 .getOutgoingPhoneAccountForScheme(uriScheme, callingUserHandle); 304 } catch (Exception e) { 305 Log.e(this, e, "getDefaultOutgoingPhoneAccount"); 306 throw e; 307 } finally { 308 Binder.restoreCallingIdentity(token); 309 } 310 if (isCallerSimCallManager(phoneAccountHandle) 311 || canReadPhoneState( 312 callingPackage, 313 callingFeatureId, 314 "getDefaultOutgoingPhoneAccount")) { 315 return phoneAccountHandle; 316 } 317 return null; 318 } 319 } finally { 320 Log.endSession(); 321 } 322 } 323 324 @Override 325 public PhoneAccountHandle getUserSelectedOutgoingPhoneAccount(String callingPackage) { 326 synchronized (mLock) { 327 try { 328 Log.startSession("TSI.gUSOPA", Log.getPackageAbbreviation(callingPackage)); 329 if (!isDialerOrPrivileged(callingPackage, "getDefaultOutgoingPhoneAccount")) { 330 throw new SecurityException("Only the default dialer, or caller with " 331 + "READ_PRIVILEGED_PHONE_STATE can call this method."); 332 } 333 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 334 return mPhoneAccountRegistrar.getUserSelectedOutgoingPhoneAccount( 335 callingUserHandle); 336 } catch (Exception e) { 337 Log.e(this, e, "getUserSelectedOutgoingPhoneAccount"); 338 throw e; 339 } finally { 340 Log.endSession(); 341 } 342 } 343 } 344 345 @Override 346 public void setUserSelectedOutgoingPhoneAccount(PhoneAccountHandle accountHandle) { 347 try { 348 Log.startSession("TSI.sUSOPA"); 349 synchronized (mLock) { 350 enforceModifyPermission(); 351 UserHandle callingUserHandle = Binder.getCallingUserHandle(); 352 long token = Binder.clearCallingIdentity(); 353 try { 354 mPhoneAccountRegistrar.setUserSelectedOutgoingPhoneAccount( 355 accountHandle, callingUserHandle); 356 } catch (Exception e) { 357 Log.e(this, e, "setUserSelectedOutgoingPhoneAccount"); 358 mAnomalyReporter.reportAnomaly(SET_USER_PHONE_ACCOUNT_ERROR_UUID, 359 SET_USER_PHONE_ACCOUNT_ERROR_MSG); 360 throw e; 361 } finally { 362 Binder.restoreCallingIdentity(token); 363 } 364 } 365 } finally { 366 Log.endSession(); 367 } 368 } 369 370 @Override 371 public ParceledListSlice<PhoneAccountHandle> getCallCapablePhoneAccounts( 372 boolean includeDisabledAccounts, String callingPackage, 373 String callingFeatureId, boolean acrossProfiles) { 374 try { 375 Log.startSession("TSI.gCCPA", Log.getPackageAbbreviation(callingPackage)); 376 377 if (mTelephonyFeatureFlags.workProfileApiSplit()) { 378 if (acrossProfiles) { 379 enforceInAppCrossProfilePermission(); 380 } 381 382 if (includeDisabledAccounts && !canReadPrivilegedPhoneState( 383 callingPackage, "getCallCapablePhoneAccounts")) { 384 throw new SecurityException( 385 "Requires READ_PRIVILEGED_PHONE_STATE permission."); 386 } 387 388 if (!includeDisabledAccounts && !canReadPhoneState(callingPackage, 389 callingFeatureId, "Requires READ_PHONE_STATE permission.")) { 390 throw new SecurityException("Requires READ_PHONE_STATE permission."); 391 } 392 } 393 394 if (includeDisabledAccounts && 395 !canReadPrivilegedPhoneState( 396 callingPackage, "getCallCapablePhoneAccounts")) { 397 return ParceledListSlice.emptyList(); 398 } 399 if (!canReadPhoneState(callingPackage, callingFeatureId, 400 "getCallCapablePhoneAccounts")) { 401 return ParceledListSlice.emptyList(); 402 } 403 synchronized (mLock) { 404 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 405 boolean crossUserAccess = mTelephonyFeatureFlags.workProfileApiSplit() 406 && !acrossProfiles ? false 407 : (mTelephonyFeatureFlags.workProfileApiSplit() 408 ? hasInAppCrossProfilePermission() 409 : hasInAppCrossUserPermission()); 410 long token = Binder.clearCallingIdentity(); 411 try { 412 return new ParceledListSlice<>( 413 mPhoneAccountRegistrar.getCallCapablePhoneAccounts(null, 414 includeDisabledAccounts, callingUserHandle, 415 crossUserAccess)); 416 } catch (Exception e) { 417 Log.e(this, e, "getCallCapablePhoneAccounts"); 418 mAnomalyReporter.reportAnomaly(GET_CALL_CAPABLE_ACCOUNTS_ERROR_UUID, 419 GET_CALL_CAPABLE_ACCOUNTS_ERROR_MSG); 420 throw e; 421 } finally { 422 Binder.restoreCallingIdentity(token); 423 } 424 } 425 } finally { 426 Log.endSession(); 427 } 428 } 429 430 @Override 431 public ParceledListSlice<PhoneAccountHandle> getSelfManagedPhoneAccounts( 432 String callingPackage, String callingFeatureId) { 433 try { 434 Log.startSession("TSI.gSMPA", Log.getPackageAbbreviation(callingPackage)); 435 if (!canReadPhoneState(callingPackage, callingFeatureId, 436 "Requires READ_PHONE_STATE permission.")) { 437 throw new SecurityException("Requires READ_PHONE_STATE permission."); 438 } 439 synchronized (mLock) { 440 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 441 long token = Binder.clearCallingIdentity(); 442 try { 443 return new ParceledListSlice<>(mPhoneAccountRegistrar 444 .getSelfManagedPhoneAccounts(callingUserHandle)); 445 } catch (Exception e) { 446 Log.e(this, e, "getSelfManagedPhoneAccounts"); 447 throw e; 448 } finally { 449 Binder.restoreCallingIdentity(token); 450 } 451 } 452 } finally { 453 Log.endSession(); 454 } 455 } 456 457 @Override 458 public ParceledListSlice<PhoneAccountHandle> getOwnSelfManagedPhoneAccounts( 459 String callingPackage, String callingFeatureId) { 460 try { 461 Log.startSession("TSI.gOSMPA", Log.getPackageAbbreviation(callingPackage)); 462 try { 463 enforceCallingPackage(callingPackage, "getOwnSelfManagedPhoneAccounts"); 464 } catch (SecurityException se) { 465 EventLog.writeEvent(0x534e4554, "231986341", Binder.getCallingUid(), 466 "getOwnSelfManagedPhoneAccounts: invalid calling package"); 467 throw se; 468 } 469 if (!canReadMangeOwnCalls("Requires MANAGE_OWN_CALLS permission.")) { 470 throw new SecurityException("Requires MANAGE_OWN_CALLS permission."); 471 } 472 synchronized (mLock) { 473 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 474 long token = Binder.clearCallingIdentity(); 475 try { 476 return new ParceledListSlice<>(mPhoneAccountRegistrar 477 .getSelfManagedPhoneAccountsForPackage(callingPackage, 478 callingUserHandle)); 479 } catch (Exception e) { 480 Log.e(this, e, 481 "getSelfManagedPhoneAccountsForPackage"); 482 throw e; 483 } finally { 484 Binder.restoreCallingIdentity(token); 485 } 486 } 487 } finally { 488 Log.endSession(); 489 } 490 } 491 492 @Override 493 public ParceledListSlice<PhoneAccountHandle> getPhoneAccountsSupportingScheme( 494 String uriScheme, String callingPackage) { 495 try { 496 Log.startSession("TSI.gPASS", Log.getPackageAbbreviation(callingPackage)); 497 try { 498 enforceModifyPermission( 499 "getPhoneAccountsSupportingScheme requires MODIFY_PHONE_STATE"); 500 } catch (SecurityException e) { 501 EventLog.writeEvent(0x534e4554, "62347125", Binder.getCallingUid(), 502 "getPhoneAccountsSupportingScheme: " + callingPackage); 503 return ParceledListSlice.emptyList(); 504 } 505 506 synchronized (mLock) { 507 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 508 long token = Binder.clearCallingIdentity(); 509 try { 510 return new ParceledListSlice<>(mPhoneAccountRegistrar 511 .getCallCapablePhoneAccounts(uriScheme, false, 512 callingUserHandle, false)); 513 } catch (Exception e) { 514 Log.e(this, e, "getPhoneAccountsSupportingScheme %s", uriScheme); 515 throw e; 516 } finally { 517 Binder.restoreCallingIdentity(token); 518 } 519 } 520 } finally { 521 Log.endSession(); 522 } 523 } 524 525 @Override 526 public ParceledListSlice<PhoneAccountHandle> getPhoneAccountsForPackage( 527 String packageName) { 528 //TODO: Deprecate this in S 529 try { 530 enforceCallingPackage(packageName, "getPhoneAccountsForPackage"); 531 } catch (SecurityException se1) { 532 EventLog.writeEvent(0x534e4554, "153995334", Binder.getCallingUid(), 533 "getPhoneAccountsForPackage: invalid calling package"); 534 throw se1; 535 } 536 537 try { 538 enforcePermission(READ_PRIVILEGED_PHONE_STATE); 539 } catch (SecurityException se2) { 540 EventLog.writeEvent(0x534e4554, "153995334", Binder.getCallingUid(), 541 "getPhoneAccountsForPackage: no permission"); 542 throw se2; 543 } 544 545 synchronized (mLock) { 546 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 547 long token = Binder.clearCallingIdentity(); 548 try { 549 Log.startSession("TSI.gPAFP"); 550 return new ParceledListSlice<>(mPhoneAccountRegistrar 551 .getAllPhoneAccountHandlesForPackage(callingUserHandle, packageName)); 552 } catch (Exception e) { 553 Log.e(this, e, "getPhoneAccountsForPackage %s", packageName); 554 throw e; 555 } finally { 556 Binder.restoreCallingIdentity(token); 557 Log.endSession(); 558 } 559 } 560 } 561 562 @Override 563 public PhoneAccount getPhoneAccount(PhoneAccountHandle accountHandle, 564 String callingPackage) { 565 try { 566 Log.startSession("TSI.gPA", Log.getPackageAbbreviation(callingPackage)); 567 try { 568 enforceCallingPackage(callingPackage, "getPhoneAccount"); 569 } catch (SecurityException se) { 570 EventLog.writeEvent(0x534e4554, "196406138", Binder.getCallingUid(), 571 "getPhoneAccount: invalid calling package"); 572 throw se; 573 } 574 synchronized (mLock) { 575 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 576 if (CompatChanges.isChangeEnabled( 577 TelecomManager.ENABLE_GET_PHONE_ACCOUNT_PERMISSION_PROTECTION, 578 callingPackage, Binder.getCallingUserHandle())) { 579 if (Binder.getCallingUid() != Process.SHELL_UID && 580 !canGetPhoneAccount(callingPackage, accountHandle)) { 581 SecurityException e = new SecurityException( 582 "getPhoneAccount API requires" + 583 "READ_PHONE_NUMBERS"); 584 Log.e(this, e, "getPhoneAccount %s", accountHandle); 585 throw e; 586 } 587 } 588 Set<String> permissions = computePermissionsForBoundPackage( 589 Set.of(MODIFY_PHONE_STATE), null); 590 long token = Binder.clearCallingIdentity(); 591 try { 592 // In ideal case, we should not resolve the handle across profiles. But 593 // given the fact that profile's call is handled by its parent user's 594 // in-call UI, parent user's in call UI need to be able to get phone account 595 // from the profile's phone account handle. 596 PhoneAccount account = mPhoneAccountRegistrar 597 .getPhoneAccount(accountHandle, callingUserHandle, 598 /* acrossProfiles */ true); 599 return maybeCleansePhoneAccount(account, permissions); 600 } catch (Exception e) { 601 Log.e(this, e, "getPhoneAccount %s", accountHandle); 602 mAnomalyReporter.reportAnomaly(GET_PHONE_ACCOUNT_ERROR_UUID, 603 GET_PHONE_ACCOUNT_ERROR_MSG); 604 throw e; 605 } finally { 606 Binder.restoreCallingIdentity(token); 607 } 608 } 609 } finally { 610 Log.endSession(); 611 } 612 } 613 614 @Override 615 public ParceledListSlice<PhoneAccount> getRegisteredPhoneAccounts(String callingPackage, 616 String callingFeatureId) { 617 try { 618 Log.startSession("TSI.gRPA", Log.getPackageAbbreviation(callingPackage)); 619 try { 620 enforceCallingPackage(callingPackage, "getRegisteredPhoneAccounts"); 621 } catch (SecurityException se) { 622 EventLog.writeEvent(0x534e4554, "307609763", Binder.getCallingUid(), 623 "getRegisteredPhoneAccounts: invalid calling package"); 624 throw se; 625 } 626 627 boolean hasCrossUserAccess = false; 628 try { 629 enforceInAppCrossUserPermission(); 630 hasCrossUserAccess = true; 631 } catch (SecurityException e) { 632 // pass through 633 } 634 635 synchronized (mLock) { 636 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 637 long token = Binder.clearCallingIdentity(); 638 try { 639 return new ParceledListSlice<>( 640 mPhoneAccountRegistrar.getPhoneAccounts( 641 0 /* capabilities */, 642 0 /* excludedCapabilities */, 643 null /* UriScheme */, 644 callingPackage, 645 true /* includeDisabledAccounts */, 646 callingUserHandle, 647 hasCrossUserAccess /* crossUserAccess */, 648 false /* includeAll */)); 649 } catch (Exception e) { 650 Log.e(this, e, "getRegisteredPhoneAccounts"); 651 throw e; 652 } finally { 653 Binder.restoreCallingIdentity(token); 654 } 655 } 656 } finally { 657 Log.endSession(); 658 } 659 } 660 661 @Override 662 public int getAllPhoneAccountsCount() { 663 try { 664 Log.startSession("TSI.gAPAC"); 665 try { 666 enforceModifyPermission( 667 "getAllPhoneAccountsCount requires MODIFY_PHONE_STATE permission."); 668 } catch (SecurityException e) { 669 EventLog.writeEvent(0x534e4554, "62347125", Binder.getCallingUid(), 670 "getAllPhoneAccountsCount"); 671 throw e; 672 } 673 674 synchronized (mLock) { 675 try { 676 // This list is pre-filtered for the calling user. 677 return getAllPhoneAccounts().getList().size(); 678 } catch (Exception e) { 679 Log.e(this, e, "getAllPhoneAccountsCount"); 680 throw e; 681 682 } 683 } 684 } finally { 685 Log.endSession(); 686 } 687 } 688 689 @Override 690 public ParceledListSlice<PhoneAccount> getAllPhoneAccounts() { 691 synchronized (mLock) { 692 try { 693 Log.startSession("TSI.gAPA"); 694 try { 695 enforceModifyPermission( 696 "getAllPhoneAccounts requires MODIFY_PHONE_STATE permission."); 697 } catch (SecurityException e) { 698 EventLog.writeEvent(0x534e4554, "62347125", Binder.getCallingUid(), 699 "getAllPhoneAccounts"); 700 throw e; 701 } 702 703 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 704 long token = Binder.clearCallingIdentity(); 705 try { 706 return new ParceledListSlice<>(mPhoneAccountRegistrar 707 .getAllPhoneAccounts(callingUserHandle, false)); 708 } catch (Exception e) { 709 Log.e(this, e, "getAllPhoneAccounts"); 710 throw e; 711 } finally { 712 Binder.restoreCallingIdentity(token); 713 } 714 } finally { 715 Log.endSession(); 716 } 717 } 718 } 719 720 @Override 721 public ParceledListSlice<PhoneAccountHandle> getAllPhoneAccountHandles() { 722 try { 723 Log.startSession("TSI.gAPAH"); 724 725 try { 726 enforceModifyPermission( 727 "getAllPhoneAccountHandles requires MODIFY_PHONE_STATE permission."); 728 } catch (SecurityException e) { 729 EventLog.writeEvent(0x534e4554, "62347125", Binder.getCallingUid(), 730 "getAllPhoneAccountHandles"); 731 throw e; 732 } 733 734 synchronized (mLock) { 735 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 736 boolean crossUserAccess = hasInAppCrossUserPermission(); 737 long token = Binder.clearCallingIdentity(); 738 try { 739 return new ParceledListSlice<>(mPhoneAccountRegistrar 740 .getAllPhoneAccountHandles(callingUserHandle, 741 crossUserAccess)); 742 } catch (Exception e) { 743 Log.e(this, e, "getAllPhoneAccountsHandles"); 744 throw e; 745 } finally { 746 Binder.restoreCallingIdentity(token); 747 } 748 } 749 } finally { 750 Log.endSession(); 751 } 752 } 753 754 @Override 755 public PhoneAccountHandle getSimCallManager(int subId, String callingPackage) { 756 synchronized (mLock) { 757 try { 758 Log.startSession("TSI.gSCM", Log.getPackageAbbreviation(callingPackage)); 759 final int callingUid = Binder.getCallingUid(); 760 final int user = UserHandle.getUserId(callingUid); 761 long token = Binder.clearCallingIdentity(); 762 try { 763 if (user != ActivityManager.getCurrentUser()) { 764 enforceCrossUserPermission(callingUid); 765 } 766 return mPhoneAccountRegistrar.getSimCallManager(subId, UserHandle.of(user)); 767 } finally { 768 Binder.restoreCallingIdentity(token); 769 } 770 } catch (Exception e) { 771 Log.e(this, e, "getSimCallManager"); 772 mAnomalyReporter.reportAnomaly(GET_SIM_MANAGER_ERROR_UUID, 773 GET_SIM_MANAGER_ERROR_MSG); 774 throw e; 775 } finally { 776 Log.endSession(); 777 } 778 } 779 } 780 781 @Override 782 public PhoneAccountHandle getSimCallManagerForUser(int user, String callingPackage) { 783 synchronized (mLock) { 784 try { 785 Log.startSession("TSI.gSCMFU", Log.getPackageAbbreviation(callingPackage)); 786 final int callingUid = Binder.getCallingUid(); 787 if (user != ActivityManager.getCurrentUser()) { 788 enforceCrossUserPermission(callingUid); 789 } 790 long token = Binder.clearCallingIdentity(); 791 try { 792 return mPhoneAccountRegistrar.getSimCallManager(UserHandle.of(user)); 793 } finally { 794 Binder.restoreCallingIdentity(token); 795 } 796 } catch (Exception e) { 797 Log.e(this, e, "getSimCallManager"); 798 mAnomalyReporter.reportAnomaly(GET_SIM_MANAGER_FOR_USER_ERROR_UUID, 799 GET_SIM_MANAGER_FOR_USER_ERROR_MSG); 800 throw e; 801 } finally { 802 Log.endSession(); 803 } 804 } 805 } 806 807 @Override 808 public void registerPhoneAccount(PhoneAccount account, String callingPackage) { 809 try { 810 Log.startSession("TSI.rPA", Log.getPackageAbbreviation(callingPackage)); 811 synchronized (mLock) { 812 try { 813 enforcePhoneAccountModificationForPackage( 814 account.getAccountHandle().getComponentName().getPackageName()); 815 if (account.hasCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)) { 816 enforceRegisterSelfManaged(); 817 if (account.hasCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER) || 818 account.hasCapabilities( 819 PhoneAccount.CAPABILITY_CONNECTION_MANAGER) || 820 account.hasCapabilities( 821 PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) { 822 throw new SecurityException("Self-managed ConnectionServices " + 823 "cannot also be call capable, connection managers, or " + 824 "SIM accounts."); 825 } 826 827 // For self-managed CS, the phone account registrar will override the 828 // label the user has set for the phone account. This ensures the 829 // self-managed cs implementation can't spoof their app name. 830 } 831 if (account.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) { 832 enforceRegisterSimSubscriptionPermission(); 833 } 834 if (account.hasCapabilities(PhoneAccount.CAPABILITY_MULTI_USER)) { 835 enforceRegisterMultiUser(); 836 } 837 // These capabilities are for SIM-based accounts only, so only the platform 838 // and carrier-designated SIM call manager can register accounts with these 839 // capabilities. 840 if (account.hasCapabilities( 841 PhoneAccount.CAPABILITY_SUPPORTS_VOICE_CALLING_INDICATIONS) 842 || account.hasCapabilities( 843 PhoneAccount.CAPABILITY_VOICE_CALLING_AVAILABLE)) { 844 enforceRegisterVoiceCallingIndicationCapabilities(account); 845 } 846 Bundle extras = account.getExtras(); 847 if (extras != null 848 && extras.getBoolean(PhoneAccount.EXTRA_SKIP_CALL_FILTERING)) { 849 // System apps should be granted the MODIFY_PHONE_STATE permission. 850 enforceModifyPermission( 851 "registerPhoneAccount requires MODIFY_PHONE_STATE permission."); 852 enforceRegisterSkipCallFiltering(); 853 } 854 final int callingUid = Binder.getCallingUid(); 855 if (callingUid != Process.SHELL_UID) { 856 enforceUserHandleMatchesCaller(account.getAccountHandle()); 857 } 858 859 if (TextUtils.isEmpty(account.getGroupId()) 860 && mContext.checkCallingOrSelfPermission(MODIFY_PHONE_STATE) 861 != PackageManager.PERMISSION_GRANTED) { 862 Log.w(this, "registerPhoneAccount - attempt to set a" 863 + " group from a non-system caller."); 864 // Not permitted to set group, so null it out. 865 account = new PhoneAccount.Builder(account) 866 .setGroupId(null) 867 .build(); 868 } 869 870 // Validate the profile boundary of the given image URI. 871 validateAccountIconUserBoundary(account.getIcon()); 872 873 if (mTelephonyFeatureFlags.simultaneousCallingIndications() 874 && account.hasSimultaneousCallingRestriction()) { 875 validateSimultaneousCallingPackageNames( 876 account.getAccountHandle().getComponentName().getPackageName(), 877 account.getSimultaneousCallingRestriction()); 878 } 879 880 final long token = Binder.clearCallingIdentity(); 881 try { 882 Log.i(this, "registerPhoneAccount: account=%s", 883 account); 884 mPhoneAccountRegistrar.registerPhoneAccount(account); 885 } finally { 886 Binder.restoreCallingIdentity(token); 887 } 888 } catch (Exception e) { 889 Log.e(this, e, "registerPhoneAccount %s", account); 890 mAnomalyReporter.reportAnomaly(REGISTER_PHONE_ACCOUNT_ERROR_UUID, 891 REGISTER_PHONE_ACCOUNT_ERROR_MSG); 892 throw e; 893 } 894 } 895 } finally { 896 Log.endSession(); 897 } 898 } 899 900 @Override 901 public void unregisterPhoneAccount(PhoneAccountHandle accountHandle, 902 String callingPackage) { 903 synchronized (mLock) { 904 try { 905 Log.startSession("TSI.uPA", Log.getPackageAbbreviation(callingPackage)); 906 enforcePhoneAccountModificationForPackage( 907 accountHandle.getComponentName().getPackageName()); 908 enforceUserHandleMatchesCaller(accountHandle); 909 final long token = Binder.clearCallingIdentity(); 910 try { 911 mPhoneAccountRegistrar.unregisterPhoneAccount(accountHandle); 912 } finally { 913 Binder.restoreCallingIdentity(token); 914 } 915 } catch (Exception e) { 916 Log.e(this, e, "unregisterPhoneAccount %s", accountHandle); 917 throw e; 918 } finally { 919 Log.endSession(); 920 } 921 } 922 } 923 924 @Override 925 public void clearAccounts(String packageName) { 926 synchronized (mLock) { 927 try { 928 Log.startSession("TSI.cA"); 929 enforcePhoneAccountModificationForPackage(packageName); 930 mPhoneAccountRegistrar 931 .clearAccounts(packageName, Binder.getCallingUserHandle()); 932 } catch (Exception e) { 933 Log.e(this, e, "clearAccounts %s", packageName); 934 throw e; 935 } finally { 936 Log.endSession(); 937 } 938 } 939 } 940 941 /** 942 * @see android.telecom.TelecomManager#isVoiceMailNumber 943 */ 944 @Override 945 public boolean isVoiceMailNumber(PhoneAccountHandle accountHandle, String number, 946 String callingPackage, String callingFeatureId) { 947 try { 948 Log.startSession("TSI.iVMN", Log.getPackageAbbreviation(callingPackage)); 949 synchronized (mLock) { 950 if (!canReadPhoneState(callingPackage, callingFeatureId, "isVoiceMailNumber")) { 951 return false; 952 } 953 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 954 if (!isPhoneAccountHandleVisibleToCallingUser(accountHandle, 955 callingUserHandle)) { 956 Log.d(this, "%s is not visible for the calling user [iVMN]", accountHandle); 957 return false; 958 } 959 long token = Binder.clearCallingIdentity(); 960 try { 961 return mPhoneAccountRegistrar.isVoiceMailNumber(accountHandle, number); 962 } catch (Exception e) { 963 Log.e(this, e, "getSubscriptionIdForPhoneAccount"); 964 throw e; 965 } finally { 966 Binder.restoreCallingIdentity(token); 967 } 968 } 969 } finally { 970 Log.endSession(); 971 } 972 } 973 974 /** 975 * @see android.telecom.TelecomManager#getVoiceMailNumber 976 */ 977 @Override 978 public String getVoiceMailNumber(PhoneAccountHandle accountHandle, String callingPackage, 979 String callingFeatureId) { 980 try { 981 Log.startSession("TSI.gVMN", Log.getPackageAbbreviation(callingPackage)); 982 if (!canReadPhoneState(callingPackage, callingFeatureId, "getVoiceMailNumber")) { 983 return null; 984 } 985 try { 986 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 987 if (!isPhoneAccountHandleVisibleToCallingUser(accountHandle, 988 callingUserHandle)) { 989 Log.d(this, "%s is not visible for the calling user [gVMN]", 990 accountHandle); 991 return null; 992 } 993 int subId = mSubscriptionManagerAdapter.getDefaultVoiceSubId(); 994 synchronized (mLock) { 995 if (accountHandle != null) { 996 subId = mPhoneAccountRegistrar 997 .getSubscriptionIdForPhoneAccount(accountHandle); 998 } 999 } 1000 return getTelephonyManager(subId).getVoiceMailNumber(); 1001 } catch (UnsupportedOperationException ignored) { 1002 Log.w(this, "getVoiceMailNumber: no Telephony"); 1003 return null; 1004 } catch (Exception e) { 1005 Log.e(this, e, "getSubscriptionIdForPhoneAccount"); 1006 throw e; 1007 } 1008 } finally { 1009 Log.endSession(); 1010 } 1011 } 1012 1013 /** 1014 * @see android.telecom.TelecomManager#getLine1Number 1015 */ 1016 @Override 1017 public String getLine1Number(PhoneAccountHandle accountHandle, String callingPackage, 1018 String callingFeatureId) { 1019 try { 1020 Log.startSession("getL1N", Log.getPackageAbbreviation(callingPackage)); 1021 if (!canReadPhoneNumbers(callingPackage, callingFeatureId, "getLine1Number")) { 1022 return null; 1023 } 1024 1025 final UserHandle callingUserHandle = Binder.getCallingUserHandle(); 1026 if (!isPhoneAccountHandleVisibleToCallingUser(accountHandle, 1027 callingUserHandle)) { 1028 Log.d(this, "%s is not visible for the calling user [gL1N]", accountHandle); 1029 return null; 1030 } 1031 1032 long token = Binder.clearCallingIdentity(); 1033 try { 1034 int subId; 1035 synchronized (mLock) { 1036 subId = mPhoneAccountRegistrar.getSubscriptionIdForPhoneAccount( 1037 accountHandle); 1038 } 1039 return getTelephonyManager(subId).getLine1Number(); 1040 } catch (UnsupportedOperationException ignored) { 1041 Log.w(this, "getLine1Number: no telephony"); 1042 return null; 1043 } catch (Exception e) { 1044 Log.e(this, e, "getSubscriptionIdForPhoneAccount"); 1045 throw e; 1046 } finally { 1047 Binder.restoreCallingIdentity(token); 1048 } 1049 } finally { 1050 Log.endSession(); 1051 } 1052 } 1053 1054 /** 1055 * @see android.telecom.TelecomManager#silenceRinger 1056 */ 1057 @Override 1058 public void silenceRinger(String callingPackage) { 1059 try { 1060 Log.startSession("TSI.sR", Log.getPackageAbbreviation(callingPackage)); 1061 synchronized (mLock) { 1062 enforcePermissionOrPrivilegedDialer(MODIFY_PHONE_STATE, callingPackage); 1063 UserHandle callingUserHandle = Binder.getCallingUserHandle(); 1064 boolean crossUserAccess = hasInAppCrossUserPermission(); 1065 long token = Binder.clearCallingIdentity(); 1066 try { 1067 Log.i(this, "Silence Ringer requested by %s", callingPackage); 1068 Set<UserHandle> userHandles = mCallsManager.getCallAudioManager(). 1069 silenceRingers(mContext, callingUserHandle, 1070 crossUserAccess); 1071 mCallsManager.getInCallController().silenceRinger(userHandles); 1072 } finally { 1073 Binder.restoreCallingIdentity(token); 1074 } 1075 } 1076 } finally { 1077 Log.endSession(); 1078 } 1079 } 1080 1081 /** 1082 * @see android.telecom.TelecomManager#getDefaultPhoneApp 1083 * @deprecated - Use {@link android.telecom.TelecomManager#getDefaultDialerPackage()} 1084 * instead. 1085 */ 1086 @Override 1087 public ComponentName getDefaultPhoneApp() { 1088 try { 1089 Log.startSession("TSI.gDPA"); 1090 return mDefaultDialerCache.getDialtactsSystemDialerComponent(); 1091 } finally { 1092 Log.endSession(); 1093 } 1094 } 1095 1096 /** 1097 * @return the package name of the current user-selected default dialer. If no default 1098 * has been selected, the package name of the system dialer is returned. If 1099 * neither exists, then {@code null} is returned. 1100 * @see android.telecom.TelecomManager#getDefaultDialerPackage 1101 */ 1102 @Override 1103 public String getDefaultDialerPackage(String callingPackage) { 1104 try { 1105 Log.startSession("TSI.gDDP", Log.getPackageAbbreviation(callingPackage)); 1106 int callerUserId = UserHandle.getCallingUserId(); 1107 final long token = Binder.clearCallingIdentity(); 1108 try { 1109 return mDefaultDialerCache.getDefaultDialerApplication( 1110 callerUserId); 1111 } finally { 1112 Binder.restoreCallingIdentity(token); 1113 } 1114 } finally { 1115 Log.endSession(); 1116 } 1117 } 1118 1119 /** 1120 * @param userId user id to get the default dialer package for 1121 * @return the package name of the current user-selected default dialer. If no default 1122 * has been selected, the package name of the system dialer is returned. If 1123 * neither exists, then {@code null} is returned. 1124 * @see android.telecom.TelecomManager#getDefaultDialerPackage 1125 */ 1126 @Override 1127 public String getDefaultDialerPackageForUser(int userId) { 1128 try { 1129 Log.startSession("TSI.gDDPU"); 1130 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, 1131 "READ_PRIVILEGED_PHONE_STATE permission required."); 1132 1133 final long token = Binder.clearCallingIdentity(); 1134 try { 1135 return mDefaultDialerCache.getDefaultDialerApplication(userId); 1136 } finally { 1137 Binder.restoreCallingIdentity(token); 1138 } 1139 } finally { 1140 Log.endSession(); 1141 } 1142 } 1143 1144 /** 1145 * @see android.telecom.TelecomManager#getSystemDialerPackage 1146 */ 1147 @Override 1148 public String getSystemDialerPackage(String callingPackage) { 1149 try { 1150 Log.startSession("TSI.gSDP", Log.getPackageAbbreviation(callingPackage)); 1151 return mDefaultDialerCache.getSystemDialerApplication(); 1152 } finally { 1153 Log.endSession(); 1154 } 1155 } 1156 1157 public void setSystemDialer(ComponentName testComponentName) { 1158 try { 1159 Log.startSession("TSI.sSD"); 1160 enforceModifyPermission(); 1161 enforceShellOnly(Binder.getCallingUid(), "setSystemDialer"); 1162 synchronized (mLock) { 1163 long token = Binder.clearCallingIdentity(); 1164 try { 1165 mDefaultDialerCache.setSystemDialerComponentName(testComponentName); 1166 } finally { 1167 Binder.restoreCallingIdentity(token); 1168 } 1169 } 1170 } finally { 1171 Log.endSession(); 1172 } 1173 } 1174 1175 /** 1176 * @see android.telecom.TelecomManager#isInCall 1177 */ 1178 @Override 1179 public boolean isInCall(String callingPackage, String callingFeatureId) { 1180 try { 1181 Log.startSession("TSI.iIC", Log.getPackageAbbreviation(callingPackage)); 1182 if (!canReadPhoneState(callingPackage, callingFeatureId, "isInCall")) { 1183 return false; 1184 } 1185 1186 synchronized (mLock) { 1187 return mCallsManager.hasOngoingCalls(Binder.getCallingUserHandle(), 1188 hasInAppCrossUserPermission()); 1189 } 1190 } finally { 1191 Log.endSession(); 1192 } 1193 } 1194 1195 /** 1196 * @see android.telecom.TelecomManager#hasManageOngoingCallsPermission 1197 */ 1198 @Override 1199 public boolean hasManageOngoingCallsPermission(String callingPackage) { 1200 try { 1201 Log.startSession("TSI.hMOCP", Log.getPackageAbbreviation(callingPackage)); 1202 enforceCallingPackage(callingPackage, "hasManageOngoingCallsPermission"); 1203 return PermissionChecker.checkPermissionForDataDeliveryFromDataSource( 1204 mContext, Manifest.permission.MANAGE_ONGOING_CALLS, 1205 Binder.getCallingPid(), 1206 new AttributionSource(mContext.getAttributionSource(), 1207 new AttributionSource(Binder.getCallingUid(), 1208 callingPackage, /*attributionTag*/ null)), 1209 "Checking whether the caller has MANAGE_ONGOING_CALLS permission") 1210 == PermissionChecker.PERMISSION_GRANTED; 1211 } finally { 1212 Log.endSession(); 1213 } 1214 } 1215 1216 /** 1217 * @see android.telecom.TelecomManager#isInManagedCall 1218 */ 1219 @Override 1220 public boolean isInManagedCall(String callingPackage, String callingFeatureId) { 1221 try { 1222 Log.startSession("TSI.iIMC", Log.getPackageAbbreviation(callingPackage)); 1223 if (!canReadPhoneState(callingPackage, callingFeatureId, "isInManagedCall")) { 1224 throw new SecurityException("Only the default dialer or caller with " + 1225 "READ_PHONE_STATE permission can use this method."); 1226 } 1227 1228 synchronized (mLock) { 1229 return mCallsManager.hasOngoingManagedCalls(Binder.getCallingUserHandle(), 1230 hasInAppCrossUserPermission()); 1231 } 1232 } finally { 1233 Log.endSession(); 1234 } 1235 } 1236 1237 /** 1238 * @see android.telecom.TelecomManager#isRinging 1239 */ 1240 @Override 1241 public boolean isRinging(String callingPackage) { 1242 try { 1243 Log.startSession("TSI.iR"); 1244 if (!isPrivilegedDialerCalling(callingPackage)) { 1245 try { 1246 enforceModifyPermission( 1247 "isRinging requires MODIFY_PHONE_STATE permission."); 1248 } catch (SecurityException e) { 1249 EventLog.writeEvent(0x534e4554, "62347125", "isRinging: " + callingPackage); 1250 throw e; 1251 } 1252 } 1253 1254 synchronized (mLock) { 1255 // Note: We are explicitly checking the calls telecom is tracking rather than 1256 // relying on mCallsManager#getCallState(). Since getCallState() relies on the 1257 // current state as tracked by PhoneStateBroadcaster, any failure to properly 1258 // track the current call state there could result in the wrong ringing state 1259 // being reported by this API. 1260 return mCallsManager.hasRingingOrSimulatedRingingCall(); 1261 } 1262 } finally { 1263 Log.endSession(); 1264 } 1265 } 1266 1267 /** 1268 * @see TelecomManager#getCallState() 1269 * @deprecated this is only being kept due to an @UnsupportedAppUsage tag. Apps targeting 1270 * API 31+ must use {@link #getCallStateUsingPackage(String, String)} below. 1271 */ 1272 @Deprecated 1273 @Override 1274 public int getCallState() { 1275 try { 1276 Log.startSession("TSI.getCallState(DEPRECATED)"); 1277 if (CompatChanges.isChangeEnabled( 1278 TelecomManager.ENABLE_GET_CALL_STATE_PERMISSION_PROTECTION, 1279 Binder.getCallingUid())) { 1280 // Do not allow this API to be called on API version 31+, it should only be 1281 // called on old apps using this Binder call directly. 1282 throw new SecurityException("This method can only be used for applications " 1283 + "targeting API version 30 or less."); 1284 } 1285 synchronized (mLock) { 1286 return mCallsManager.getCallState(); 1287 } 1288 } finally { 1289 Log.endSession(); 1290 } 1291 } 1292 1293 /** 1294 * @see TelecomManager#getCallState() 1295 */ 1296 @Override 1297 public int getCallStateUsingPackage(String callingPackage, String callingFeatureId) { 1298 try { 1299 Log.startSession("TSI.getCallStateUsingPackage"); 1300 1301 // ensure the callingPackage is not spoofed 1302 // skip check for privileged UIDs and throw SE if package does not match records 1303 if (!isPrivilegedUid(callingPackage) 1304 && !callingUidMatchesPackageManagerRecords(callingPackage)) { 1305 EventLog.writeEvent(0x534e4554, "236813210", Binder.getCallingUid(), 1306 "getCallStateUsingPackage"); 1307 Log.i(this, 1308 "getCallStateUsingPackage: packageName does not match records for " 1309 + "callingPackage=[%s], callingUid=[%d]", 1310 callingPackage, Binder.getCallingUid()); 1311 throw new SecurityException(String.format("getCallStateUsingPackage: " 1312 + "enforceCallingPackage: callingPackage=[%s], callingUid=[%d]", 1313 callingPackage, Binder.getCallingUid())); 1314 } 1315 1316 if (CompatChanges.isChangeEnabled( 1317 TelecomManager.ENABLE_GET_CALL_STATE_PERMISSION_PROTECTION, callingPackage, 1318 Binder.getCallingUserHandle())) { 1319 // Bypass canReadPhoneState check if this is being called from SHELL UID 1320 if (Binder.getCallingUid() != Process.SHELL_UID && !canReadPhoneState( 1321 callingPackage, callingFeatureId, "getCallState")) { 1322 throw new SecurityException("getCallState API requires READ_PHONE_STATE" 1323 + " for API version 31+"); 1324 } 1325 } 1326 synchronized (mLock) { 1327 return mCallsManager.getCallState(); 1328 } 1329 } finally { 1330 Log.endSession(); 1331 } 1332 } 1333 1334 private boolean isPrivilegedUid(String callingPackage) { 1335 int callingUid = Binder.getCallingUid(); 1336 boolean isPrivileged = false; 1337 switch (callingUid) { 1338 case Process.ROOT_UID: 1339 case Process.SYSTEM_UID: 1340 case Process.SHELL_UID: 1341 isPrivileged = true; 1342 break; 1343 } 1344 return isPrivileged; 1345 } 1346 1347 /** 1348 * @see android.telecom.TelecomManager#endCall 1349 */ 1350 @Override 1351 public boolean endCall(String callingPackage) { 1352 try { 1353 Log.startSession("TSI.eC", Log.getPackageAbbreviation(callingPackage)); 1354 synchronized (mLock) { 1355 if (!enforceAnswerCallPermission(callingPackage, Binder.getCallingUid())) { 1356 throw new SecurityException("requires ANSWER_PHONE_CALLS permission"); 1357 } 1358 1359 long token = Binder.clearCallingIdentity(); 1360 try { 1361 return endCallInternal(callingPackage); 1362 } finally { 1363 Binder.restoreCallingIdentity(token); 1364 } 1365 } 1366 } finally { 1367 Log.endSession(); 1368 } 1369 } 1370 1371 /** 1372 * @see android.telecom.TelecomManager#acceptRingingCall 1373 */ 1374 @Override 1375 public void acceptRingingCall(String packageName) { 1376 try { 1377 Log.startSession("TSI.aRC", Log.getPackageAbbreviation(packageName)); 1378 synchronized (mLock) { 1379 if (!enforceAnswerCallPermission(packageName, Binder.getCallingUid())) return; 1380 1381 long token = Binder.clearCallingIdentity(); 1382 try { 1383 acceptRingingCallInternal(DEFAULT_VIDEO_STATE, packageName); 1384 } finally { 1385 Binder.restoreCallingIdentity(token); 1386 } 1387 } 1388 } finally { 1389 Log.endSession(); 1390 } 1391 } 1392 1393 /** 1394 * @see android.telecom.TelecomManager#acceptRingingCall(int) 1395 */ 1396 @Override 1397 public void acceptRingingCallWithVideoState(String packageName, int videoState) { 1398 try { 1399 Log.startSession("TSI.aRCWVS", Log.getPackageAbbreviation(packageName)); 1400 synchronized (mLock) { 1401 if (!enforceAnswerCallPermission(packageName, Binder.getCallingUid())) return; 1402 1403 long token = Binder.clearCallingIdentity(); 1404 try { 1405 acceptRingingCallInternal(videoState, packageName); 1406 } finally { 1407 Binder.restoreCallingIdentity(token); 1408 } 1409 } 1410 } finally { 1411 Log.endSession(); 1412 } 1413 } 1414 1415 /** 1416 * @see android.telecom.TelecomManager#showInCallScreen 1417 */ 1418 @Override 1419 public void showInCallScreen(boolean showDialpad, String callingPackage, 1420 String callingFeatureId) { 1421 try { 1422 Log.startSession("TSI.sICS", Log.getPackageAbbreviation(callingPackage)); 1423 if (!canReadPhoneState(callingPackage, callingFeatureId, "showInCallScreen")) { 1424 return; 1425 } 1426 1427 synchronized (mLock) { 1428 1429 UserHandle callingUser = Binder.getCallingUserHandle(); 1430 long token = Binder.clearCallingIdentity(); 1431 try { 1432 mCallsManager.getInCallController().bringToForeground(showDialpad, callingUser); 1433 } finally { 1434 Binder.restoreCallingIdentity(token); 1435 } 1436 } 1437 } finally { 1438 Log.endSession(); 1439 } 1440 } 1441 1442 /** 1443 * @see android.telecom.TelecomManager#cancelMissedCallsNotification 1444 */ 1445 @Override 1446 public void cancelMissedCallsNotification(String callingPackage) { 1447 try { 1448 Log.startSession("TSI.cMCN", Log.getPackageAbbreviation(callingPackage)); 1449 synchronized (mLock) { 1450 enforcePermissionOrPrivilegedDialer(MODIFY_PHONE_STATE, callingPackage); 1451 UserHandle userHandle = Binder.getCallingUserHandle(); 1452 long token = Binder.clearCallingIdentity(); 1453 try { 1454 mCallsManager.getMissedCallNotifier().clearMissedCalls(userHandle); 1455 } finally { 1456 Binder.restoreCallingIdentity(token); 1457 } 1458 } 1459 } finally { 1460 Log.endSession(); 1461 } 1462 } 1463 1464 /** 1465 * @see android.telecom.TelecomManager#handleMmi 1466 */ 1467 @Override 1468 public boolean handlePinMmi(String dialString, String callingPackage) { 1469 try { 1470 Log.startSession("TSI.hPM", Log.getPackageAbbreviation(callingPackage)); 1471 enforcePermissionOrPrivilegedDialer(MODIFY_PHONE_STATE, callingPackage); 1472 1473 // Switch identity so that TelephonyManager checks Telecom's permissions 1474 // instead. 1475 long token = Binder.clearCallingIdentity(); 1476 boolean retval = false; 1477 try { 1478 retval = getTelephonyManager( 1479 SubscriptionManager.getDefaultVoiceSubscriptionId()) 1480 .handlePinMmi(dialString); 1481 } finally { 1482 Binder.restoreCallingIdentity(token); 1483 } 1484 1485 return retval; 1486 } finally { 1487 Log.endSession(); 1488 } 1489 } 1490 1491 /** 1492 * @see android.telecom.TelecomManager#handleMmi 1493 */ 1494 @Override 1495 public boolean handlePinMmiForPhoneAccount(PhoneAccountHandle accountHandle, 1496 String dialString, String callingPackage) { 1497 try { 1498 Log.startSession("TSI.hPMFPA", Log.getPackageAbbreviation(callingPackage)); 1499 1500 enforcePermissionOrPrivilegedDialer(MODIFY_PHONE_STATE, callingPackage); 1501 UserHandle callingUserHandle = Binder.getCallingUserHandle(); 1502 synchronized (mLock) { 1503 if (!isPhoneAccountHandleVisibleToCallingUser(accountHandle, 1504 callingUserHandle)) { 1505 Log.d(this, "%s is not visible for the calling user [hMMI]", 1506 accountHandle); 1507 return false; 1508 } 1509 } 1510 1511 // Switch identity so that TelephonyManager checks Telecom's permissions 1512 // instead. 1513 long token = Binder.clearCallingIdentity(); 1514 boolean retval = false; 1515 int subId; 1516 try { 1517 synchronized (mLock) { 1518 subId = mPhoneAccountRegistrar.getSubscriptionIdForPhoneAccount( 1519 accountHandle); 1520 } 1521 try { 1522 retval = getTelephonyManager(subId) 1523 .handlePinMmiForSubscriber(subId, dialString); 1524 } catch (UnsupportedOperationException uoe) { 1525 Log.w(this, "handlePinMmiForPhoneAccount: no telephony"); 1526 retval = false; 1527 } 1528 } finally { 1529 Binder.restoreCallingIdentity(token); 1530 } 1531 return retval; 1532 } finally { 1533 Log.endSession(); 1534 } 1535 } 1536 1537 /** 1538 * @see android.telecom.TelecomManager#getAdnUriForPhoneAccount 1539 */ 1540 @Override 1541 public Uri getAdnUriForPhoneAccount(PhoneAccountHandle accountHandle, 1542 String callingPackage) { 1543 try { 1544 Log.startSession("TSI.aAUFPA", Log.getPackageAbbreviation(callingPackage)); 1545 enforcePermissionOrPrivilegedDialer(MODIFY_PHONE_STATE, callingPackage); 1546 synchronized (mLock) { 1547 if (!isPhoneAccountHandleVisibleToCallingUser(accountHandle, 1548 Binder.getCallingUserHandle())) { 1549 Log.d(this, "%s is not visible for the calling user [gA4PA]", 1550 accountHandle); 1551 return null; 1552 } 1553 } 1554 // Switch identity so that TelephonyManager checks Telecom's permissions 1555 // instead. 1556 long token = Binder.clearCallingIdentity(); 1557 String retval = "content://icc/adn/"; 1558 try { 1559 long subId = mPhoneAccountRegistrar 1560 .getSubscriptionIdForPhoneAccount(accountHandle); 1561 retval = retval + "subId/" + subId; 1562 } finally { 1563 Binder.restoreCallingIdentity(token); 1564 } 1565 1566 return Uri.parse(retval); 1567 } finally { 1568 Log.endSession(); 1569 } 1570 } 1571 1572 /** 1573 * @see android.telecom.TelecomManager#isTtySupported 1574 */ 1575 @Override 1576 public boolean isTtySupported(String callingPackage, String callingFeatureId) { 1577 try { 1578 Log.startSession("TSI.iTS", Log.getPackageAbbreviation(callingPackage)); 1579 if (!canReadPhoneState(callingPackage, callingFeatureId, "isTtySupported")) { 1580 throw new SecurityException("Only default dialer or an app with" + 1581 "READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE can call this api"); 1582 } 1583 1584 synchronized (mLock) { 1585 return mCallsManager.isTtySupported(); 1586 } 1587 } finally { 1588 Log.endSession(); 1589 } 1590 } 1591 1592 /** 1593 * @see android.telecom.TelecomManager#getCurrentTtyMode 1594 */ 1595 @Override 1596 public int getCurrentTtyMode(String callingPackage, String callingFeatureId) { 1597 try { 1598 Log.startSession("TSI.gCTM", Log.getPackageAbbreviation(callingPackage)); 1599 if (!canReadPhoneState(callingPackage, callingFeatureId, "getCurrentTtyMode")) { 1600 return TelecomManager.TTY_MODE_OFF; 1601 } 1602 1603 synchronized (mLock) { 1604 return mCallsManager.getCurrentTtyMode(); 1605 } 1606 } finally { 1607 Log.endSession(); 1608 } 1609 } 1610 1611 /** 1612 * @see android.telecom.TelecomManager#addNewIncomingCall 1613 */ 1614 @Override 1615 public void addNewIncomingCall(PhoneAccountHandle phoneAccountHandle, Bundle extras, 1616 String callingPackage) { 1617 try { 1618 Log.startSession("TSI.aNIC", Log.getPackageAbbreviation(callingPackage)); 1619 synchronized (mLock) { 1620 Log.i(this, "Adding new incoming call with phoneAccountHandle %s", 1621 phoneAccountHandle); 1622 if (phoneAccountHandle != null && 1623 phoneAccountHandle.getComponentName() != null) { 1624 if (isCallerSimCallManager(phoneAccountHandle) 1625 && TelephonyUtil.isPstnComponentName( 1626 phoneAccountHandle.getComponentName())) { 1627 Log.v(this, "Allowing call manager to add incoming call with PSTN" + 1628 " handle"); 1629 } else { 1630 mAppOpsManager.checkPackage( 1631 Binder.getCallingUid(), 1632 phoneAccountHandle.getComponentName().getPackageName()); 1633 // Make sure it doesn't cross the UserHandle boundary 1634 enforceUserHandleMatchesCaller(phoneAccountHandle); 1635 enforcePhoneAccountIsRegisteredEnabled(phoneAccountHandle, 1636 phoneAccountHandle.getUserHandle()); 1637 if (isSelfManagedConnectionService(phoneAccountHandle)) { 1638 // Self-managed phone account, ensure it has MANAGE_OWN_CALLS. 1639 mContext.enforceCallingOrSelfPermission( 1640 android.Manifest.permission.MANAGE_OWN_CALLS, 1641 "Self-managed phone accounts must have MANAGE_OWN_CALLS " + 1642 "permission."); 1643 1644 // Self-managed ConnectionServices can ONLY add new incoming calls 1645 // using their own PhoneAccounts. The checkPackage(..) app opps 1646 // check above ensures this. 1647 } 1648 } 1649 long token = Binder.clearCallingIdentity(); 1650 try { 1651 Intent intent = new Intent(TelecomManager.ACTION_INCOMING_CALL); 1652 intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, 1653 phoneAccountHandle); 1654 intent.putExtra(CallIntentProcessor.KEY_IS_INCOMING_CALL, true); 1655 if (extras != null) { 1656 extras.setDefusable(true); 1657 intent.putExtra(TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, extras); 1658 } 1659 mCallIntentProcessorAdapter.processIncomingCallIntent( 1660 mCallsManager, intent); 1661 if (mFeatureFlags.earlyBindingToIncallService()) { 1662 PhoneAccount account = 1663 mPhoneAccountRegistrar.getPhoneAccountUnchecked( 1664 phoneAccountHandle); 1665 Bundle accountExtra = 1666 account == null ? new Bundle() : account.getExtras(); 1667 PackageManager packageManager = mContext.getPackageManager(); 1668 // Start binding to InCallServices for wearable calls that do not 1669 // require call filtering. This is to wake up default dialer earlier 1670 // to mitigate InCallService binding latency. 1671 if (packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH) 1672 && accountExtra != null && accountExtra.getBoolean( 1673 PhoneAccount.EXTRA_SKIP_CALL_FILTERING, 1674 false)) { 1675 if (mFeatureFlags.separatelyBindToBtIncallService()) { 1676 mCallsManager.getInCallController().bindToBTService( 1677 null, null); 1678 } 1679 // Should be able to run this as is even if above flag is 1680 // enabled (BT binding should be skipped automatically). 1681 mCallsManager.getInCallController().bindToServices(null); 1682 } 1683 } 1684 } finally { 1685 Binder.restoreCallingIdentity(token); 1686 } 1687 } else { 1688 Log.w(this, "Null phoneAccountHandle. Ignoring request to add new" + 1689 " incoming call"); 1690 } 1691 } 1692 } finally { 1693 Log.endSession(); 1694 } 1695 } 1696 1697 /** 1698 * @see android.telecom.TelecomManager#addNewIncomingConference 1699 */ 1700 @Override 1701 public void addNewIncomingConference(PhoneAccountHandle phoneAccountHandle, Bundle extras, 1702 String callingPackage) { 1703 try { 1704 Log.startSession("TSI.aNIC", Log.getPackageAbbreviation(callingPackage)); 1705 synchronized (mLock) { 1706 Log.i(this, "Adding new incoming conference with phoneAccountHandle %s", 1707 phoneAccountHandle); 1708 if (phoneAccountHandle != null && 1709 phoneAccountHandle.getComponentName() != null) { 1710 if (isCallerSimCallManager(phoneAccountHandle) 1711 && TelephonyUtil.isPstnComponentName( 1712 phoneAccountHandle.getComponentName())) { 1713 Log.v(this, "Allowing call manager to add incoming conference" + 1714 " with PSTN handle"); 1715 } else { 1716 mAppOpsManager.checkPackage( 1717 Binder.getCallingUid(), 1718 phoneAccountHandle.getComponentName().getPackageName()); 1719 // Make sure it doesn't cross the UserHandle boundary 1720 enforceUserHandleMatchesCaller(phoneAccountHandle); 1721 enforcePhoneAccountIsRegisteredEnabled(phoneAccountHandle, 1722 Binder.getCallingUserHandle()); 1723 if (isSelfManagedConnectionService(phoneAccountHandle)) { 1724 throw new SecurityException( 1725 "Self-Managed ConnectionServices cannot add " 1726 + "adhoc conference calls"); 1727 } 1728 } 1729 long token = Binder.clearCallingIdentity(); 1730 try { 1731 mCallsManager.processIncomingConference( 1732 phoneAccountHandle, extras); 1733 } finally { 1734 Binder.restoreCallingIdentity(token); 1735 } 1736 } else { 1737 Log.w(this, "Null phoneAccountHandle. Ignoring request to add new" + 1738 " incoming conference"); 1739 } 1740 } 1741 } finally { 1742 Log.endSession(); 1743 } 1744 } 1745 1746 1747 /** 1748 * @see android.telecom.TelecomManager#acceptHandover 1749 */ 1750 @Override 1751 public void acceptHandover(Uri srcAddr, int videoState, PhoneAccountHandle destAcct, 1752 String callingPackage) { 1753 try { 1754 Log.startSession("TSI.aHO", Log.getPackageAbbreviation(callingPackage)); 1755 synchronized (mLock) { 1756 Log.i(this, "acceptHandover; srcAddr=%s, videoState=%s, dest=%s", 1757 Log.pii(srcAddr), VideoProfile.videoStateToString(videoState), 1758 destAcct); 1759 1760 if (destAcct != null && destAcct.getComponentName() != null) { 1761 mAppOpsManager.checkPackage( 1762 Binder.getCallingUid(), 1763 destAcct.getComponentName().getPackageName()); 1764 enforceUserHandleMatchesCaller(destAcct); 1765 enforcePhoneAccountIsRegisteredEnabled(destAcct, 1766 Binder.getCallingUserHandle()); 1767 if (isSelfManagedConnectionService(destAcct)) { 1768 // Self-managed phone account, ensure it has MANAGE_OWN_CALLS. 1769 mContext.enforceCallingOrSelfPermission( 1770 android.Manifest.permission.MANAGE_OWN_CALLS, 1771 "Self-managed phone accounts must have MANAGE_OWN_CALLS " + 1772 "permission."); 1773 } 1774 if (!enforceAcceptHandoverPermission( 1775 destAcct.getComponentName().getPackageName(), 1776 Binder.getCallingUid())) { 1777 throw new SecurityException("App must be granted runtime " 1778 + "ACCEPT_HANDOVER permission."); 1779 } 1780 1781 long token = Binder.clearCallingIdentity(); 1782 try { 1783 mCallsManager.acceptHandover(srcAddr, videoState, destAcct); 1784 } finally { 1785 Binder.restoreCallingIdentity(token); 1786 } 1787 } else { 1788 Log.w(this, "Null phoneAccountHandle. Ignoring request " + 1789 "to handover the call"); 1790 } 1791 } 1792 } finally { 1793 Log.endSession(); 1794 } 1795 } 1796 1797 /** 1798 * @see android.telecom.TelecomManager#addNewUnknownCall 1799 */ 1800 @Override 1801 public void addNewUnknownCall(PhoneAccountHandle phoneAccountHandle, Bundle extras) { 1802 try { 1803 Log.startSession("TSI.aNUC"); 1804 try { 1805 enforceModifyPermission( 1806 "addNewUnknownCall requires MODIFY_PHONE_STATE permission."); 1807 } catch (SecurityException e) { 1808 EventLog.writeEvent(0x534e4554, "62347125", Binder.getCallingUid(), 1809 "addNewUnknownCall"); 1810 throw e; 1811 } 1812 1813 synchronized (mLock) { 1814 if (phoneAccountHandle != null && 1815 phoneAccountHandle.getComponentName() != null) { 1816 mAppOpsManager.checkPackage( 1817 Binder.getCallingUid(), 1818 phoneAccountHandle.getComponentName().getPackageName()); 1819 1820 // Make sure it doesn't cross the UserHandle boundary 1821 enforceUserHandleMatchesCaller(phoneAccountHandle); 1822 enforcePhoneAccountIsRegisteredEnabled(phoneAccountHandle, 1823 Binder.getCallingUserHandle()); 1824 long token = Binder.clearCallingIdentity(); 1825 1826 try { 1827 Intent intent = new Intent(TelecomManager.ACTION_NEW_UNKNOWN_CALL); 1828 if (extras != null) { 1829 extras.setDefusable(true); 1830 intent.putExtras(extras); 1831 } 1832 intent.putExtra(CallIntentProcessor.KEY_IS_UNKNOWN_CALL, true); 1833 intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, 1834 phoneAccountHandle); 1835 mCallIntentProcessorAdapter.processUnknownCallIntent(mCallsManager, 1836 intent); 1837 } finally { 1838 Binder.restoreCallingIdentity(token); 1839 } 1840 } else { 1841 Log.i(this, 1842 "Null phoneAccountHandle or not initiated by Telephony. " + 1843 "Ignoring request to add new unknown call."); 1844 } 1845 } 1846 } finally { 1847 Log.endSession(); 1848 } 1849 } 1850 1851 /** 1852 * @see android.telecom.TelecomManager#startConference. 1853 */ 1854 @Override 1855 public void startConference(List<Uri> participants, Bundle extras, 1856 String callingPackage) { 1857 try { 1858 Log.startSession("TSI.sC", Log.getPackageAbbreviation(callingPackage)); 1859 if (!canCallPhone(callingPackage, "startConference")) { 1860 throw new SecurityException("Package " + callingPackage + " is not allowed" 1861 + " to start conference call"); 1862 } 1863 // Binder is clearing the identity, so we need to keep the store the handle 1864 UserHandle currentUserHandle = Binder.getCallingUserHandle(); 1865 long token = Binder.clearCallingIdentity(); 1866 try { 1867 mCallsManager.startConference(participants, extras, callingPackage, 1868 currentUserHandle); 1869 } finally { 1870 Binder.restoreCallingIdentity(token); 1871 } 1872 } finally { 1873 Log.endSession(); 1874 } 1875 } 1876 1877 /** 1878 * @see android.telecom.TelecomManager#placeCall 1879 */ 1880 @Override 1881 public void placeCall(Uri handle, Bundle extras, String callingPackage, 1882 String callingFeatureId) { 1883 try { 1884 Log.startSession("TSI.pC", Log.getPackageAbbreviation(callingPackage)); 1885 enforceCallingPackage(callingPackage, "placeCall"); 1886 1887 PhoneAccountHandle phoneAccountHandle = null; 1888 if (extras != null) { 1889 phoneAccountHandle = extras.getParcelable( 1890 TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE); 1891 if (extras.containsKey(TelecomManager.EXTRA_IS_HANDOVER)) { 1892 // This extra is for Telecom use only so should never be passed in. 1893 extras.remove(TelecomManager.EXTRA_IS_HANDOVER); 1894 } 1895 } 1896 ComponentName phoneAccountComponentName = phoneAccountHandle != null 1897 ? phoneAccountHandle.getComponentName() : null; 1898 String phoneAccountPackageName = phoneAccountComponentName != null 1899 ? phoneAccountComponentName.getPackageName() : null; 1900 boolean isCallerOwnerOfPhoneAccount = 1901 callingPackage.equals(phoneAccountPackageName); 1902 boolean isSelfManagedPhoneAccount = 1903 isSelfManagedConnectionService(phoneAccountHandle); 1904 // Ensure the app's calling package matches the PhoneAccount package name before 1905 // checking self-managed status so that we do not leak installed package 1906 // information. 1907 boolean isSelfManagedRequest = isCallerOwnerOfPhoneAccount && 1908 isSelfManagedPhoneAccount; 1909 if (isSelfManagedRequest) { 1910 // The package name of the caller matches the package name of the 1911 // PhoneAccountHandle, so ensure the app has MANAGE_OWN_CALLS permission if 1912 // self-managed. 1913 mContext.enforceCallingOrSelfPermission( 1914 Manifest.permission.MANAGE_OWN_CALLS, 1915 "Self-managed ConnectionServices require MANAGE_OWN_CALLS permission."); 1916 } else if (!canCallPhone(callingPackage, callingFeatureId, 1917 "CALL_PHONE permission required to place calls.")) { 1918 // not self-managed, so CALL_PHONE is required. 1919 mAnomalyReporter.reportAnomaly(PLACE_CALL_SECURITY_EXCEPTION_ERROR_UUID, 1920 PLACE_CALL_SECURITY_EXCEPTION_ERROR_MSG); 1921 throw new SecurityException( 1922 "CALL_PHONE permission required to place calls."); 1923 } 1924 1925 // An application can not place a call with a self-managed PhoneAccount that 1926 // they do not own. If this is the case (and the app has CALL_PHONE permission), 1927 // remove the PhoneAccount from the request and place the call as if it was a 1928 // managed call request with no PhoneAccount specified. 1929 if (!isCallerOwnerOfPhoneAccount && isSelfManagedPhoneAccount) { 1930 // extras can not be null if isSelfManagedPhoneAccount is true 1931 extras.remove(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE); 1932 } 1933 1934 // Note: we can still get here for the default/system dialer, even if the Phone 1935 // permission is turned off. This is because the default/system dialer is always 1936 // allowed to attempt to place a call (regardless of permission state), in case 1937 // it turns out to be an emergency call. If the permission is denied and the 1938 // call is being made to a non-emergency number, the call will be denied later on 1939 // by {@link UserCallIntentProcessor}. 1940 1941 final boolean hasCallAppOp = mAppOpsManager.noteOp(AppOpsManager.OP_CALL_PHONE, 1942 Binder.getCallingUid(), callingPackage, callingFeatureId, null) 1943 == AppOpsManager.MODE_ALLOWED; 1944 1945 final boolean hasCallPermission = mContext.checkCallingOrSelfPermission(CALL_PHONE) 1946 == PackageManager.PERMISSION_GRANTED; 1947 // The Emergency Dialer has call privileged permission and uses this to place 1948 // emergency calls. We ensure permission checks in 1949 // NewOutgoingCallIntentBroadcaster#process pass by sending this to 1950 // Telecom as an ACTION_CALL_PRIVILEGED intent (which makes sense since the 1951 // com.android.phone process has that permission). 1952 final boolean hasCallPrivilegedPermission = mContext.checkCallingOrSelfPermission( 1953 CALL_PRIVILEGED) == PackageManager.PERMISSION_GRANTED; 1954 1955 synchronized (mLock) { 1956 final UserHandle userHandle = Binder.getCallingUserHandle(); 1957 long token = Binder.clearCallingIdentity(); 1958 try { 1959 final Intent intent = new Intent(hasCallPrivilegedPermission ? 1960 Intent.ACTION_CALL_PRIVILEGED : Intent.ACTION_CALL, handle); 1961 if (extras != null) { 1962 extras.setDefusable(true); 1963 intent.putExtras(extras); 1964 } 1965 mUserCallIntentProcessorFactory.create(mContext, userHandle) 1966 .processIntent(intent, callingPackage, isSelfManagedRequest, 1967 (hasCallAppOp && hasCallPermission) 1968 || hasCallPrivilegedPermission, 1969 true /* isLocalInvocation */); 1970 } finally { 1971 Binder.restoreCallingIdentity(token); 1972 } 1973 } 1974 } finally { 1975 Log.endSession(); 1976 } 1977 } 1978 1979 /** 1980 * @see android.telecom.TelecomManager#enablePhoneAccount 1981 */ 1982 @Override 1983 public boolean enablePhoneAccount(PhoneAccountHandle accountHandle, boolean isEnabled) { 1984 try { 1985 Log.startSession("TSI.ePA"); 1986 enforceModifyPermission(); 1987 synchronized (mLock) { 1988 long token = Binder.clearCallingIdentity(); 1989 try { 1990 // enable/disable phone account 1991 return mPhoneAccountRegistrar.enablePhoneAccount(accountHandle, isEnabled); 1992 } finally { 1993 Binder.restoreCallingIdentity(token); 1994 } 1995 } 1996 } finally { 1997 Log.endSession(); 1998 } 1999 } 2000 2001 @Override 2002 public boolean setDefaultDialer(String packageName) { 2003 try { 2004 Log.startSession("TSI.sDD"); 2005 enforcePermission(MODIFY_PHONE_STATE); 2006 enforcePermission(WRITE_SECURE_SETTINGS); 2007 synchronized (mLock) { 2008 int callerUserId = UserHandle.getCallingUserId(); 2009 long token = Binder.clearCallingIdentity(); 2010 try { 2011 return mDefaultDialerCache.setDefaultDialer(packageName, 2012 callerUserId); 2013 } finally { 2014 Binder.restoreCallingIdentity(token); 2015 } 2016 } 2017 } finally { 2018 Log.endSession(); 2019 } 2020 } 2021 2022 @Override 2023 public void stopBlockSuppression() { 2024 try { 2025 Log.startSession("TSI.sBS"); 2026 enforceModifyPermission(); 2027 if (Binder.getCallingUid() != Process.SHELL_UID 2028 && Binder.getCallingUid() != Process.ROOT_UID) { 2029 throw new SecurityException("Shell-only API."); 2030 } 2031 synchronized (mLock) { 2032 long token = Binder.clearCallingIdentity(); 2033 try { 2034 if (mBlockedNumbersManager != null) { 2035 mBlockedNumbersManager.endBlockSuppression(); 2036 } else { 2037 BlockedNumberContract.SystemContract.endBlockSuppression(mContext); 2038 } 2039 } finally { 2040 Binder.restoreCallingIdentity(token); 2041 } 2042 } 2043 } finally { 2044 Log.endSession(); 2045 } 2046 } 2047 2048 @Override 2049 public TelecomAnalytics dumpCallAnalytics() { 2050 try { 2051 Log.startSession("TSI.dCA"); 2052 enforcePermission(DUMP); 2053 return Analytics.dumpToParcelableAnalytics(); 2054 } finally { 2055 Log.endSession(); 2056 } 2057 } 2058 2059 /** 2060 * Dumps the current state of the TelecomService. Used when generating problem 2061 * reports. 2062 * 2063 * @param fd The file descriptor. 2064 * @param writer The print writer to dump the state to. 2065 * @param args Optional dump arguments. 2066 */ 2067 @Override 2068 protected void dump(FileDescriptor fd, final PrintWriter writer, String[] args) { 2069 if (mContext.checkCallingOrSelfPermission( 2070 android.Manifest.permission.DUMP) 2071 != PackageManager.PERMISSION_GRANTED) { 2072 writer.println("Permission Denial: can't dump TelecomService " + 2073 "from from pid=" + Binder.getCallingPid() + ", uid=" + 2074 Binder.getCallingUid()); 2075 return; 2076 } 2077 2078 2079 if (args != null && args.length > 0 && Analytics.ANALYTICS_DUMPSYS_ARG.equals( 2080 args[0])) { 2081 long token = Binder.clearCallingIdentity(); 2082 try { 2083 Analytics.dumpToEncodedProto(mContext, writer, args); 2084 } finally { 2085 Binder.restoreCallingIdentity(token); 2086 } 2087 return; 2088 } 2089 2090 boolean isTimeLineView = 2091 (args != null && args.length > 0 && TIME_LINE_ARG.equalsIgnoreCase(args[0])); 2092 2093 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); 2094 if (mCallsManager != null) { 2095 pw.println("CallsManager: "); 2096 pw.increaseIndent(); 2097 mCallsManager.dump(pw, args); 2098 pw.decreaseIndent(); 2099 2100 pw.println("PhoneAccountRegistrar: "); 2101 pw.increaseIndent(); 2102 mPhoneAccountRegistrar.dump(pw); 2103 pw.decreaseIndent(); 2104 2105 pw.println("Analytics:"); 2106 pw.increaseIndent(); 2107 Analytics.dump(pw); 2108 pw.decreaseIndent(); 2109 2110 pw.println("Flag Configurations: "); 2111 pw.increaseIndent(); 2112 reflectAndPrintFlagConfigs(pw); 2113 pw.decreaseIndent(); 2114 2115 pw.println("TransactionManager: "); 2116 pw.increaseIndent(); 2117 TransactionManager.getInstance().dump(pw); 2118 pw.decreaseIndent(); 2119 } 2120 if (isTimeLineView) { 2121 Log.dumpEventsTimeline(pw); 2122 } else { 2123 Log.dumpEvents(pw); 2124 } 2125 } 2126 2127 @Override 2128 public int handleShellCommand(@NonNull ParcelFileDescriptor in, 2129 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err, 2130 @NonNull String[] args) { 2131 return new TelecomShellCommand(this, mContext).exec(this, 2132 in.getFileDescriptor(), out.getFileDescriptor(), err.getFileDescriptor(), args); 2133 } 2134 2135 /** 2136 * Print all feature flag configurations that Telecom is using for debugging purposes. 2137 */ 2138 private void reflectAndPrintFlagConfigs(IndentingPrintWriter pw) { 2139 2140 try { 2141 // Look away, a forbidden technique (reflection) is being used to allow us to get 2142 // all flag configs without having to add them manually to this method. 2143 Method[] methods = FeatureFlags.class.getMethods(); 2144 int maxLength = Arrays.stream(methods) 2145 .map(Method::getName) 2146 .map(String::length) 2147 .max(Integer::compare) 2148 .get(); 2149 String format = "\t%s: %-" + maxLength + "s %s"; 2150 2151 if (methods.length == 0) { 2152 pw.println("NONE"); 2153 return; 2154 } 2155 2156 for (Method m : methods) { 2157 String flagEnabled = (Boolean) m.invoke(mFeatureFlags) ? "[✅]": "[❌]"; 2158 String methodName = m.getName(); 2159 String camelCaseName = methodName.replaceAll("([a-z])([A-Z]+)", "$1_$2") 2160 .toLowerCase(Locale.US); 2161 pw.println(String.format(format, flagEnabled, methodName, camelCaseName)); 2162 } 2163 } catch (Exception e) { 2164 pw.println("[ERROR]"); 2165 } 2166 2167 } 2168 2169 /** 2170 * @see android.telecom.TelecomManager#createManageBlockedNumbersIntent 2171 */ 2172 @Override 2173 public Intent createManageBlockedNumbersIntent(String callingPackage) { 2174 try { 2175 Log.startSession("TSI.cMBNI", Log.getPackageAbbreviation(callingPackage)); 2176 return BlockedNumbersActivity.getIntentForStartingActivity(); 2177 } finally { 2178 Log.endSession(); 2179 } 2180 } 2181 2182 2183 @Override 2184 public Intent createLaunchEmergencyDialerIntent(String number) { 2185 String packageName = mContext.getApplicationContext().getString( 2186 com.android.internal.R.string.config_emergency_dialer_package); 2187 Intent intent = new Intent(Intent.ACTION_DIAL_EMERGENCY) 2188 .setPackage(packageName); 2189 ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0 /* flags*/); 2190 if (resolveInfo == null) { 2191 // No matching activity from config, fallback to default platform implementation 2192 intent.setPackage(null); 2193 } 2194 if (!TextUtils.isEmpty(number) && TextUtils.isDigitsOnly(number)) { 2195 intent.setData(Uri.parse("tel:" + number)); 2196 } 2197 return intent; 2198 } 2199 2200 /** 2201 * @see android.telecom.TelecomManager#isIncomingCallPermitted(PhoneAccountHandle) 2202 */ 2203 @Override 2204 public boolean isIncomingCallPermitted(PhoneAccountHandle phoneAccountHandle, 2205 String callingPackage) { 2206 Log.startSession("TSI.iICP", Log.getPackageAbbreviation(callingPackage)); 2207 try { 2208 enforceCallingPackage(callingPackage, "isIncomingCallPermitted"); 2209 enforcePhoneAccountHandleMatchesCaller(phoneAccountHandle, callingPackage); 2210 enforcePermission(android.Manifest.permission.MANAGE_OWN_CALLS); 2211 enforceUserHandleMatchesCaller(phoneAccountHandle); 2212 synchronized (mLock) { 2213 long token = Binder.clearCallingIdentity(); 2214 try { 2215 return mCallsManager.isIncomingCallPermitted(phoneAccountHandle); 2216 } finally { 2217 Binder.restoreCallingIdentity(token); 2218 } 2219 } 2220 } finally { 2221 Log.endSession(); 2222 } 2223 } 2224 2225 /** 2226 * @see android.telecom.TelecomManager#isOutgoingCallPermitted(PhoneAccountHandle) 2227 */ 2228 @Override 2229 public boolean isOutgoingCallPermitted(PhoneAccountHandle phoneAccountHandle, 2230 String callingPackage) { 2231 Log.startSession("TSI.iOCP", Log.getPackageAbbreviation(callingPackage)); 2232 try { 2233 enforceCallingPackage(callingPackage, "isOutgoingCallPermitted"); 2234 enforcePhoneAccountHandleMatchesCaller(phoneAccountHandle, callingPackage); 2235 enforcePermission(android.Manifest.permission.MANAGE_OWN_CALLS); 2236 enforceUserHandleMatchesCaller(phoneAccountHandle); 2237 synchronized (mLock) { 2238 long token = Binder.clearCallingIdentity(); 2239 try { 2240 return mCallsManager.isOutgoingCallPermitted(phoneAccountHandle); 2241 } finally { 2242 Binder.restoreCallingIdentity(token); 2243 } 2244 } 2245 } finally { 2246 Log.endSession(); 2247 } 2248 } 2249 2250 /** 2251 * Blocks until all Telecom handlers have completed their current work. 2252 * 2253 * See {@link com.android.commands.telecom.Telecom}. 2254 */ 2255 @Override 2256 public void waitOnHandlers() { 2257 try { 2258 Log.startSession("TSI.wOH"); 2259 enforceModifyPermission(); 2260 synchronized (mLock) { 2261 long token = Binder.clearCallingIdentity(); 2262 try { 2263 Log.i(this, "waitOnHandlers"); 2264 mCallsManager.waitOnHandlers(); 2265 } finally { 2266 Binder.restoreCallingIdentity(token); 2267 } 2268 } 2269 } finally { 2270 Log.endSession(); 2271 } 2272 } 2273 2274 @Override 2275 public void setTestEmergencyPhoneAccountPackageNameFilter(String packageName) { 2276 try { 2277 Log.startSession("TSI.sTPAPNF"); 2278 enforceModifyPermission(); 2279 enforceShellOnly(Binder.getCallingUid(), 2280 "setTestEmergencyPhoneAccountPackageNameFilter"); 2281 synchronized (mLock) { 2282 long token = Binder.clearCallingIdentity(); 2283 try { 2284 mPhoneAccountRegistrar.setTestPhoneAccountPackageNameFilter(packageName); 2285 } finally { 2286 Binder.restoreCallingIdentity(token); 2287 } 2288 } 2289 } finally { 2290 Log.endSession(); 2291 } 2292 } 2293 2294 /** 2295 * See {@link TelecomManager#isInEmergencyCall()} 2296 */ 2297 @Override 2298 public boolean isInEmergencyCall() { 2299 try { 2300 Log.startSession("TSI.iIEC"); 2301 enforceModifyPermission(); 2302 synchronized (mLock) { 2303 long token = Binder.clearCallingIdentity(); 2304 try { 2305 boolean isInEmergencyCall = mCallsManager.isInEmergencyCall(); 2306 Log.i(this, "isInEmergencyCall: %b", isInEmergencyCall); 2307 return isInEmergencyCall; 2308 } finally { 2309 Binder.restoreCallingIdentity(token); 2310 } 2311 } 2312 } finally { 2313 Log.endSession(); 2314 } 2315 } 2316 2317 /** 2318 * See {@link TelecomManager#handleCallIntent(Intent, String)} 2319 */ 2320 @Override 2321 public void handleCallIntent(Intent intent, String callingPackage) { 2322 try { 2323 Log.startSession("TSI.hCI"); 2324 synchronized (mLock) { 2325 mContext.enforceCallingOrSelfPermission(PERMISSION_HANDLE_CALL_INTENT, 2326 "handleCallIntent is for internal use only."); 2327 2328 long token = Binder.clearCallingIdentity(); 2329 try { 2330 Log.i(this, "handleCallIntent: handling call intent"); 2331 mCallIntentProcessorAdapter.processOutgoingCallIntent(mContext, 2332 mCallsManager, intent, callingPackage, mFeatureFlags); 2333 } finally { 2334 Binder.restoreCallingIdentity(token); 2335 } 2336 } 2337 } finally { 2338 Log.endSession(); 2339 } 2340 } 2341 2342 /** 2343 * A method intended for use in testing to clean up any calls are ongoing. Stuck 2344 * calls during CTS cause cascading failures, so if the CTS test detects such a state, it 2345 * should call this method via a shell command to clean up before moving on to the next 2346 * test. Also cleans up any pending futures related to 2347 * {@link android.telecom.CallDiagnosticService}s. 2348 */ 2349 @Override 2350 public void cleanupStuckCalls() { 2351 Log.startSession("TCI.cSC"); 2352 try { 2353 synchronized (mLock) { 2354 enforceShellOnly(Binder.getCallingUid(), "cleanupStuckCalls"); 2355 long token = Binder.clearCallingIdentity(); 2356 try { 2357 Set<UserHandle> userHandles = new HashSet<>(); 2358 for (Call call : mCallsManager.getCalls()) { 2359 // Any call that is not in a disconnect* state should be moved to the 2360 // disconnected state 2361 if (!isDisconnectingOrDisconnected(call)) { 2362 mCallsManager.markCallAsDisconnected( 2363 call, 2364 new DisconnectCause(DisconnectCause.OTHER, 2365 "cleaning up stuck calls")); 2366 } 2367 // ensure the call is immediately removed from CallsManager instead of 2368 // using a Future to do the work. 2369 call.cleanup(); 2370 // finally, officially remove the call from CallsManager tracking 2371 mCallsManager.markCallAsRemoved(call); 2372 userHandles.add(call.getAssociatedUser()); 2373 } 2374 for (UserHandle userHandle : userHandles) { 2375 mCallsManager.getInCallController().unbindFromServices(userHandle); 2376 } 2377 } finally { 2378 Binder.restoreCallingIdentity(token); 2379 } 2380 } 2381 } finally { 2382 Log.endSession(); 2383 } 2384 } 2385 2386 private boolean isDisconnectingOrDisconnected(Call call){ 2387 return call.getState() == CallState.DISCONNECTED 2388 || call.getState() == CallState.DISCONNECTING; 2389 } 2390 2391 /** 2392 * A method intended for test to clean up orphan {@link PhoneAccount}. An orphan 2393 * {@link PhoneAccount} is a phone account belongs to an invalid {@link UserHandle} 2394 * or a 2395 * deleted package. 2396 * 2397 * @return the number of orphan {@code PhoneAccount} deleted. 2398 */ 2399 @Override 2400 public int cleanupOrphanPhoneAccounts() { 2401 Log.startSession("TCI.cOPA"); 2402 try { 2403 synchronized (mLock) { 2404 enforceShellOnly(Binder.getCallingUid(), "cleanupOrphanPhoneAccounts"); 2405 long token = Binder.clearCallingIdentity(); 2406 try { 2407 return mPhoneAccountRegistrar.cleanupOrphanedPhoneAccounts(); 2408 } finally { 2409 Binder.restoreCallingIdentity(token); 2410 } 2411 } 2412 } finally { 2413 Log.endSession(); 2414 } 2415 } 2416 2417 /** 2418 * A method intended for use in testing to query whether a particular non-ui inCallService 2419 * is bound in a call. 2420 * @param packageName of the service to query. 2421 * @return whether it is bound or not. 2422 */ 2423 @Override 2424 public boolean isNonUiInCallServiceBound(String packageName) { 2425 Log.startSession("TCI.iNUICSB"); 2426 try { 2427 synchronized (mLock) { 2428 enforceShellOnly(Binder.getCallingUid(), "isNonUiInCallServiceBound"); 2429 if (!(mContext.checkCallingOrSelfPermission(READ_PHONE_STATE) 2430 == PackageManager.PERMISSION_GRANTED) || 2431 !(mContext.checkCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE) 2432 == PackageManager.PERMISSION_GRANTED)) { 2433 throw new SecurityException("isNonUiInCallServiceBound requires the" 2434 + " READ_PHONE_STATE or READ_PRIVILEGED_PHONE_STATE permission"); 2435 } 2436 long token = Binder.clearCallingIdentity(); 2437 try { 2438 return mCallsManager 2439 .getInCallController() 2440 .isNonUiInCallServiceBound(packageName); 2441 } finally { 2442 Binder.restoreCallingIdentity(token); 2443 } 2444 } 2445 } finally { 2446 Log.endSession(); 2447 } 2448 } 2449 2450 /** 2451 * A method intended for use in testing to reset car mode at all priorities. 2452 * 2453 * Runs during setup to avoid cascading failures from failing car mode CTS. 2454 */ 2455 @Override 2456 public void resetCarMode() { 2457 Log.startSession("TCI.rCM"); 2458 try { 2459 synchronized (mLock) { 2460 enforceShellOnly(Binder.getCallingUid(), "resetCarMode"); 2461 long token = Binder.clearCallingIdentity(); 2462 try { 2463 UiModeManager uiModeManager = 2464 mContext.getSystemService(UiModeManager.class); 2465 uiModeManager.disableCarMode(UiModeManager.DISABLE_CAR_MODE_ALL_PRIORITIES); 2466 } finally { 2467 Binder.restoreCallingIdentity(token); 2468 } 2469 } 2470 } finally { 2471 Log.endSession(); 2472 } 2473 } 2474 2475 @Override 2476 public void setTestDefaultCallRedirectionApp(String packageName) { 2477 try { 2478 Log.startSession("TSI.sTDCRA"); 2479 enforceModifyPermission(); 2480 if (!Build.IS_USERDEBUG) { 2481 throw new SecurityException("Test-only API."); 2482 } 2483 synchronized (mLock) { 2484 long token = Binder.clearCallingIdentity(); 2485 try { 2486 mCallsManager.getRoleManagerAdapter().setTestDefaultCallRedirectionApp( 2487 packageName); 2488 } finally { 2489 Binder.restoreCallingIdentity(token); 2490 } 2491 } 2492 } finally { 2493 Log.endSession(); 2494 } 2495 } 2496 2497 @Override 2498 public void setTestDefaultCallScreeningApp(String packageName) { 2499 try { 2500 Log.startSession("TSI.sTDCSA"); 2501 enforceModifyPermission(); 2502 if (!Build.IS_USERDEBUG) { 2503 throw new SecurityException("Test-only API."); 2504 } 2505 synchronized (mLock) { 2506 long token = Binder.clearCallingIdentity(); 2507 try { 2508 mCallsManager.getRoleManagerAdapter().setTestDefaultCallScreeningApp( 2509 packageName); 2510 } finally { 2511 Binder.restoreCallingIdentity(token); 2512 } 2513 } 2514 } finally { 2515 Log.endSession(); 2516 } 2517 } 2518 2519 @Override 2520 public void addOrRemoveTestCallCompanionApp(String packageName, boolean isAdded) { 2521 try { 2522 Log.startSession("TSI.aORTCCA"); 2523 enforceModifyPermission(); 2524 enforceShellOnly(Binder.getCallingUid(), "addOrRemoveTestCallCompanionApp"); 2525 synchronized (mLock) { 2526 long token = Binder.clearCallingIdentity(); 2527 try { 2528 mCallsManager.getRoleManagerAdapter().addOrRemoveTestCallCompanionApp( 2529 packageName, isAdded); 2530 } finally { 2531 Binder.restoreCallingIdentity(token); 2532 } 2533 } 2534 } finally { 2535 Log.endSession(); 2536 } 2537 } 2538 2539 @Override 2540 public void requestLogMark(String message) { 2541 try { 2542 Log.startSession("TSI.rLM"); 2543 enforceShellOnly(Binder.getCallingUid(), "requestLogMark is for shell only"); 2544 synchronized (mLock) { 2545 long token = Binder.clearCallingIdentity(); 2546 try { 2547 mCallsManager.requestLogMark(message); 2548 } finally { 2549 Binder.restoreCallingIdentity(token); 2550 } 2551 } 2552 } finally { 2553 Log.endSession(); 2554 } 2555 } 2556 2557 @Override 2558 public void setTestPhoneAcctSuggestionComponent(String flattenedComponentName) { 2559 try { 2560 Log.startSession("TSI.sPASA"); 2561 enforceModifyPermission(); 2562 if (Binder.getCallingUid() != Process.SHELL_UID 2563 && Binder.getCallingUid() != Process.ROOT_UID) { 2564 throw new SecurityException("Shell-only API."); 2565 } 2566 synchronized (mLock) { 2567 PhoneAccountSuggestionHelper.setOverrideServiceName(flattenedComponentName); 2568 } 2569 } finally { 2570 Log.endSession(); 2571 } 2572 } 2573 2574 @Override 2575 public void setTestDefaultDialer(String packageName) { 2576 try { 2577 Log.startSession("TSI.sTDD"); 2578 enforceModifyPermission(); 2579 if (Binder.getCallingUid() != Process.SHELL_UID 2580 && Binder.getCallingUid() != Process.ROOT_UID) { 2581 throw new SecurityException("Shell-only API."); 2582 } 2583 synchronized (mLock) { 2584 long token = Binder.clearCallingIdentity(); 2585 try { 2586 mCallsManager.getRoleManagerAdapter().setTestDefaultDialer(packageName); 2587 } finally { 2588 Binder.restoreCallingIdentity(token); 2589 } 2590 } 2591 } finally { 2592 Log.endSession(); 2593 } 2594 } 2595 2596 @Override 2597 public void setTestCallDiagnosticService(String packageName) { 2598 try { 2599 Log.startSession("TSI.sTCDS"); 2600 enforceModifyPermission(); 2601 enforceShellOnly(Binder.getCallingUid(), "setTestCallDiagnosticService is for " 2602 + "shell use only."); 2603 synchronized (mLock) { 2604 long token = Binder.clearCallingIdentity(); 2605 try { 2606 CallDiagnosticServiceController controller = 2607 mCallsManager.getCallDiagnosticServiceController(); 2608 if (controller != null) { 2609 controller.setTestCallDiagnosticService(packageName); 2610 } 2611 } finally { 2612 Binder.restoreCallingIdentity(token); 2613 } 2614 } 2615 } finally { 2616 Log.endSession(); 2617 } 2618 } 2619 2620 /** 2621 * Determines whether there are any ongoing {@link PhoneAccount#CAPABILITY_SELF_MANAGED} 2622 * calls for a given {@code packageName} and {@code userHandle}. 2623 * 2624 * @param packageName the package name of the app to check calls for. 2625 * @param userHandle the user handle on which to check for calls. 2626 * @param callingPackage The caller's package name. 2627 * @return {@code true} if there are ongoing calls, {@code false} otherwise. 2628 */ 2629 @Override 2630 public boolean isInSelfManagedCall(String packageName, UserHandle userHandle, 2631 String callingPackage) { 2632 try { 2633 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, 2634 "READ_PRIVILEGED_PHONE_STATE required."); 2635 // Ensure that the caller has the INTERACT_ACROSS_USERS permission if it's trying 2636 // to access calls that don't belong to it. 2637 if (!Binder.getCallingUserHandle().equals(userHandle)) { 2638 enforceInAppCrossUserPermission(); 2639 } 2640 2641 Log.startSession("TSI.iISMC", Log.getPackageAbbreviation(callingPackage)); 2642 synchronized (mLock) { 2643 long token = Binder.clearCallingIdentity(); 2644 try { 2645 return mCallsManager.isInSelfManagedCall( 2646 packageName, userHandle); 2647 } finally { 2648 Binder.restoreCallingIdentity(token); 2649 } 2650 } 2651 } finally { 2652 Log.endSession(); 2653 } 2654 } 2655 }; 2656 enforceCallStreamingPermission(String packageName, PhoneAccountHandle handle, int uid)2657 private boolean enforceCallStreamingPermission(String packageName, PhoneAccountHandle handle, 2658 int uid) { 2659 // TODO: implement this permission check (make sure the calling package is the d2di package) 2660 PhoneAccount account = mPhoneAccountRegistrar.getPhoneAccount(handle, 2661 UserHandle.getUserHandleForUid(uid)); 2662 if (account == null 2663 || !account.hasCapabilities(PhoneAccount.CAPABILITY_SUPPORTS_CALL_STREAMING)) { 2664 throw new SecurityException( 2665 "The phone account handle in requesting can't support call streaming: " 2666 + handle); 2667 } 2668 return true; 2669 } 2670 2671 /** 2672 * @return whether to return early without doing the action/throwing 2673 * @throws SecurityException same as {@link Context#enforceCallingOrSelfPermission} 2674 */ enforceAnswerCallPermission(String packageName, int uid)2675 private boolean enforceAnswerCallPermission(String packageName, int uid) { 2676 try { 2677 enforceModifyPermission(); 2678 } catch (SecurityException e) { 2679 final String permission = Manifest.permission.ANSWER_PHONE_CALLS; 2680 enforcePermission(permission); 2681 2682 final int opCode = AppOpsManager.permissionToOpCode(permission); 2683 if (opCode != AppOpsManager.OP_NONE 2684 && mAppOpsManager.checkOp(opCode, uid, packageName) 2685 != AppOpsManager.MODE_ALLOWED) { 2686 return false; 2687 } 2688 } 2689 return true; 2690 } 2691 2692 /** 2693 * @return {@code true} if the app has the handover permission and has received runtime 2694 * permission to perform that operation, {@code false}. 2695 * @throws SecurityException same as {@link Context#enforceCallingOrSelfPermission} 2696 */ enforceAcceptHandoverPermission(String packageName, int uid)2697 private boolean enforceAcceptHandoverPermission(String packageName, int uid) { 2698 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCEPT_HANDOVER, 2699 "App requires ACCEPT_HANDOVER permission to accept handovers."); 2700 2701 final int opCode = AppOpsManager.permissionToOpCode(Manifest.permission.ACCEPT_HANDOVER); 2702 if (opCode != AppOpsManager.OP_ACCEPT_HANDOVER || ( 2703 mAppOpsManager.checkOp(opCode, uid, packageName) 2704 != AppOpsManager.MODE_ALLOWED)) { 2705 return false; 2706 } 2707 return true; 2708 } 2709 2710 private Context mContext; 2711 private AppOpsManager mAppOpsManager; 2712 private PackageManager mPackageManager; 2713 private CallsManager mCallsManager; 2714 private final PhoneAccountRegistrar mPhoneAccountRegistrar; 2715 private final CallIntentProcessor.Adapter mCallIntentProcessorAdapter; 2716 private final UserCallIntentProcessorFactory mUserCallIntentProcessorFactory; 2717 private final DefaultDialerCache mDefaultDialerCache; 2718 private final SubscriptionManagerAdapter mSubscriptionManagerAdapter; 2719 private final SettingsSecureAdapter mSettingsSecureAdapter; 2720 private final TelecomSystem.SyncRoot mLock; 2721 private TransactionManager mTransactionManager; 2722 private final TransactionalServiceRepository mTransactionalServiceRepository; 2723 private final BlockedNumbersManager mBlockedNumbersManager; 2724 private final FeatureFlags mFeatureFlags; 2725 private final com.android.internal.telephony.flags.FeatureFlags mTelephonyFeatureFlags; 2726 TelecomServiceImpl( Context context, CallsManager callsManager, PhoneAccountRegistrar phoneAccountRegistrar, CallIntentProcessor.Adapter callIntentProcessorAdapter, UserCallIntentProcessorFactory userCallIntentProcessorFactory, DefaultDialerCache defaultDialerCache, SubscriptionManagerAdapter subscriptionManagerAdapter, SettingsSecureAdapter settingsSecureAdapter, FeatureFlags featureFlags, com.android.internal.telephony.flags.FeatureFlags telephonyFeatureFlags, TelecomSystem.SyncRoot lock)2727 public TelecomServiceImpl( 2728 Context context, 2729 CallsManager callsManager, 2730 PhoneAccountRegistrar phoneAccountRegistrar, 2731 CallIntentProcessor.Adapter callIntentProcessorAdapter, 2732 UserCallIntentProcessorFactory userCallIntentProcessorFactory, 2733 DefaultDialerCache defaultDialerCache, 2734 SubscriptionManagerAdapter subscriptionManagerAdapter, 2735 SettingsSecureAdapter settingsSecureAdapter, 2736 FeatureFlags featureFlags, 2737 com.android.internal.telephony.flags.FeatureFlags telephonyFeatureFlags, 2738 TelecomSystem.SyncRoot lock) { 2739 mContext = context; 2740 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE); 2741 2742 mPackageManager = mContext.getPackageManager(); 2743 2744 mCallsManager = callsManager; 2745 mFeatureFlags = featureFlags; 2746 if (telephonyFeatureFlags != null) { 2747 mTelephonyFeatureFlags = telephonyFeatureFlags; 2748 } else { 2749 mTelephonyFeatureFlags = 2750 new com.android.internal.telephony.flags.FeatureFlagsImpl(); 2751 } 2752 mLock = lock; 2753 mPhoneAccountRegistrar = phoneAccountRegistrar; 2754 mUserCallIntentProcessorFactory = userCallIntentProcessorFactory; 2755 mDefaultDialerCache = defaultDialerCache; 2756 mCallIntentProcessorAdapter = callIntentProcessorAdapter; 2757 mSubscriptionManagerAdapter = subscriptionManagerAdapter; 2758 mSettingsSecureAdapter = settingsSecureAdapter; 2759 2760 mDefaultDialerCache.observeDefaultDialerApplication(mContext.getMainExecutor(), userId -> { 2761 String defaultDialer = mDefaultDialerCache.getDefaultDialerApplication(userId); 2762 if (defaultDialer == null) { 2763 // We are replacing the dialer, just wait for the upcoming callback. 2764 return; 2765 } 2766 final Intent intent = new Intent(TelecomManager.ACTION_DEFAULT_DIALER_CHANGED) 2767 .putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, 2768 defaultDialer); 2769 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 2770 }); 2771 2772 mTransactionManager = TransactionManager.getInstance(); 2773 mTransactionalServiceRepository = new TransactionalServiceRepository(); 2774 mBlockedNumbersManager = mFeatureFlags.telecomMainlineBlockedNumbersManager() 2775 ? mContext.getSystemService(BlockedNumbersManager.class) 2776 : null; 2777 } 2778 2779 @VisibleForTesting setTransactionManager(TransactionManager transactionManager)2780 public void setTransactionManager(TransactionManager transactionManager){ 2781 mTransactionManager = transactionManager; 2782 } 2783 getBinder()2784 public ITelecomService.Stub getBinder() { 2785 return mBinderImpl; 2786 } 2787 2788 // 2789 // Supporting methods for the ITelecomService interface implementation. 2790 // 2791 isPhoneAccountHandleVisibleToCallingUser( PhoneAccountHandle phoneAccountUserHandle, UserHandle callingUser)2792 private boolean isPhoneAccountHandleVisibleToCallingUser( 2793 PhoneAccountHandle phoneAccountUserHandle, UserHandle callingUser) { 2794 synchronized (mLock) { 2795 return mPhoneAccountRegistrar.getPhoneAccount(phoneAccountUserHandle, callingUser) 2796 != null; 2797 } 2798 } 2799 isCallerSystemApp()2800 private boolean isCallerSystemApp() { 2801 int uid = Binder.getCallingUid(); 2802 String[] packages = mPackageManager.getPackagesForUid(uid); 2803 for (String packageName : packages) { 2804 if (isPackageSystemApp(packageName)) { 2805 return true; 2806 } 2807 } 2808 return false; 2809 } 2810 isPackageSystemApp(String packageName)2811 private boolean isPackageSystemApp(String packageName) { 2812 try { 2813 ApplicationInfo applicationInfo = mPackageManager.getApplicationInfo(packageName, 2814 PackageManager.GET_META_DATA); 2815 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 2816 return true; 2817 } 2818 } catch (PackageManager.NameNotFoundException e) { 2819 } 2820 return false; 2821 } 2822 acceptRingingCallInternal(int videoState, String packageName)2823 private void acceptRingingCallInternal(int videoState, String packageName) { 2824 Call call = mCallsManager.getFirstCallWithState(CallState.RINGING, 2825 CallState.SIMULATED_RINGING); 2826 if (call != null) { 2827 if (call.isSelfManaged()) { 2828 Log.addEvent(call, LogUtils.Events.REQUEST_ACCEPT, 2829 "self-mgd accept ignored from " + packageName); 2830 return; 2831 } 2832 2833 if (videoState == DEFAULT_VIDEO_STATE || !isValidAcceptVideoState(videoState)) { 2834 videoState = call.getVideoState(); 2835 } 2836 mCallsManager.answerCall(call, videoState); 2837 } 2838 } 2839 endCallInternal(String callingPackage)2840 private boolean endCallInternal(String callingPackage) { 2841 // Always operate on the foreground call if one exists, otherwise get the first call in 2842 // priority order by call-state. 2843 Call call = mCallsManager.getForegroundCall(); 2844 if (call == null) { 2845 call = mCallsManager.getFirstCallWithState( 2846 CallState.ACTIVE, 2847 CallState.DIALING, 2848 CallState.PULLING, 2849 CallState.RINGING, 2850 CallState.SIMULATED_RINGING, 2851 CallState.ON_HOLD); 2852 } 2853 2854 if (call != null) { 2855 if (call.isEmergencyCall()) { 2856 android.util.EventLog.writeEvent(0x534e4554, "132438333", -1, ""); 2857 return false; 2858 } 2859 2860 if (call.isSelfManaged()) { 2861 Log.addEvent(call, LogUtils.Events.REQUEST_DISCONNECT, 2862 "self-mgd disconnect ignored from " + callingPackage); 2863 return false; 2864 } 2865 2866 if (call.getState() == CallState.RINGING 2867 || call.getState() == CallState.SIMULATED_RINGING) { 2868 mCallsManager.rejectCall(call, false /* rejectWithMessage */, null); 2869 } else { 2870 mCallsManager.disconnectCall(call); 2871 } 2872 return true; 2873 } 2874 2875 return false; 2876 } 2877 2878 // Enforce that the PhoneAccountHandle being passed in is both registered to the current user 2879 // and enabled. enforcePhoneAccountIsRegisteredEnabled(PhoneAccountHandle phoneAccountHandle, UserHandle callingUserHandle)2880 private void enforcePhoneAccountIsRegisteredEnabled(PhoneAccountHandle phoneAccountHandle, 2881 UserHandle callingUserHandle) { 2882 PhoneAccount phoneAccount = mPhoneAccountRegistrar.getPhoneAccount(phoneAccountHandle, 2883 callingUserHandle); 2884 if(phoneAccount == null) { 2885 EventLog.writeEvent(0x534e4554, "26864502", Binder.getCallingUid(), "R"); 2886 throw new SecurityException("This PhoneAccountHandle is not registered for this user!"); 2887 } 2888 if(!phoneAccount.isEnabled()) { 2889 EventLog.writeEvent(0x534e4554, "26864502", Binder.getCallingUid(), "E"); 2890 throw new SecurityException("This PhoneAccountHandle is not enabled for this user!"); 2891 } 2892 } 2893 2894 // Enforce that the PhoneAccountHandle is tied to a self-managed package and not managed (aka 2895 // sim calling, etc.) enforcePhoneAccountIsNotManaged(PhoneAccountHandle phoneAccountHandle)2896 private void enforcePhoneAccountIsNotManaged(PhoneAccountHandle phoneAccountHandle) { 2897 PhoneAccount phoneAccount = mPhoneAccountRegistrar.getPhoneAccount(phoneAccountHandle, 2898 phoneAccountHandle.getUserHandle()); 2899 if (phoneAccount == null) { 2900 throw new IllegalArgumentException("enforcePhoneAccountIsNotManaged:" 2901 + " phoneAccount is null"); 2902 } 2903 if (phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) { 2904 throw new IllegalArgumentException("enforcePhoneAccountIsNotManaged:" 2905 + " CAPABILITY_SIM_SUBSCRIPTION is not allowed"); 2906 } 2907 if (phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)) { 2908 throw new IllegalArgumentException("enforcePhoneAccountIsNotManaged:" 2909 + " CAPABILITY_CALL_PROVIDER is not allowed"); 2910 } 2911 if (phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER)) { 2912 throw new IllegalArgumentException("enforcePhoneAccountIsNotManaged:" 2913 + " CAPABILITY_CONNECTION_MANAGER is not allowed"); 2914 } 2915 } 2916 enforcePhoneAccountModificationForPackage(String packageName)2917 private void enforcePhoneAccountModificationForPackage(String packageName) { 2918 // TODO: Use a new telecomm permission for this instead of reusing modify. 2919 2920 int result = mContext.checkCallingOrSelfPermission(MODIFY_PHONE_STATE); 2921 2922 // Callers with MODIFY_PHONE_STATE can use the PhoneAccount mechanism to implement 2923 // built-in behavior even when PhoneAccounts are not exposed as a third-part API. They 2924 // may also modify PhoneAccounts on behalf of any 'packageName'. 2925 2926 if (result != PackageManager.PERMISSION_GRANTED) { 2927 // Other callers are only allowed to modify PhoneAccounts if the relevant system 2928 // feature is enabled ... 2929 enforceTelecomFeature(); 2930 // ... and the PhoneAccounts they refer to are for their own package. 2931 enforceCallingPackage(packageName, "enforcePhoneAccountModificationForPackage"); 2932 } 2933 } 2934 enforcePermissionOrPrivilegedDialer(String permission, String packageName)2935 private void enforcePermissionOrPrivilegedDialer(String permission, String packageName) { 2936 if (!isPrivilegedDialerCalling(packageName)) { 2937 try { 2938 enforcePermission(permission); 2939 } catch (SecurityException e) { 2940 Log.e(this, e, "Caller must be the default or system dialer, or have the permission" 2941 + " %s to perform this operation.", permission); 2942 throw e; 2943 } 2944 } 2945 } 2946 enforceCallingPackage(String packageName, String message)2947 private void enforceCallingPackage(String packageName, String message) { 2948 int callingUid = Binder.getCallingUid(); 2949 2950 if (callingUid != Process.ROOT_UID && 2951 !callingUidMatchesPackageManagerRecords(packageName)) { 2952 throw new SecurityException(message + ": Package " + packageName 2953 + " does not belong to " + callingUid); 2954 } 2955 } 2956 2957 /** 2958 * helper method that compares the binder_uid to what the packageManager_uid reports for the 2959 * passed in packageName. 2960 * 2961 * returns true if the binder_uid matches the packageManager_uid records 2962 */ callingUidMatchesPackageManagerRecords(String packageName)2963 private boolean callingUidMatchesPackageManagerRecords(String packageName) { 2964 int packageUid = -1; 2965 int callingUid = Binder.getCallingUid(); 2966 PackageManager pm; 2967 long token = Binder.clearCallingIdentity(); 2968 try{ 2969 pm = mContext.createContextAsUser( 2970 UserHandle.getUserHandleForUid(callingUid), 0).getPackageManager(); 2971 } 2972 catch (Exception e){ 2973 Log.i(this, "callingUidMatchesPackageManagerRecords:" 2974 + " createContextAsUser hit exception=[%s]", e.toString()); 2975 return false; 2976 } finally { 2977 Binder.restoreCallingIdentity(token); 2978 } 2979 if (pm != null) { 2980 try { 2981 packageUid = pm.getPackageUid(packageName, 0); 2982 } catch (PackageManager.NameNotFoundException e) { 2983 // packageUid is -1. 2984 } 2985 } 2986 2987 if (packageUid != callingUid) { 2988 Log.i(this, "callingUidMatchesPackageManagerRecords: uid mismatch found for" 2989 + "packageName=[%s]. packageManager reports packageUid=[%d] but " 2990 + "binder reports callingUid=[%d]", packageName, packageUid, callingUid); 2991 } 2992 2993 return packageUid == callingUid; 2994 } 2995 2996 /** 2997 * Note: This method should be called BEFORE clearing the binder identity. 2998 * 2999 * @param permissionsToValidate set of permissions that should be checked 3000 * @param alreadyComputedPermissions a list of permissions that were already checked 3001 * @return all the permissions that 3002 */ computePermissionsForBoundPackage( Set<String> permissionsToValidate, Set<String> alreadyComputedPermissions)3003 private Set<String> computePermissionsForBoundPackage( 3004 Set<String> permissionsToValidate, 3005 Set<String> alreadyComputedPermissions) { 3006 Set<String> permissions = Objects.requireNonNullElseGet(alreadyComputedPermissions, 3007 HashSet::new); 3008 for (String permission : permissionsToValidate) { 3009 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) { 3010 permissions.add(permission); 3011 } 3012 } 3013 return permissions; 3014 } 3015 3016 /** 3017 * This method should be used to clear {@link PhoneAccount} properties based on a 3018 * callingPackages permissions. 3019 * 3020 * @param account to clear properties from 3021 * @param permissions the list of permissions the callingPackge has 3022 * @return the account that callingPackage will receive 3023 */ maybeCleansePhoneAccount(PhoneAccount account, Set<String> permissions)3024 private PhoneAccount maybeCleansePhoneAccount(PhoneAccount account, 3025 Set<String> permissions) { 3026 if (account == null) { 3027 return null; 3028 } 3029 PhoneAccount.Builder accountBuilder = new PhoneAccount.Builder(account); 3030 if (!permissions.contains(MODIFY_PHONE_STATE)) { 3031 accountBuilder.setGroupId("***"); 3032 } 3033 return accountBuilder.build(); 3034 } 3035 enforceTelecomFeature()3036 private void enforceTelecomFeature() { 3037 PackageManager pm = mContext.getPackageManager(); 3038 if (!pm.hasSystemFeature(PackageManager.FEATURE_TELECOM) 3039 && !pm.hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE)) { 3040 throw new UnsupportedOperationException( 3041 "System does not support feature " + PackageManager.FEATURE_TELECOM); 3042 } 3043 } 3044 enforceRegisterSimSubscriptionPermission()3045 private void enforceRegisterSimSubscriptionPermission() { 3046 enforcePermission(REGISTER_SIM_SUBSCRIPTION); 3047 } 3048 enforceModifyPermission()3049 private void enforceModifyPermission() { 3050 enforcePermission(MODIFY_PHONE_STATE); 3051 } 3052 enforceModifyPermission(String message)3053 private void enforceModifyPermission(String message) { 3054 mContext.enforceCallingOrSelfPermission(MODIFY_PHONE_STATE, message); 3055 } 3056 enforcePermission(String permission)3057 private void enforcePermission(String permission) { 3058 mContext.enforceCallingOrSelfPermission(permission, null); 3059 } 3060 enforceRegisterSelfManaged()3061 private void enforceRegisterSelfManaged() { 3062 mContext.enforceCallingPermission(android.Manifest.permission.MANAGE_OWN_CALLS, null); 3063 } 3064 enforceRegisterMultiUser()3065 private void enforceRegisterMultiUser() { 3066 if (!isCallerSystemApp()) { 3067 throw new SecurityException("CAPABILITY_MULTI_USER is only available to system apps."); 3068 } 3069 } 3070 enforceRegisterVoiceCallingIndicationCapabilities(PhoneAccount account)3071 private void enforceRegisterVoiceCallingIndicationCapabilities(PhoneAccount account) { 3072 // Caller must be able to register a SIM PhoneAccount or be the SIM call manager (as named 3073 // in carrier config) to declare the two voice indication capabilities. 3074 boolean prerequisiteCapabilitiesOk = 3075 account.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION) 3076 || account.hasCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER); 3077 boolean permissionsOk = 3078 isCallerSimCallManagerForAnySim(account.getAccountHandle()) 3079 || mContext.checkCallingOrSelfPermission(REGISTER_SIM_SUBSCRIPTION) 3080 == PackageManager.PERMISSION_GRANTED; 3081 if (!prerequisiteCapabilitiesOk || !permissionsOk) { 3082 throw new SecurityException( 3083 "Only SIM subscriptions and connection managers are allowed to declare " 3084 + "CAPABILITY_SUPPORTS_VOICE_CALLING_INDICATIONS and " 3085 + "CAPABILITY_VOICE_CALLING_AVAILABLE"); 3086 } 3087 } 3088 enforceRegisterSkipCallFiltering()3089 private void enforceRegisterSkipCallFiltering() { 3090 if (!isCallerSystemApp()) { 3091 throw new SecurityException( 3092 "EXTRA_SKIP_CALL_FILTERING is only available to system apps."); 3093 } 3094 } 3095 enforceUserHandleMatchesCaller(PhoneAccountHandle accountHandle)3096 private void enforceUserHandleMatchesCaller(PhoneAccountHandle accountHandle) { 3097 if (!Binder.getCallingUserHandle().equals(accountHandle.getUserHandle())) { 3098 // Enforce INTERACT_ACROSS_USERS if the calling user handle does not match 3099 // phone account's user handle 3100 enforceInAppCrossUserPermission(); 3101 } 3102 } 3103 enforcePhoneAccountHandleMatchesCaller(PhoneAccountHandle phoneAccountHandle, String callingPackage)3104 private void enforcePhoneAccountHandleMatchesCaller(PhoneAccountHandle phoneAccountHandle, 3105 String callingPackage) { 3106 if (!callingPackage.equals(phoneAccountHandle.getComponentName().getPackageName())) { 3107 throw new SecurityException("Caller does not own the PhoneAccountHandle"); 3108 } 3109 } 3110 enforceCrossUserPermission(int callingUid)3111 private void enforceCrossUserPermission(int callingUid) { 3112 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3113 mContext.enforceCallingOrSelfPermission( 3114 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have" 3115 + " INTERACT_ACROSS_USERS_FULL permission"); 3116 } 3117 } 3118 enforceInAppCrossUserPermission()3119 private void enforceInAppCrossUserPermission() { 3120 mContext.enforceCallingOrSelfPermission( 3121 android.Manifest.permission.INTERACT_ACROSS_USERS, "Must be system or have" 3122 + " INTERACT_ACROSS_USERS permission"); 3123 } 3124 enforceInAppCrossProfilePermission()3125 private void enforceInAppCrossProfilePermission() { 3126 mContext.enforceCallingOrSelfPermission( 3127 android.Manifest.permission.INTERACT_ACROSS_PROFILES, "Must be system or have" 3128 + " INTERACT_ACROSS_PROFILES permission"); 3129 } 3130 hasInAppCrossUserPermission()3131 private boolean hasInAppCrossUserPermission() { 3132 return mContext.checkCallingOrSelfPermission( 3133 Manifest.permission.INTERACT_ACROSS_USERS) 3134 == PackageManager.PERMISSION_GRANTED; 3135 } 3136 hasInAppCrossProfilePermission()3137 private boolean hasInAppCrossProfilePermission() { 3138 return mContext.checkCallingOrSelfPermission( 3139 Manifest.permission.INTERACT_ACROSS_PROFILES) 3140 == PackageManager.PERMISSION_GRANTED; 3141 } 3142 3143 // to be used for TestApi methods that can only be called with SHELL UID. enforceShellOnly(int callingUid, String message)3144 private void enforceShellOnly(int callingUid, String message) { 3145 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) { 3146 return; // okay 3147 } 3148 3149 throw new SecurityException(message + ": Only shell user can call it"); 3150 } 3151 canReadPhoneState(String callingPackage, String callingFeatureId, String message)3152 private boolean canReadPhoneState(String callingPackage, String callingFeatureId, 3153 String message) { 3154 // The system/default dialer can always read phone state - so that emergency calls will 3155 // still work. 3156 if (isPrivilegedDialerCalling(callingPackage)) { 3157 return true; 3158 } 3159 3160 try { 3161 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, message); 3162 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED 3163 // permission 3164 return true; 3165 } catch (SecurityException e) { 3166 // Accessing phone state is gated by a special permission. 3167 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, message); 3168 3169 // Some apps that have the permission can be restricted via app ops. 3170 return mAppOpsManager.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(), 3171 callingPackage, callingFeatureId, message) == AppOpsManager.MODE_ALLOWED; 3172 } 3173 } 3174 canReadMangeOwnCalls(String message)3175 private boolean canReadMangeOwnCalls(String message) { 3176 try { 3177 mContext.enforceCallingOrSelfPermission(MANAGE_OWN_CALLS, message); 3178 return true; 3179 } catch (SecurityException e) { 3180 return false; 3181 } 3182 } 3183 canReadPhoneNumbers(String callingPackage, String callingFeatureId, String message)3184 private boolean canReadPhoneNumbers(String callingPackage, String callingFeatureId, 3185 String message) { 3186 boolean targetSdkPreR = false; 3187 int uid = Binder.getCallingUid(); 3188 try { 3189 ApplicationInfo applicationInfo = mPackageManager.getApplicationInfoAsUser( 3190 callingPackage, 0, UserHandle.getUserHandleForUid(Binder.getCallingUid())); 3191 targetSdkPreR = applicationInfo != null 3192 && applicationInfo.targetSdkVersion < Build.VERSION_CODES.R; 3193 } catch (PackageManager.NameNotFoundException e) { 3194 // In the case that the PackageManager cannot find the specified calling package apply 3195 // the more restrictive target R+ requirements. 3196 } 3197 // Apps targeting pre-R can access phone numbers via READ_PHONE_STATE 3198 if (targetSdkPreR) { 3199 try { 3200 return canReadPhoneState(callingPackage, callingFeatureId, message); 3201 } catch (SecurityException e) { 3202 // Apps targeting pre-R can still access phone numbers via the additional checks 3203 // below. 3204 } 3205 } else { 3206 // The system/default dialer can always read phone state - so that emergency calls will 3207 // still work. 3208 if (isPrivilegedDialerCalling(callingPackage)) { 3209 return true; 3210 } 3211 if (mContext.checkCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE) 3212 == PackageManager.PERMISSION_GRANTED) { 3213 return true; 3214 } 3215 } 3216 if (mContext.checkCallingOrSelfPermission(READ_PHONE_NUMBERS) 3217 == PackageManager.PERMISSION_GRANTED && mAppOpsManager.noteOpNoThrow( 3218 AppOpsManager.OPSTR_READ_PHONE_NUMBERS, uid, callingPackage, callingFeatureId, 3219 message) == AppOpsManager.MODE_ALLOWED) { 3220 return true; 3221 } 3222 if (mContext.checkCallingOrSelfPermission(READ_SMS) == PackageManager.PERMISSION_GRANTED 3223 && mAppOpsManager.noteOpNoThrow(AppOpsManager.OPSTR_READ_SMS, uid, callingPackage, 3224 callingFeatureId, message) == AppOpsManager.MODE_ALLOWED) { 3225 return true; 3226 } 3227 // The default SMS app with the WRITE_SMS appop granted can access phone numbers. 3228 if (mAppOpsManager.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SMS, uid, callingPackage, 3229 callingFeatureId, message) == AppOpsManager.MODE_ALLOWED) { 3230 return true; 3231 } 3232 throw new SecurityException("Package " + callingPackage 3233 + " does not meet the requirements to access the phone number"); 3234 } 3235 3236 private boolean canReadPrivilegedPhoneState(String callingPackage, String message) { 3237 // The system/default dialer can always read phone state - so that emergency calls will 3238 // still work. 3239 if (isPrivilegedDialerCalling(callingPackage)) { 3240 return true; 3241 } 3242 3243 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, message); 3244 return true; 3245 } 3246 3247 private boolean isDialerOrPrivileged(String callingPackage, String message) { 3248 // The system/default dialer can always read phone state - so that emergency calls will 3249 // still work. 3250 if (isPrivilegedDialerCalling(callingPackage)) { 3251 return true; 3252 } 3253 3254 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, message); 3255 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED 3256 // permission 3257 return true; 3258 } 3259 3260 private boolean isSelfManagedConnectionService(PhoneAccountHandle phoneAccountHandle) { 3261 if (phoneAccountHandle != null) { 3262 PhoneAccount phoneAccount = mPhoneAccountRegistrar.getPhoneAccountUnchecked( 3263 phoneAccountHandle); 3264 return phoneAccount != null && phoneAccount.isSelfManaged(); 3265 } 3266 return false; 3267 } 3268 3269 private boolean canCallPhone(String callingPackage, String message) { 3270 return canCallPhone(callingPackage, null /* featureId */, message); 3271 } 3272 3273 private boolean canCallPhone(String callingPackage, String callingFeatureId, String message) { 3274 // The system/default dialer can always read phone state - so that emergency calls will 3275 // still work. 3276 if (isPrivilegedDialerCalling(callingPackage)) { 3277 return true; 3278 } 3279 3280 if (mContext.checkCallingOrSelfPermission(CALL_PRIVILEGED) 3281 == PackageManager.PERMISSION_GRANTED) { 3282 return true; 3283 } 3284 3285 // Accessing phone state is gated by a special permission. 3286 mContext.enforceCallingOrSelfPermission(CALL_PHONE, message); 3287 3288 // Some apps that have the permission can be restricted via app ops. 3289 return mAppOpsManager.noteOp(AppOpsManager.OP_CALL_PHONE, 3290 Binder.getCallingUid(), callingPackage, callingFeatureId, message) 3291 == AppOpsManager.MODE_ALLOWED; 3292 } 3293 3294 private boolean canGetPhoneAccount(String callingPackage, PhoneAccountHandle accountHandle) { 3295 // Allow default dialer, system dialer and sim call manager to be able to do this without 3296 // extra permission 3297 try { 3298 if (isPrivilegedDialerCalling(callingPackage) || isCallerSimCallManager( 3299 accountHandle)) { 3300 return true; 3301 } 3302 } catch (SecurityException e) { 3303 // ignore 3304 } 3305 3306 try { 3307 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, null); 3308 return true; 3309 } catch (SecurityException e) { 3310 // Accessing phone state is gated by a special permission. 3311 mContext.enforceCallingOrSelfPermission(READ_PHONE_NUMBERS, null); 3312 return true; 3313 } 3314 } 3315 3316 private boolean isCallerSimCallManager(PhoneAccountHandle targetPhoneAccount) { 3317 long token = Binder.clearCallingIdentity(); 3318 PhoneAccountHandle accountHandle = null; 3319 try { 3320 accountHandle = mPhoneAccountRegistrar.getSimCallManagerFromHandle(targetPhoneAccount, 3321 mCallsManager.getCurrentUserHandle()); 3322 } finally { 3323 Binder.restoreCallingIdentity(token); 3324 } 3325 3326 if (accountHandle != null) { 3327 try { 3328 mAppOpsManager.checkPackage( 3329 Binder.getCallingUid(), accountHandle.getComponentName().getPackageName()); 3330 return true; 3331 } catch (SecurityException e) { 3332 } 3333 } 3334 return false; 3335 } 3336 3337 /** 3338 * Similar to {@link #isCallerSimCallManager}, but works for all SIMs and does not require 3339 * {@code accountHandle} to be registered yet. 3340 */ 3341 private boolean isCallerSimCallManagerForAnySim(PhoneAccountHandle accountHandle) { 3342 if (isCallerSimCallManager(accountHandle)) { 3343 // The caller has already registered a CONNECTION_MANAGER PhoneAccount, so let them pass 3344 // (this allows the SIM call manager through in case of SIM switches, where carrier 3345 // config may be in a transient state) 3346 return true; 3347 } 3348 // If the caller isn't already registered, then we have to look at the active PSTN 3349 // PhoneAccounts and check their carrier configs to see if any point to this one's component 3350 final long token = Binder.clearCallingIdentity(); 3351 try { 3352 return !mPhoneAccountRegistrar 3353 .getSimPhoneAccountsFromSimCallManager(accountHandle) 3354 .isEmpty(); 3355 } finally { 3356 Binder.restoreCallingIdentity(token); 3357 } 3358 } 3359 3360 private boolean isPrivilegedDialerCalling(String callingPackage) { 3361 mAppOpsManager.checkPackage(Binder.getCallingUid(), callingPackage); 3362 3363 // Note: Important to clear the calling identity since the code below calls into RoleManager 3364 // to check who holds the dialer role, and that requires MANAGE_ROLE_HOLDERS permission 3365 // which is a system permission. 3366 long token = Binder.clearCallingIdentity(); 3367 try { 3368 return mDefaultDialerCache.isDefaultOrSystemDialer( 3369 callingPackage, Binder.getCallingUserHandle().getIdentifier()); 3370 } finally { 3371 Binder.restoreCallingIdentity(token); 3372 } 3373 } 3374 3375 private TelephonyManager getTelephonyManager(int subId) { 3376 return ((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE)) 3377 .createForSubscriptionId(subId); 3378 } 3379 3380 /** 3381 * Determines if a video state is valid for accepting an incoming call. 3382 * For the purpose of accepting a call, states {@link VideoProfile#STATE_AUDIO_ONLY}, and 3383 * any combination of {@link VideoProfile#STATE_RX_ENABLED} and 3384 * {@link VideoProfile#STATE_TX_ENABLED} are considered valid. 3385 * 3386 * @param videoState The video state. 3387 * @return {@code true} if the video state is valid, {@code false} otherwise. 3388 */ 3389 private boolean isValidAcceptVideoState(int videoState) { 3390 // Given a video state input, turn off TX and RX so that we can determine if those were the 3391 // only bits set. 3392 int remainingState = videoState & ~VideoProfile.STATE_TX_ENABLED; 3393 remainingState = remainingState & ~VideoProfile.STATE_RX_ENABLED; 3394 3395 // If only TX or RX were set (or neither), the video state is valid. 3396 return remainingState == 0; 3397 } 3398 3399 private void broadcastCallScreeningAppChangedIntent(String componentName, 3400 boolean isDefault) { 3401 if (TextUtils.isEmpty(componentName)) { 3402 return; 3403 } 3404 3405 ComponentName broadcastComponentName = ComponentName.unflattenFromString(componentName); 3406 3407 if (broadcastComponentName != null) { 3408 Intent intent = new Intent(TelecomManager 3409 .ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED); 3410 intent.putExtra(TelecomManager 3411 .EXTRA_IS_DEFAULT_CALL_SCREENING_APP, isDefault); 3412 intent.putExtra(TelecomManager 3413 .EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME, componentName); 3414 intent.setPackage(broadcastComponentName.getPackageName()); 3415 mContext.sendBroadcast(intent); 3416 } 3417 } 3418 3419 private void validateAccountIconUserBoundary(Icon icon) { 3420 // Refer to Icon#getUriString for context. The URI string is invalid for icons of 3421 // incompatible types. 3422 if (icon != null && (icon.getType() == Icon.TYPE_URI 3423 || icon.getType() == Icon.TYPE_URI_ADAPTIVE_BITMAP)) { 3424 String encodedUser = icon.getUri().getEncodedUserInfo(); 3425 // If there is no encoded user, the URI is calling into the calling user space 3426 if (encodedUser != null) { 3427 int userId = Integer.parseInt(encodedUser); 3428 if (userId != UserHandle.getUserId(Binder.getCallingUid())) { 3429 // If we are transcending the profile boundary, throw an error. 3430 throw new IllegalArgumentException("Attempting to register a phone account with" 3431 + " an image icon belonging to another user."); 3432 } 3433 } 3434 } 3435 } 3436 3437 private void validateSimultaneousCallingPackageNames(String appPackageName, 3438 Set<PhoneAccountHandle> handles) { 3439 for (PhoneAccountHandle handle : handles) { 3440 ComponentName name = handle.getComponentName(); 3441 if (name == null) { 3442 throw new IllegalArgumentException("ComponentName is null"); 3443 } 3444 String restrictionPackageName = name.getPackageName(); 3445 if (!appPackageName.equals(restrictionPackageName)) { 3446 throw new SecurityException("The package name of the PhoneAccount does not " 3447 + "match one or more of the package names set in the simultaneous " 3448 + "calling restriction."); 3449 } 3450 } 3451 } 3452 } 3453