• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.MODIFY_PHONE_STATE;
23 import static android.Manifest.permission.READ_PHONE_NUMBERS;
24 import static android.Manifest.permission.READ_PHONE_STATE;
25 import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
26 import static android.Manifest.permission.READ_SMS;
27 import static android.Manifest.permission.REGISTER_SIM_SUBSCRIPTION;
28 import static android.Manifest.permission.WRITE_SECURE_SETTINGS;
29 
30 import android.Manifest;
31 import android.app.ActivityManager;
32 import android.app.AppOpsManager;
33 import android.app.UiModeManager;
34 import android.app.compat.CompatChanges;
35 import android.content.AttributionSource;
36 import android.content.ComponentName;
37 import android.content.ContentResolver;
38 import android.content.Context;
39 import android.content.Intent;
40 import android.content.PermissionChecker;
41 import android.content.pm.ApplicationInfo;
42 import android.content.pm.PackageManager;
43 import android.content.pm.ResolveInfo;
44 import android.net.Uri;
45 import android.os.Binder;
46 import android.os.Build;
47 import android.os.Bundle;
48 import android.os.Process;
49 import android.os.UserHandle;
50 import android.provider.BlockedNumberContract;
51 import android.provider.Settings;
52 import android.telecom.Log;
53 import android.telecom.PhoneAccount;
54 import android.telecom.PhoneAccountHandle;
55 import android.telecom.TelecomAnalytics;
56 import android.telecom.TelecomManager;
57 import android.telecom.VideoProfile;
58 import android.telephony.SubscriptionManager;
59 import android.telephony.TelephonyManager;
60 import android.text.TextUtils;
61 import android.util.EventLog;
62 
63 import com.android.internal.telecom.ITelecomService;
64 import com.android.internal.util.IndentingPrintWriter;
65 import com.android.server.telecom.components.UserCallIntentProcessorFactory;
66 import com.android.server.telecom.settings.BlockedNumbersActivity;
67 
68 import java.io.FileDescriptor;
69 import java.io.PrintWriter;
70 import java.util.Collections;
71 import java.util.List;
72 
73 // TODO: Needed for move to system service: import com.android.internal.R;
74 
75 /**
76  * Implementation of the ITelecom interface.
77  */
78 public class TelecomServiceImpl {
79 
80     public interface SubscriptionManagerAdapter {
getDefaultVoiceSubId()81         int getDefaultVoiceSubId();
82     }
83 
84     static class SubscriptionManagerAdapterImpl implements SubscriptionManagerAdapter {
85         @Override
getDefaultVoiceSubId()86         public int getDefaultVoiceSubId() {
87             return SubscriptionManager.getDefaultVoiceSubscriptionId();
88         }
89     }
90 
91     public interface SettingsSecureAdapter {
putStringForUser(ContentResolver resolver, String name, String value, int userHandle)92         void putStringForUser(ContentResolver resolver, String name, String value, int userHandle);
93 
getStringForUser(ContentResolver resolver, String name, int userHandle)94         String getStringForUser(ContentResolver resolver, String name, int userHandle);
95     }
96 
97     static class SettingsSecureAdapterImpl implements SettingsSecureAdapter {
98         @Override
putStringForUser(ContentResolver resolver, String name, String value, int userHandle)99         public void putStringForUser(ContentResolver resolver, String name, String value,
100             int userHandle) {
101             Settings.Secure.putStringForUser(resolver, name, value, userHandle);
102         }
103 
104         @Override
getStringForUser(ContentResolver resolver, String name, int userHandle)105         public String getStringForUser(ContentResolver resolver, String name, int userHandle) {
106             return Settings.Secure.getStringForUser(resolver, name, userHandle);
107         }
108     }
109 
110     private static final String TIME_LINE_ARG = "timeline";
111     private static final int DEFAULT_VIDEO_STATE = -1;
112     private static final String PERMISSION_HANDLE_CALL_INTENT =
113             "android.permission.HANDLE_CALL_INTENT";
114 
115     private final ITelecomService.Stub mBinderImpl = new ITelecomService.Stub() {
116         @Override
117         public PhoneAccountHandle getDefaultOutgoingPhoneAccount(String uriScheme,
118                 String callingPackage, String callingFeatureId) {
119             try {
120                 Log.startSession("TSI.gDOPA");
121                 synchronized (mLock) {
122                     PhoneAccountHandle phoneAccountHandle = null;
123                     final UserHandle callingUserHandle = Binder.getCallingUserHandle();
124                     long token = Binder.clearCallingIdentity();
125                     try {
126                         phoneAccountHandle = mPhoneAccountRegistrar
127                                 .getOutgoingPhoneAccountForScheme(uriScheme, callingUserHandle);
128                     } catch (Exception e) {
129                         Log.e(this, e, "getDefaultOutgoingPhoneAccount");
130                         throw e;
131                     } finally {
132                         Binder.restoreCallingIdentity(token);
133                     }
134                     if (isCallerSimCallManager(phoneAccountHandle)
135                         || canReadPhoneState(
136                             callingPackage,
137                             callingFeatureId,
138                             "getDefaultOutgoingPhoneAccount")) {
139                       return phoneAccountHandle;
140                     }
141                     return null;
142                 }
143             } finally {
144                 Log.endSession();
145             }
146         }
147 
148         @Override
149         public PhoneAccountHandle getUserSelectedOutgoingPhoneAccount(String callingPackage) {
150             synchronized (mLock) {
151                 try {
152                     Log.startSession("TSI.gUSOPA");
153                     if (!isDialerOrPrivileged(callingPackage, "getDefaultOutgoingPhoneAccount")) {
154                         throw new SecurityException("Only the default dialer, or caller with "
155                                 + "READ_PRIVILEGED_PHONE_STATE can call this method.");
156                     }
157                     final UserHandle callingUserHandle = Binder.getCallingUserHandle();
158                     return mPhoneAccountRegistrar.getUserSelectedOutgoingPhoneAccount(
159                             callingUserHandle);
160                 } catch (Exception e) {
161                     Log.e(this, e, "getUserSelectedOutgoingPhoneAccount");
162                     throw e;
163                 } finally {
164                     Log.endSession();
165                 }
166             }
167         }
168 
169         @Override
170         public void setUserSelectedOutgoingPhoneAccount(PhoneAccountHandle accountHandle) {
171             try {
172                 Log.startSession("TSI.sUSOPA");
173                 synchronized (mLock) {
174                     enforceModifyPermission();
175                     UserHandle callingUserHandle = Binder.getCallingUserHandle();
176                     long token = Binder.clearCallingIdentity();
177                     try {
178                         mPhoneAccountRegistrar.setUserSelectedOutgoingPhoneAccount(
179                                 accountHandle, callingUserHandle);
180                     } catch (Exception e) {
181                         Log.e(this, e, "setUserSelectedOutgoingPhoneAccount");
182                         throw e;
183                     } finally {
184                         Binder.restoreCallingIdentity(token);
185                     }
186                 }
187             } finally {
188                 Log.endSession();
189             }
190         }
191 
192         @Override
193         public List<PhoneAccountHandle> getCallCapablePhoneAccounts(
194                 boolean includeDisabledAccounts, String callingPackage, String callingFeatureId) {
195             try {
196                 Log.startSession("TSI.gCCPA");
197                 if (includeDisabledAccounts &&
198                         !canReadPrivilegedPhoneState(
199                                 callingPackage, "getCallCapablePhoneAccounts")) {
200                     return Collections.emptyList();
201                 }
202                 if (!canReadPhoneState(callingPackage, callingFeatureId,
203                         "getCallCapablePhoneAccounts")) {
204                     return Collections.emptyList();
205                 }
206                 synchronized (mLock) {
207                     final UserHandle callingUserHandle = Binder.getCallingUserHandle();
208                     long token = Binder.clearCallingIdentity();
209                     try {
210                         return mPhoneAccountRegistrar.getCallCapablePhoneAccounts(null,
211                                 includeDisabledAccounts, callingUserHandle);
212                     } catch (Exception e) {
213                         Log.e(this, e, "getCallCapablePhoneAccounts");
214                         throw e;
215                     } finally {
216                         Binder.restoreCallingIdentity(token);
217                     }
218                 }
219             } finally {
220                 Log.endSession();
221             }
222         }
223 
224         @Override
225         public List<PhoneAccountHandle> getSelfManagedPhoneAccounts(String callingPackage,
226                 String callingFeatureId) {
227             try {
228                 Log.startSession("TSI.gSMPA");
229                 if (!canReadPhoneState(callingPackage, callingFeatureId,
230                         "Requires READ_PHONE_STATE permission.")) {
231                     throw new SecurityException("Requires READ_PHONE_STATE permission.");
232                 }
233                 synchronized (mLock) {
234                     final UserHandle callingUserHandle = Binder.getCallingUserHandle();
235                     long token = Binder.clearCallingIdentity();
236                     try {
237                         return mPhoneAccountRegistrar.getSelfManagedPhoneAccounts(
238                                 callingUserHandle);
239                     } catch (Exception e) {
240                         Log.e(this, e, "getSelfManagedPhoneAccounts");
241                         throw e;
242                     } finally {
243                         Binder.restoreCallingIdentity(token);
244                     }
245                 }
246             } finally {
247                 Log.endSession();
248             }
249         }
250 
251         @Override
252         public List<PhoneAccountHandle> getPhoneAccountsSupportingScheme(String uriScheme,
253                 String callingPackage) {
254             try {
255                 Log.startSession("TSI.gPASS");
256                 try {
257                     enforceModifyPermission(
258                             "getPhoneAccountsSupportingScheme requires MODIFY_PHONE_STATE");
259                 } catch (SecurityException e) {
260                     EventLog.writeEvent(0x534e4554, "62347125", Binder.getCallingUid(),
261                             "getPhoneAccountsSupportingScheme: " + callingPackage);
262                     return Collections.emptyList();
263                 }
264 
265                 synchronized (mLock) {
266                     final UserHandle callingUserHandle = Binder.getCallingUserHandle();
267                     long token = Binder.clearCallingIdentity();
268                     try {
269                         return mPhoneAccountRegistrar.getCallCapablePhoneAccounts(uriScheme, false,
270                                 callingUserHandle);
271                     } catch (Exception e) {
272                         Log.e(this, e, "getPhoneAccountsSupportingScheme %s", uriScheme);
273                         throw e;
274                     } finally {
275                         Binder.restoreCallingIdentity(token);
276                     }
277                 }
278             } finally {
279                 Log.endSession();
280             }
281         }
282 
283         @Override
284         public List<PhoneAccountHandle> getPhoneAccountsForPackage(String packageName) {
285             //TODO: Deprecate this in S
286             try {
287                 enforceCallingPackage(packageName);
288             } catch (SecurityException se1) {
289                 EventLog.writeEvent(0x534e4554, "153995334", Binder.getCallingUid(),
290                         "getPhoneAccountsForPackage: invalid calling package");
291                 throw se1;
292             }
293 
294             try {
295                 enforcePermission(READ_PRIVILEGED_PHONE_STATE);
296             } catch (SecurityException se2) {
297                 EventLog.writeEvent(0x534e4554, "153995334", Binder.getCallingUid(),
298                         "getPhoneAccountsForPackage: no permission");
299                 throw se2;
300             }
301 
302             synchronized (mLock) {
303                 final UserHandle callingUserHandle = Binder.getCallingUserHandle();
304                 long token = Binder.clearCallingIdentity();
305                 try {
306                     Log.startSession("TSI.gPAFP");
307                     return mPhoneAccountRegistrar.getPhoneAccountsForPackage(packageName,
308                             callingUserHandle);
309                 } catch (Exception e) {
310                     Log.e(this, e, "getPhoneAccountsForPackage %s", packageName);
311                     throw e;
312                 } finally {
313                     Binder.restoreCallingIdentity(token);
314                     Log.endSession();
315                 }
316             }
317         }
318 
319         @Override
320         public PhoneAccount getPhoneAccount(PhoneAccountHandle accountHandle,
321                 String callingPackage) {
322             synchronized (mLock) {
323                 final UserHandle callingUserHandle = Binder.getCallingUserHandle();
324                 if (CompatChanges.isChangeEnabled(
325                         TelecomManager.ENABLE_GET_PHONE_ACCOUNT_PERMISSION_PROTECTION,
326                         callingPackage, Binder.getCallingUserHandle())) {
327                     if (Binder.getCallingUid() != Process.SHELL_UID &&
328                             !canGetPhoneAccount(callingPackage, accountHandle)) {
329                         SecurityException e = new SecurityException("getPhoneAccount API requires" +
330                                 "READ_PHONE_NUMBERS");
331                         Log.e(this, e, "getPhoneAccount %s", accountHandle);
332                         throw e;
333                     }
334                 }
335                 long token = Binder.clearCallingIdentity();
336                 try {
337                     Log.startSession("TSI.gPA");
338                     // In ideal case, we should not resolve the handle across profiles. But given
339                     // the fact that profile's call is handled by its parent user's in-call UI,
340                     // parent user's in call UI need to be able to get phone account from the
341                     // profile's phone account handle.
342                     return mPhoneAccountRegistrar
343                             .getPhoneAccount(accountHandle, callingUserHandle,
344                                     /* acrossProfiles */ true);
345                 } catch (Exception e) {
346                     Log.e(this, e, "getPhoneAccount %s", accountHandle);
347                     throw e;
348                 } finally {
349                     Binder.restoreCallingIdentity(token);
350                     Log.endSession();
351                 }
352             }
353         }
354 
355         @Override
356         public int getAllPhoneAccountsCount() {
357             try {
358                 Log.startSession("TSI.gAPAC");
359                 try {
360                     enforceModifyPermission(
361                             "getAllPhoneAccountsCount requires MODIFY_PHONE_STATE permission.");
362                 } catch (SecurityException e) {
363                     EventLog.writeEvent(0x534e4554, "62347125", Binder.getCallingUid(),
364                             "getAllPhoneAccountsCount");
365                     throw e;
366                 }
367 
368                 synchronized (mLock) {
369                     try {
370                         // This list is pre-filtered for the calling user.
371                         return getAllPhoneAccounts().size();
372                     } catch (Exception e) {
373                         Log.e(this, e, "getAllPhoneAccountsCount");
374                         throw e;
375 
376                     }
377                 }
378             } finally {
379                 Log.endSession();
380             }
381         }
382 
383         @Override
384         public List<PhoneAccount> getAllPhoneAccounts() {
385             synchronized (mLock) {
386                 try {
387                     Log.startSession("TSI.gAPA");
388                     try {
389                         enforceModifyPermission(
390                                 "getAllPhoneAccounts requires MODIFY_PHONE_STATE permission.");
391                     } catch (SecurityException e) {
392                         EventLog.writeEvent(0x534e4554, "62347125", Binder.getCallingUid(),
393                                 "getAllPhoneAccounts");
394                         throw e;
395                     }
396 
397                     final UserHandle callingUserHandle = Binder.getCallingUserHandle();
398                     long token = Binder.clearCallingIdentity();
399                     try {
400                         return mPhoneAccountRegistrar.getAllPhoneAccounts(callingUserHandle);
401                     } catch (Exception e) {
402                         Log.e(this, e, "getAllPhoneAccounts");
403                         throw e;
404                     } finally {
405                         Binder.restoreCallingIdentity(token);
406                     }
407                 } finally {
408                     Log.endSession();
409                 }
410             }
411         }
412 
413         @Override
414         public List<PhoneAccountHandle> getAllPhoneAccountHandles() {
415             try {
416                 Log.startSession("TSI.gAPAH");
417                 try {
418                     enforceModifyPermission(
419                             "getAllPhoneAccountHandles requires MODIFY_PHONE_STATE permission.");
420                 } catch (SecurityException e) {
421                     EventLog.writeEvent(0x534e4554, "62347125", Binder.getCallingUid(),
422                             "getAllPhoneAccountHandles");
423                     throw e;
424                 }
425 
426                 synchronized (mLock) {
427                     final UserHandle callingUserHandle = Binder.getCallingUserHandle();
428                     long token = Binder.clearCallingIdentity();
429                     try {
430                         return mPhoneAccountRegistrar.getAllPhoneAccountHandles(callingUserHandle);
431                     } catch (Exception e) {
432                         Log.e(this, e, "getAllPhoneAccounts");
433                         throw e;
434                     } finally {
435                         Binder.restoreCallingIdentity(token);
436                     }
437                 }
438             } finally {
439                 Log.endSession();
440             }
441         }
442 
443         @Override
444         public PhoneAccountHandle getSimCallManager(int subId) {
445             synchronized (mLock) {
446                 try {
447                     Log.startSession("TSI.gSCM");
448                     final int callingUid = Binder.getCallingUid();
449                     final int user = UserHandle.getUserId(callingUid);
450                     long token = Binder.clearCallingIdentity();
451                     try {
452                         if (user != ActivityManager.getCurrentUser()) {
453                             enforceCrossUserPermission(callingUid);
454                         }
455                         return mPhoneAccountRegistrar.getSimCallManager(subId, UserHandle.of(user));
456                     } finally {
457                         Binder.restoreCallingIdentity(token);
458                     }
459                 } catch (Exception e) {
460                     Log.e(this, e, "getSimCallManager");
461                     throw e;
462                 } finally {
463                     Log.endSession();
464                 }
465             }
466         }
467 
468         @Override
469         public PhoneAccountHandle getSimCallManagerForUser(int user) {
470             synchronized (mLock) {
471                 try {
472                     Log.startSession("TSI.gSCMFU");
473                     final int callingUid = Binder.getCallingUid();
474                     if (user != ActivityManager.getCurrentUser()) {
475                         enforceCrossUserPermission(callingUid);
476                     }
477                     long token = Binder.clearCallingIdentity();
478                     try {
479                         return mPhoneAccountRegistrar.getSimCallManager(UserHandle.of(user));
480                     } finally {
481                         Binder.restoreCallingIdentity(token);
482                     }
483                 } catch (Exception e) {
484                     Log.e(this, e, "getSimCallManager");
485                     throw e;
486                 } finally {
487                     Log.endSession();
488                 }
489             }
490         }
491 
492         @Override
493         public void registerPhoneAccount(PhoneAccount account) {
494             try {
495                 Log.startSession("TSI.rPA");
496                 synchronized (mLock) {
497                     if (!((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE))
498                                 .isVoiceCapable()) {
499                         Log.w(this,
500                                 "registerPhoneAccount not allowed on non-voice capable device.");
501                         return;
502                     }
503                     try {
504                         enforcePhoneAccountModificationForPackage(
505                                 account.getAccountHandle().getComponentName().getPackageName());
506                         if (account.hasCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)) {
507                             enforceRegisterSelfManaged();
508                             if (account.hasCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER) ||
509                                     account.hasCapabilities(
510                                             PhoneAccount.CAPABILITY_CONNECTION_MANAGER) ||
511                                     account.hasCapabilities(
512                                             PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
513                                 throw new SecurityException("Self-managed ConnectionServices " +
514                                         "cannot also be call capable, connection managers, or " +
515                                         "SIM accounts.");
516                             }
517 
518                             // For self-managed CS, the phone account registrar will override the
519                             // label the user has set for the phone account.  This ensures the
520                             // self-managed cs implementation can't spoof their app name.
521                         }
522                         if (account.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
523                             enforceRegisterSimSubscriptionPermission();
524                         }
525                         if (account.hasCapabilities(PhoneAccount.CAPABILITY_MULTI_USER)) {
526                             enforceRegisterMultiUser();
527                         }
528                         Bundle extras = account.getExtras();
529                         if (extras != null
530                                 && extras.getBoolean(PhoneAccount.EXTRA_SKIP_CALL_FILTERING)) {
531                             enforceRegisterSkipCallFiltering();
532                         }
533                         final int callingUid = Binder.getCallingUid();
534                         if (callingUid != Process.SHELL_UID) {
535                             enforceUserHandleMatchesCaller(account.getAccountHandle());
536                         }
537 
538                         if (TextUtils.isEmpty(account.getGroupId())
539                                 && mContext.checkCallingOrSelfPermission(MODIFY_PHONE_STATE)
540                                 != PackageManager.PERMISSION_GRANTED) {
541                             Log.w(this, "registerPhoneAccount - attempt to set a"
542                                     + " group from a non-system caller.");
543                             // Not permitted to set group, so null it out.
544                             account = new PhoneAccount.Builder(account)
545                                     .setGroupId(null)
546                                     .build();
547                         }
548 
549                         final long token = Binder.clearCallingIdentity();
550                         try {
551                             mPhoneAccountRegistrar.registerPhoneAccount(account);
552                         } finally {
553                             Binder.restoreCallingIdentity(token);
554                         }
555                     } catch (Exception e) {
556                         Log.e(this, e, "registerPhoneAccount %s", account);
557                         throw e;
558                     }
559                 }
560             } finally {
561                 Log.endSession();
562             }
563         }
564 
565         @Override
566         public void unregisterPhoneAccount(PhoneAccountHandle accountHandle) {
567             synchronized (mLock) {
568                 try {
569                     Log.startSession("TSI.uPA");
570                     enforcePhoneAccountModificationForPackage(
571                             accountHandle.getComponentName().getPackageName());
572                     enforceUserHandleMatchesCaller(accountHandle);
573                     final long token = Binder.clearCallingIdentity();
574                     try {
575                         mPhoneAccountRegistrar.unregisterPhoneAccount(accountHandle);
576                     } finally {
577                         Binder.restoreCallingIdentity(token);
578                     }
579                 } catch (Exception e) {
580                     Log.e(this, e, "unregisterPhoneAccount %s", accountHandle);
581                     throw e;
582                 } finally {
583                     Log.endSession();
584                 }
585             }
586         }
587 
588         @Override
589         public void clearAccounts(String packageName) {
590             synchronized (mLock) {
591                 try {
592                     Log.startSession("TSI.cA");
593                     enforcePhoneAccountModificationForPackage(packageName);
594                     mPhoneAccountRegistrar
595                             .clearAccounts(packageName, Binder.getCallingUserHandle());
596                 } catch (Exception e) {
597                     Log.e(this, e, "clearAccounts %s", packageName);
598                     throw e;
599                 } finally {
600                     Log.endSession();
601                 }
602             }
603         }
604 
605         /**
606          * @see android.telecom.TelecomManager#isVoiceMailNumber
607          */
608         @Override
609         public boolean isVoiceMailNumber(PhoneAccountHandle accountHandle, String number,
610                 String callingPackage, String callingFeatureId) {
611             try {
612                 Log.startSession("TSI.iVMN");
613                 synchronized (mLock) {
614                     if (!canReadPhoneState(callingPackage, callingFeatureId, "isVoiceMailNumber")) {
615                         return false;
616                     }
617                     final UserHandle callingUserHandle = Binder.getCallingUserHandle();
618                     if (!isPhoneAccountHandleVisibleToCallingUser(accountHandle,
619                             callingUserHandle)) {
620                         Log.d(this, "%s is not visible for the calling user [iVMN]", accountHandle);
621                         return false;
622                     }
623                     long token = Binder.clearCallingIdentity();
624                     try {
625                         return mPhoneAccountRegistrar.isVoiceMailNumber(accountHandle, number);
626                     } catch (Exception e) {
627                         Log.e(this, e, "getSubscriptionIdForPhoneAccount");
628                         throw e;
629                     } finally {
630                         Binder.restoreCallingIdentity(token);
631                     }
632                 }
633             } finally {
634                 Log.endSession();
635             }
636         }
637 
638         /**
639          * @see android.telecom.TelecomManager#getVoiceMailNumber
640          */
641         @Override
642         public String getVoiceMailNumber(PhoneAccountHandle accountHandle, String callingPackage,
643                 String callingFeatureId) {
644             try {
645                 Log.startSession("TSI.gVMN");
646                 if (!canReadPhoneState(callingPackage, callingFeatureId, "getVoiceMailNumber")) {
647                     return null;
648                 }
649                 try {
650                     final UserHandle callingUserHandle = Binder.getCallingUserHandle();
651                     if (!isPhoneAccountHandleVisibleToCallingUser(accountHandle,
652                             callingUserHandle)) {
653                         Log.d(this, "%s is not visible for the calling user [gVMN]",
654                                 accountHandle);
655                         return null;
656                     }
657                     int subId = mSubscriptionManagerAdapter.getDefaultVoiceSubId();
658                     synchronized (mLock) {
659                         if (accountHandle != null) {
660                             subId = mPhoneAccountRegistrar
661                                     .getSubscriptionIdForPhoneAccount(accountHandle);
662                         }
663                     }
664                     return getTelephonyManager(subId).getVoiceMailNumber();
665                 } catch (Exception e) {
666                     Log.e(this, e, "getSubscriptionIdForPhoneAccount");
667                     throw e;
668                 }
669             } finally {
670                 Log.endSession();
671             }
672         }
673 
674         /**
675          * @see android.telecom.TelecomManager#getLine1Number
676          */
677         @Override
678         public String getLine1Number(PhoneAccountHandle accountHandle, String callingPackage,
679                 String callingFeatureId) {
680             try {
681                 Log.startSession("getL1N");
682                 if (!canReadPhoneNumbers(callingPackage, callingFeatureId, "getLine1Number")) {
683                     return null;
684                 }
685 
686                 final UserHandle callingUserHandle = Binder.getCallingUserHandle();
687                 if (!isPhoneAccountHandleVisibleToCallingUser(accountHandle,
688                         callingUserHandle)) {
689                     Log.d(this, "%s is not visible for the calling user [gL1N]", accountHandle);
690                     return null;
691                 }
692 
693                 long token = Binder.clearCallingIdentity();
694                 try {
695                     int subId;
696                     synchronized (mLock) {
697                         subId = mPhoneAccountRegistrar.getSubscriptionIdForPhoneAccount(
698                                 accountHandle);
699                     }
700                     return getTelephonyManager(subId).getLine1Number();
701                 } catch (Exception e) {
702                     Log.e(this, e, "getSubscriptionIdForPhoneAccount");
703                     throw e;
704                 } finally {
705                     Binder.restoreCallingIdentity(token);
706                 }
707             } finally {
708                 Log.endSession();
709             }
710         }
711 
712         /**
713          * @see android.telecom.TelecomManager#silenceRinger
714          */
715         @Override
716         public void silenceRinger(String callingPackage) {
717             try {
718                 Log.startSession("TSI.sR");
719                 synchronized (mLock) {
720                     enforcePermissionOrPrivilegedDialer(MODIFY_PHONE_STATE, callingPackage);
721 
722                     long token = Binder.clearCallingIdentity();
723                     try {
724                         Log.i(this, "Silence Ringer requested by %s", callingPackage);
725                         mCallsManager.getCallAudioManager().silenceRingers();
726                         mCallsManager.getInCallController().silenceRinger();
727                     } finally {
728                         Binder.restoreCallingIdentity(token);
729                     }
730                 }
731             } finally {
732                 Log.endSession();
733             }
734         }
735 
736         /**
737          * @see android.telecom.TelecomManager#getDefaultPhoneApp
738          * @deprecated - Use {@link android.telecom.TelecomManager#getDefaultDialerPackage()}
739          *         instead.
740          */
741         @Override
742         public ComponentName getDefaultPhoneApp() {
743             try {
744                 Log.startSession("TSI.gDPA");
745                 return mDefaultDialerCache.getDialtactsSystemDialerComponent();
746             } finally {
747                 Log.endSession();
748             }
749         }
750 
751         /**
752          * @return the package name of the current user-selected default dialer. If no default
753          *         has been selected, the package name of the system dialer is returned. If
754          *         neither exists, then {@code null} is returned.
755          * @see android.telecom.TelecomManager#getDefaultDialerPackage
756          */
757         @Override
758         public String getDefaultDialerPackage() {
759             try {
760                 Log.startSession("TSI.gDDP");
761                 final long token = Binder.clearCallingIdentity();
762                 try {
763                     return mDefaultDialerCache.getDefaultDialerApplication(
764                             ActivityManager.getCurrentUser());
765                 } finally {
766                     Binder.restoreCallingIdentity(token);
767                 }
768             } finally {
769                 Log.endSession();
770             }
771         }
772 
773         /**
774          * @param userId user id to get the default dialer package for
775          * @return the package name of the current user-selected default dialer. If no default
776          *         has been selected, the package name of the system dialer is returned. If
777          *         neither exists, then {@code null} is returned.
778          * @see android.telecom.TelecomManager#getDefaultDialerPackage
779          */
780         @Override
781         public String getDefaultDialerPackageForUser(int userId) {
782             try {
783                 Log.startSession("TSI.gDDPU");
784                 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE,
785                         "READ_PRIVILEGED_PHONE_STATE permission required.");
786 
787                 final long token = Binder.clearCallingIdentity();
788                 try {
789                     return mDefaultDialerCache.getDefaultDialerApplication(userId);
790                 } finally {
791                     Binder.restoreCallingIdentity(token);
792                 }
793             } finally {
794                 Log.endSession();
795             }
796         }
797 
798         /**
799          * @see android.telecom.TelecomManager#getSystemDialerPackage
800          */
801         @Override
802         public String getSystemDialerPackage() {
803             try {
804                 Log.startSession("TSI.gSDP");
805                 return mDefaultDialerCache.getSystemDialerApplication();
806             } finally {
807                 Log.endSession();
808             }
809         }
810 
811         public void setSystemDialer(ComponentName testComponentName) {
812             try {
813                 Log.startSession("TSI.sSD");
814                 enforceModifyPermission();
815                 enforceShellOnly(Binder.getCallingUid(), "setSystemDialer");
816                 synchronized (mLock) {
817                     long token = Binder.clearCallingIdentity();
818                     try {
819                         mDefaultDialerCache.setSystemDialerComponentName(testComponentName);
820                     } finally {
821                         Binder.restoreCallingIdentity(token);
822                     }
823                 }
824             } finally {
825                 Log.endSession();
826             }
827         }
828 
829         /**
830          * @see android.telecom.TelecomManager#isInCall
831          */
832         @Override
833         public boolean isInCall(String callingPackage, String callingFeatureId) {
834             try {
835                 Log.startSession("TSI.iIC");
836                 if (!canReadPhoneState(callingPackage, callingFeatureId, "isInCall")) {
837                     return false;
838                 }
839 
840                 synchronized (mLock) {
841                     return mCallsManager.hasOngoingCalls();
842                 }
843             } finally {
844                 Log.endSession();
845             }
846         }
847 
848         /**
849          * @see android.telecom.TelecomManager#hasManageOngoingCallsPermission
850          */
851         @Override
852         public boolean hasManageOngoingCallsPermission(String callingPackage) {
853             try {
854                 Log.startSession("TSI.hMOCP");
855                 return PermissionChecker.checkPermissionForDataDeliveryFromDataSource(
856                         mContext, Manifest.permission.MANAGE_ONGOING_CALLS,
857                         Binder.getCallingPid(),
858                         new AttributionSource(mContext.getAttributionSource(),
859                                 new AttributionSource(Binder.getCallingUid(),
860                                         callingPackage, /*attributionTag*/ null)),
861                         "Checking whether the caller has MANAGE_ONGOING_CALLS permission")
862                                 == PermissionChecker.PERMISSION_GRANTED;
863             } finally {
864                 Log.endSession();
865             }
866         }
867 
868         /**
869          * @see android.telecom.TelecomManager#isInManagedCall
870          */
871         @Override
872         public boolean isInManagedCall(String callingPackage, String callingFeatureId) {
873             try {
874                 Log.startSession("TSI.iIMC");
875                 if (!canReadPhoneState(callingPackage, callingFeatureId, "isInManagedCall")) {
876                     throw new SecurityException("Only the default dialer or caller with " +
877                             "READ_PHONE_STATE permission can use this method.");
878                 }
879 
880                 synchronized (mLock) {
881                     return mCallsManager.hasOngoingManagedCalls();
882                 }
883             } finally {
884                 Log.endSession();
885             }
886         }
887 
888         /**
889          * @see android.telecom.TelecomManager#isRinging
890          */
891         @Override
892         public boolean isRinging(String callingPackage) {
893             try {
894                 Log.startSession("TSI.iR");
895                 if (!isPrivilegedDialerCalling(callingPackage)) {
896                     try {
897                         enforceModifyPermission(
898                                 "isRinging requires MODIFY_PHONE_STATE permission.");
899                     } catch (SecurityException e) {
900                         EventLog.writeEvent(0x534e4554, "62347125", "isRinging: " + callingPackage);
901                         throw e;
902                     }
903                 }
904 
905                 synchronized (mLock) {
906                     // Note: We are explicitly checking the calls telecom is tracking rather than
907                     // relying on mCallsManager#getCallState(). Since getCallState() relies on the
908                     // current state as tracked by PhoneStateBroadcaster, any failure to properly
909                     // track the current call state there could result in the wrong ringing state
910                     // being reported by this API.
911                     return mCallsManager.hasRingingOrSimulatedRingingCall();
912                 }
913             } finally {
914                 Log.endSession();
915             }
916         }
917 
918         /**
919          * @see TelecomManager#getCallState()
920          * @deprecated this is only being kept due to an @UnsupportedAppUsage tag. Apps targeting
921          * API 31+ must use {@link #getCallStateUsingPackage(String, String)} below.
922          */
923         @Deprecated
924         @Override
925         public int getCallState() {
926             try {
927                 Log.startSession("TSI.getCallState(DEPRECATED)");
928                 if (CompatChanges.isChangeEnabled(
929                         TelecomManager.ENABLE_GET_CALL_STATE_PERMISSION_PROTECTION,
930                         Binder.getCallingUid())) {
931                     // Do not allow this API to be called on API version 31+, it should only be
932                     // called on old apps using this Binder call directly.
933                     throw new SecurityException("This method can only be used for applications "
934                             + "targeting API version 30 or less.");
935                 }
936                 synchronized (mLock) {
937                     return mCallsManager.getCallState();
938                 }
939             } finally {
940                 Log.endSession();
941             }
942         }
943 
944         /**
945          * @see TelecomManager#getCallState()
946          */
947         @Override
948         public int getCallStateUsingPackage(String callingPackage, String callingFeatureId) {
949             try {
950                 Log.startSession("TSI.getCallStateUsingPackage");
951                 if (CompatChanges.isChangeEnabled(
952                         TelecomManager.ENABLE_GET_CALL_STATE_PERMISSION_PROTECTION, callingPackage,
953                         Binder.getCallingUserHandle())) {
954                     // Bypass canReadPhoneState check if this is being called from SHELL UID
955                     if (Binder.getCallingUid() != Process.SHELL_UID && !canReadPhoneState(
956                             callingPackage, callingFeatureId, "getCallState")) {
957                         throw new SecurityException("getCallState API requires READ_PHONE_STATE"
958                                 + " for API version 31+");
959                     }
960                 }
961                 synchronized (mLock) {
962                     return mCallsManager.getCallState();
963                 }
964             } finally {
965                 Log.endSession();
966             }
967         }
968 
969         /**
970          * @see android.telecom.TelecomManager#endCall
971          */
972         @Override
973         public boolean endCall(String callingPackage) {
974             try {
975                 Log.startSession("TSI.eC");
976                 synchronized (mLock) {
977                     if (!enforceAnswerCallPermission(callingPackage, Binder.getCallingUid())) {
978                         throw new SecurityException("requires ANSWER_PHONE_CALLS permission");
979                     }
980 
981                     long token = Binder.clearCallingIdentity();
982                     try {
983                         return endCallInternal(callingPackage);
984                     } finally {
985                         Binder.restoreCallingIdentity(token);
986                     }
987                 }
988             } finally {
989                 Log.endSession();
990             }
991         }
992 
993         /**
994          * @see android.telecom.TelecomManager#acceptRingingCall
995          */
996         @Override
997         public void acceptRingingCall(String packageName) {
998             try {
999                 Log.startSession("TSI.aRC");
1000                 synchronized (mLock) {
1001                     if (!enforceAnswerCallPermission(packageName, Binder.getCallingUid())) return;
1002 
1003                     long token = Binder.clearCallingIdentity();
1004                     try {
1005                         acceptRingingCallInternal(DEFAULT_VIDEO_STATE, packageName);
1006                     } finally {
1007                         Binder.restoreCallingIdentity(token);
1008                     }
1009                 }
1010             } finally {
1011                 Log.endSession();
1012             }
1013         }
1014 
1015         /**
1016          * @see android.telecom.TelecomManager#acceptRingingCall(int)
1017          *
1018          */
1019         @Override
1020         public void acceptRingingCallWithVideoState(String packageName, int videoState) {
1021             try {
1022                 Log.startSession("TSI.aRCWVS");
1023                 synchronized (mLock) {
1024                     if (!enforceAnswerCallPermission(packageName, Binder.getCallingUid())) return;
1025 
1026                     long token = Binder.clearCallingIdentity();
1027                     try {
1028                         acceptRingingCallInternal(videoState, packageName);
1029                     } finally {
1030                         Binder.restoreCallingIdentity(token);
1031                     }
1032                 }
1033             } finally {
1034                 Log.endSession();
1035             }
1036         }
1037 
1038         /**
1039          * @see android.telecom.TelecomManager#showInCallScreen
1040          */
1041         @Override
1042         public void showInCallScreen(boolean showDialpad, String callingPackage,
1043                 String callingFeatureId) {
1044             try {
1045                 Log.startSession("TSI.sICS");
1046                 if (!canReadPhoneState(callingPackage, callingFeatureId, "showInCallScreen")) {
1047                     return;
1048                 }
1049 
1050                 synchronized (mLock) {
1051 
1052                     long token = Binder.clearCallingIdentity();
1053                     try {
1054                         mCallsManager.getInCallController().bringToForeground(showDialpad);
1055                     } finally {
1056                         Binder.restoreCallingIdentity(token);
1057                     }
1058                 }
1059             } finally {
1060                 Log.endSession();
1061             }
1062         }
1063 
1064         /**
1065          * @see android.telecom.TelecomManager#cancelMissedCallsNotification
1066          */
1067         @Override
1068         public void cancelMissedCallsNotification(String callingPackage) {
1069             try {
1070                 Log.startSession("TSI.cMCN");
1071                 synchronized (mLock) {
1072                     enforcePermissionOrPrivilegedDialer(MODIFY_PHONE_STATE, callingPackage);
1073                     UserHandle userHandle = Binder.getCallingUserHandle();
1074                     long token = Binder.clearCallingIdentity();
1075                     try {
1076                         mCallsManager.getMissedCallNotifier().clearMissedCalls(userHandle);
1077                     } finally {
1078                         Binder.restoreCallingIdentity(token);
1079                     }
1080                 }
1081             } finally {
1082                 Log.endSession();
1083             }
1084         }
1085         /**
1086          * @see android.telecom.TelecomManager#handleMmi
1087          */
1088         @Override
1089         public boolean handlePinMmi(String dialString, String callingPackage) {
1090             try {
1091                 Log.startSession("TSI.hPM");
1092                 enforcePermissionOrPrivilegedDialer(MODIFY_PHONE_STATE, callingPackage);
1093 
1094                 // Switch identity so that TelephonyManager checks Telecom's permissions
1095                 // instead.
1096                 long token = Binder.clearCallingIdentity();
1097                 boolean retval = false;
1098                 try {
1099                     retval = getTelephonyManager(
1100                             SubscriptionManager.getDefaultVoiceSubscriptionId())
1101                             .handlePinMmi(dialString);
1102                 } finally {
1103                     Binder.restoreCallingIdentity(token);
1104                 }
1105 
1106                 return retval;
1107             }finally {
1108                 Log.endSession();
1109             }
1110         }
1111 
1112         /**
1113          * @see android.telecom.TelecomManager#handleMmi
1114          */
1115         @Override
1116         public boolean handlePinMmiForPhoneAccount(PhoneAccountHandle accountHandle,
1117                 String dialString, String callingPackage) {
1118             try {
1119                 Log.startSession("TSI.hPMFPA");
1120 
1121                 enforcePermissionOrPrivilegedDialer(MODIFY_PHONE_STATE, callingPackage);
1122                 UserHandle callingUserHandle = Binder.getCallingUserHandle();
1123                 synchronized (mLock) {
1124                     if (!isPhoneAccountHandleVisibleToCallingUser(accountHandle,
1125                             callingUserHandle)) {
1126                         Log.d(this, "%s is not visible for the calling user [hMMI]",
1127                                 accountHandle);
1128                         return false;
1129                     }
1130                 }
1131 
1132                 // Switch identity so that TelephonyManager checks Telecom's permissions
1133                 // instead.
1134                 long token = Binder.clearCallingIdentity();
1135                 boolean retval = false;
1136                 int subId;
1137                 try {
1138                     synchronized (mLock) {
1139                         subId = mPhoneAccountRegistrar.getSubscriptionIdForPhoneAccount(
1140                                 accountHandle);
1141                     }
1142                     retval = getTelephonyManager(subId)
1143                             .handlePinMmiForSubscriber(subId, dialString);
1144                 } finally {
1145                     Binder.restoreCallingIdentity(token);
1146                 }
1147                 return retval;
1148             }finally {
1149                 Log.endSession();
1150             }
1151         }
1152 
1153         /**
1154          * @see android.telecom.TelecomManager#getAdnUriForPhoneAccount
1155          */
1156         @Override
1157         public Uri getAdnUriForPhoneAccount(PhoneAccountHandle accountHandle,
1158                 String callingPackage) {
1159             try {
1160                 Log.startSession("TSI.aAUFPA");
1161                 enforcePermissionOrPrivilegedDialer(MODIFY_PHONE_STATE, callingPackage);
1162                 synchronized (mLock) {
1163                     if (!isPhoneAccountHandleVisibleToCallingUser(accountHandle,
1164                             Binder.getCallingUserHandle())) {
1165                         Log.d(this, "%s is not visible for the calling user [gA4PA]",
1166                                 accountHandle);
1167                         return null;
1168                     }
1169                 }
1170                 // Switch identity so that TelephonyManager checks Telecom's permissions
1171                 // instead.
1172                 long token = Binder.clearCallingIdentity();
1173                 String retval = "content://icc/adn/";
1174                 try {
1175                     long subId = mPhoneAccountRegistrar
1176                             .getSubscriptionIdForPhoneAccount(accountHandle);
1177                     retval = retval + "subId/" + subId;
1178                 } finally {
1179                     Binder.restoreCallingIdentity(token);
1180                 }
1181 
1182                 return Uri.parse(retval);
1183             } finally {
1184                 Log.endSession();
1185             }
1186         }
1187 
1188         /**
1189          * @see android.telecom.TelecomManager#isTtySupported
1190          */
1191         @Override
1192         public boolean isTtySupported(String callingPackage, String callingFeatureId) {
1193             try {
1194                 Log.startSession("TSI.iTS");
1195                 if (!canReadPhoneState(callingPackage, callingFeatureId, "isTtySupported")) {
1196                     throw new SecurityException("Only default dialer or an app with" +
1197                             "READ_PRIVILEGED_PHONE_STATE or READ_PHONE_STATE can call this api");
1198                 }
1199 
1200                 synchronized (mLock) {
1201                     return mCallsManager.isTtySupported();
1202                 }
1203             } finally {
1204                 Log.endSession();
1205             }
1206         }
1207 
1208         /**
1209          * @see android.telecom.TelecomManager#getCurrentTtyMode
1210          */
1211         @Override
1212         public int getCurrentTtyMode(String callingPackage, String callingFeatureId) {
1213             try {
1214                 Log.startSession("TSI.gCTM");
1215                 if (!canReadPhoneState(callingPackage, callingFeatureId, "getCurrentTtyMode")) {
1216                     return TelecomManager.TTY_MODE_OFF;
1217                 }
1218 
1219                 synchronized (mLock) {
1220                     return mCallsManager.getCurrentTtyMode();
1221                 }
1222             } finally {
1223                 Log.endSession();
1224             }
1225         }
1226 
1227         /**
1228          * @see android.telecom.TelecomManager#addNewIncomingCall
1229          */
1230         @Override
1231         public void addNewIncomingCall(PhoneAccountHandle phoneAccountHandle, Bundle extras) {
1232             try {
1233                 Log.startSession("TSI.aNIC");
1234                 synchronized (mLock) {
1235                     Log.i(this, "Adding new incoming call with phoneAccountHandle %s",
1236                             phoneAccountHandle);
1237                     if (phoneAccountHandle != null &&
1238                             phoneAccountHandle.getComponentName() != null) {
1239                         if (isCallerSimCallManager(phoneAccountHandle)
1240                                 && TelephonyUtil.isPstnComponentName(
1241                                         phoneAccountHandle.getComponentName())) {
1242                             Log.v(this, "Allowing call manager to add incoming call with PSTN" +
1243                                     " handle");
1244                         } else {
1245                             mAppOpsManager.checkPackage(
1246                                     Binder.getCallingUid(),
1247                                     phoneAccountHandle.getComponentName().getPackageName());
1248                             // Make sure it doesn't cross the UserHandle boundary
1249                             enforceUserHandleMatchesCaller(phoneAccountHandle);
1250                             enforcePhoneAccountIsRegisteredEnabled(phoneAccountHandle,
1251                                     Binder.getCallingUserHandle());
1252                             if (isSelfManagedConnectionService(phoneAccountHandle)) {
1253                                 // Self-managed phone account, ensure it has MANAGE_OWN_CALLS.
1254                                 mContext.enforceCallingOrSelfPermission(
1255                                         android.Manifest.permission.MANAGE_OWN_CALLS,
1256                                         "Self-managed phone accounts must have MANAGE_OWN_CALLS " +
1257                                                 "permission.");
1258 
1259                                 // Self-managed ConnectionServices can ONLY add new incoming calls
1260                                 // using their own PhoneAccounts.  The checkPackage(..) app opps
1261                                 // check above ensures this.
1262                             }
1263                         }
1264                         long token = Binder.clearCallingIdentity();
1265                         try {
1266                             Intent intent = new Intent(TelecomManager.ACTION_INCOMING_CALL);
1267                             intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,
1268                                     phoneAccountHandle);
1269                             intent.putExtra(CallIntentProcessor.KEY_IS_INCOMING_CALL, true);
1270                             if (extras != null) {
1271                                 extras.setDefusable(true);
1272                                 intent.putExtra(TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, extras);
1273                             }
1274                             mCallIntentProcessorAdapter.processIncomingCallIntent(
1275                                     mCallsManager, intent);
1276                         } finally {
1277                             Binder.restoreCallingIdentity(token);
1278                         }
1279                     } else {
1280                         Log.w(this, "Null phoneAccountHandle. Ignoring request to add new" +
1281                                 " incoming call");
1282                     }
1283                 }
1284             } finally {
1285                 Log.endSession();
1286             }
1287         }
1288 
1289         /**
1290          * @see android.telecom.TelecomManager#addNewIncomingConference
1291          */
1292         @Override
1293         public void addNewIncomingConference(PhoneAccountHandle phoneAccountHandle, Bundle extras) {
1294             try {
1295                 Log.startSession("TSI.aNIC");
1296                 synchronized (mLock) {
1297                     Log.i(this, "Adding new incoming conference with phoneAccountHandle %s",
1298                             phoneAccountHandle);
1299                     if (phoneAccountHandle != null &&
1300                             phoneAccountHandle.getComponentName() != null) {
1301                         if (isCallerSimCallManager(phoneAccountHandle)
1302                                 && TelephonyUtil.isPstnComponentName(
1303                                         phoneAccountHandle.getComponentName())) {
1304                             Log.v(this, "Allowing call manager to add incoming conference" +
1305                                     " with PSTN handle");
1306                         } else {
1307                             mAppOpsManager.checkPackage(
1308                                     Binder.getCallingUid(),
1309                                     phoneAccountHandle.getComponentName().getPackageName());
1310                             // Make sure it doesn't cross the UserHandle boundary
1311                             enforceUserHandleMatchesCaller(phoneAccountHandle);
1312                             enforcePhoneAccountIsRegisteredEnabled(phoneAccountHandle,
1313                                     Binder.getCallingUserHandle());
1314                             if (isSelfManagedConnectionService(phoneAccountHandle)) {
1315                                 throw new SecurityException("Self-Managed ConnectionServices cannot add "
1316                                         + "adhoc conference calls");
1317                             }
1318                         }
1319                         long token = Binder.clearCallingIdentity();
1320                         try {
1321                             mCallsManager.processIncomingConference(
1322                                     phoneAccountHandle, extras);
1323                         } finally {
1324                             Binder.restoreCallingIdentity(token);
1325                         }
1326                     } else {
1327                         Log.w(this, "Null phoneAccountHandle. Ignoring request to add new" +
1328                                 " incoming conference");
1329                     }
1330                 }
1331             } finally {
1332                 Log.endSession();
1333             }
1334         }
1335 
1336 
1337         /**
1338          * @see android.telecom.TelecomManager#acceptHandover
1339          */
1340         @Override
1341         public void acceptHandover(Uri srcAddr, int videoState, PhoneAccountHandle destAcct) {
1342             try {
1343                 Log.startSession("TSI.aHO");
1344                 synchronized (mLock) {
1345                     Log.i(this, "acceptHandover; srcAddr=%s, videoState=%s, dest=%s",
1346                             Log.pii(srcAddr), VideoProfile.videoStateToString(videoState),
1347                             destAcct);
1348 
1349                     if (destAcct != null && destAcct.getComponentName() != null) {
1350                         mAppOpsManager.checkPackage(
1351                                 Binder.getCallingUid(),
1352                                 destAcct.getComponentName().getPackageName());
1353                         enforceUserHandleMatchesCaller(destAcct);
1354                         enforcePhoneAccountIsRegisteredEnabled(destAcct,
1355                                 Binder.getCallingUserHandle());
1356                         if (isSelfManagedConnectionService(destAcct)) {
1357                             // Self-managed phone account, ensure it has MANAGE_OWN_CALLS.
1358                             mContext.enforceCallingOrSelfPermission(
1359                                     android.Manifest.permission.MANAGE_OWN_CALLS,
1360                                     "Self-managed phone accounts must have MANAGE_OWN_CALLS " +
1361                                             "permission.");
1362                         }
1363                         if (!enforceAcceptHandoverPermission(
1364                                 destAcct.getComponentName().getPackageName(),
1365                                 Binder.getCallingUid())) {
1366                             throw new SecurityException("App must be granted runtime "
1367                                     + "ACCEPT_HANDOVER permission.");
1368                         }
1369 
1370                         long token = Binder.clearCallingIdentity();
1371                         try {
1372                             mCallsManager.acceptHandover(srcAddr, videoState, destAcct);
1373                         } finally {
1374                             Binder.restoreCallingIdentity(token);
1375                         }
1376                     } else {
1377                         Log.w(this, "Null phoneAccountHandle. Ignoring request " +
1378                                 "to handover the call");
1379                     }
1380                 }
1381             } finally {
1382                 Log.endSession();
1383             }
1384         }
1385 
1386         /**
1387          * @see android.telecom.TelecomManager#addNewUnknownCall
1388          */
1389         @Override
1390         public void addNewUnknownCall(PhoneAccountHandle phoneAccountHandle, Bundle extras) {
1391             try {
1392                 Log.startSession("TSI.aNUC");
1393                 try {
1394                     enforceModifyPermission(
1395                             "addNewUnknownCall requires MODIFY_PHONE_STATE permission.");
1396                 } catch (SecurityException e) {
1397                     EventLog.writeEvent(0x534e4554, "62347125", Binder.getCallingUid(),
1398                             "addNewUnknownCall");
1399                     throw e;
1400                 }
1401 
1402                 synchronized (mLock) {
1403                     if (phoneAccountHandle != null &&
1404                             phoneAccountHandle.getComponentName() != null) {
1405                         mAppOpsManager.checkPackage(
1406                                 Binder.getCallingUid(),
1407                                 phoneAccountHandle.getComponentName().getPackageName());
1408 
1409                         // Make sure it doesn't cross the UserHandle boundary
1410                         enforceUserHandleMatchesCaller(phoneAccountHandle);
1411                         enforcePhoneAccountIsRegisteredEnabled(phoneAccountHandle,
1412                                 Binder.getCallingUserHandle());
1413                         long token = Binder.clearCallingIdentity();
1414 
1415                         try {
1416                             Intent intent = new Intent(TelecomManager.ACTION_NEW_UNKNOWN_CALL);
1417                             if (extras != null) {
1418                                 extras.setDefusable(true);
1419                                 intent.putExtras(extras);
1420                             }
1421                             intent.putExtra(CallIntentProcessor.KEY_IS_UNKNOWN_CALL, true);
1422                             intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,
1423                                     phoneAccountHandle);
1424                             mCallIntentProcessorAdapter.processUnknownCallIntent(mCallsManager, intent);
1425                         } finally {
1426                             Binder.restoreCallingIdentity(token);
1427                         }
1428                     } else {
1429                         Log.i(this,
1430                                 "Null phoneAccountHandle or not initiated by Telephony. " +
1431                                         "Ignoring request to add new unknown call.");
1432                     }
1433                 }
1434             } finally {
1435                 Log.endSession();
1436             }
1437         }
1438 
1439         /**
1440          * @see android.telecom.TelecomManager#startConference.
1441          */
1442         @Override
1443         public void startConference(List<Uri> participants, Bundle extras,
1444                 String callingPackage) {
1445             try {
1446                 Log.startSession("TSI.sC");
1447                 if (!canCallPhone(callingPackage, "startConference")) {
1448                     throw new SecurityException("Package " + callingPackage + " is not allowed"
1449                             + " to start conference call");
1450                 }
1451                 mCallsManager.startConference(participants, extras, callingPackage,
1452                         Binder.getCallingUserHandle());
1453             } finally {
1454                 Log.endSession();
1455             }
1456         }
1457 
1458         /**
1459          * @see android.telecom.TelecomManager#placeCall
1460          */
1461         @Override
1462         public void placeCall(Uri handle, Bundle extras, String callingPackage,
1463                 String callingFeatureId) {
1464             try {
1465                 Log.startSession("TSI.pC");
1466                 enforceCallingPackage(callingPackage);
1467 
1468                 PhoneAccountHandle phoneAccountHandle = null;
1469                 if (extras != null) {
1470                     phoneAccountHandle = extras.getParcelable(
1471                             TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
1472                     if (extras.containsKey(TelecomManager.EXTRA_IS_HANDOVER)) {
1473                         // This extra is for Telecom use only so should never be passed in.
1474                         extras.remove(TelecomManager.EXTRA_IS_HANDOVER);
1475                     }
1476                 }
1477                 boolean isSelfManaged = phoneAccountHandle != null &&
1478                         isSelfManagedConnectionService(phoneAccountHandle);
1479                 if (isSelfManaged) {
1480                     mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_OWN_CALLS,
1481                             "Self-managed ConnectionServices require MANAGE_OWN_CALLS permission.");
1482 
1483                     if (!callingPackage.equals(
1484                             phoneAccountHandle.getComponentName().getPackageName())
1485                             && !canCallPhone(callingPackage, callingFeatureId,
1486                             "CALL_PHONE permission required to place calls.")) {
1487                         // The caller is not allowed to place calls, so we want to ensure that it
1488                         // can only place calls through itself.
1489                         throw new SecurityException("Self-managed ConnectionServices can only "
1490                                 + "place calls through their own ConnectionService.");
1491                     }
1492                 } else if (!canCallPhone(callingPackage, callingFeatureId, "placeCall")) {
1493                     throw new SecurityException("Package " + callingPackage
1494                             + " is not allowed to place phone calls");
1495                 }
1496 
1497                 // Note: we can still get here for the default/system dialer, even if the Phone
1498                 // permission is turned off. This is because the default/system dialer is always
1499                 // allowed to attempt to place a call (regardless of permission state), in case
1500                 // it turns out to be an emergency call. If the permission is denied and the
1501                 // call is being made to a non-emergency number, the call will be denied later on
1502                 // by {@link UserCallIntentProcessor}.
1503 
1504                 final boolean hasCallAppOp = mAppOpsManager.noteOp(AppOpsManager.OP_CALL_PHONE,
1505                         Binder.getCallingUid(), callingPackage, callingFeatureId, null)
1506                         == AppOpsManager.MODE_ALLOWED;
1507 
1508                 final boolean hasCallPermission = mContext.checkCallingPermission(CALL_PHONE) ==
1509                         PackageManager.PERMISSION_GRANTED;
1510                 // The Emergency Dialer has call privileged permission and uses this to place
1511                 // emergency calls.  We ensure permission checks in
1512                 // NewOutgoingCallIntentBroadcaster#process pass by sending this to
1513                 // Telecom as an ACTION_CALL_PRIVILEGED intent (which makes sense since the
1514                 // com.android.phone process has that permission).
1515                 final boolean hasCallPrivilegedPermission = mContext.checkCallingPermission(
1516                         CALL_PRIVILEGED) == PackageManager.PERMISSION_GRANTED;
1517 
1518                 synchronized (mLock) {
1519                     final UserHandle userHandle = Binder.getCallingUserHandle();
1520                     long token = Binder.clearCallingIdentity();
1521                     try {
1522                         final Intent intent = new Intent(hasCallPrivilegedPermission ?
1523                                 Intent.ACTION_CALL_PRIVILEGED : Intent.ACTION_CALL, handle);
1524                         if (extras != null) {
1525                             extras.setDefusable(true);
1526                             intent.putExtras(extras);
1527                         }
1528                         mUserCallIntentProcessorFactory.create(mContext, userHandle)
1529                                 .processIntent(
1530                                         intent, callingPackage, isSelfManaged ||
1531                                                 (hasCallAppOp && hasCallPermission),
1532                                         true /* isLocalInvocation */);
1533                     } finally {
1534                         Binder.restoreCallingIdentity(token);
1535                     }
1536                 }
1537             } finally {
1538                 Log.endSession();
1539             }
1540         }
1541 
1542         /**
1543          * @see android.telecom.TelecomManager#enablePhoneAccount
1544          */
1545         @Override
1546         public boolean enablePhoneAccount(PhoneAccountHandle accountHandle, boolean isEnabled) {
1547             try {
1548                 Log.startSession("TSI.ePA");
1549                 enforceModifyPermission();
1550                 synchronized (mLock) {
1551                     long token = Binder.clearCallingIdentity();
1552                     try {
1553                         // enable/disable phone account
1554                         return mPhoneAccountRegistrar.enablePhoneAccount(accountHandle, isEnabled);
1555                     } finally {
1556                         Binder.restoreCallingIdentity(token);
1557                     }
1558                 }
1559             } finally {
1560                 Log.endSession();
1561             }
1562         }
1563 
1564         @Override
1565         public boolean setDefaultDialer(String packageName) {
1566             try {
1567                 Log.startSession("TSI.sDD");
1568                 enforcePermission(MODIFY_PHONE_STATE);
1569                 enforcePermission(WRITE_SECURE_SETTINGS);
1570                 synchronized (mLock) {
1571                     long token = Binder.clearCallingIdentity();
1572                     try {
1573                         return mDefaultDialerCache.setDefaultDialer(packageName,
1574                                 ActivityManager.getCurrentUser());
1575                     } finally {
1576                         Binder.restoreCallingIdentity(token);
1577                     }
1578                 }
1579             } finally {
1580                 Log.endSession();
1581             }
1582         }
1583 
1584         @Override
1585         public void stopBlockSuppression() {
1586             try {
1587                 Log.startSession("TSI.sBS");
1588                 enforceModifyPermission();
1589                 if (Binder.getCallingUid() != Process.SHELL_UID
1590                         && Binder.getCallingUid() != Process.ROOT_UID) {
1591                     throw new SecurityException("Shell-only API.");
1592                 }
1593                 synchronized (mLock) {
1594                     long token = Binder.clearCallingIdentity();
1595                     try {
1596                         BlockedNumberContract.SystemContract.endBlockSuppression(mContext);
1597                     } finally {
1598                         Binder.restoreCallingIdentity(token);
1599                     }
1600                 }
1601             } finally {
1602                 Log.endSession();
1603             }
1604         }
1605 
1606         @Override
1607         public TelecomAnalytics dumpCallAnalytics() {
1608             try {
1609                 Log.startSession("TSI.dCA");
1610                 enforcePermission(DUMP);
1611                 return Analytics.dumpToParcelableAnalytics();
1612             } finally {
1613                 Log.endSession();
1614             }
1615         }
1616 
1617         /**
1618          * Dumps the current state of the TelecomService.  Used when generating problem reports.
1619          *
1620          * @param fd The file descriptor.
1621          * @param writer The print writer to dump the state to.
1622          * @param args Optional dump arguments.
1623          */
1624         @Override
1625         protected void dump(FileDescriptor fd, final PrintWriter writer, String[] args) {
1626             if (mContext.checkCallingOrSelfPermission(
1627                     android.Manifest.permission.DUMP)
1628                     != PackageManager.PERMISSION_GRANTED) {
1629                 writer.println("Permission Denial: can't dump TelecomService " +
1630                         "from from pid=" + Binder.getCallingPid() + ", uid=" +
1631                         Binder.getCallingUid());
1632                 return;
1633             }
1634 
1635 
1636             if (args.length > 0 && Analytics.ANALYTICS_DUMPSYS_ARG.equals(args[0])) {
1637                 Binder.withCleanCallingIdentity(() ->
1638                         Analytics.dumpToEncodedProto(mContext, writer, args));
1639                 return;
1640             }
1641 
1642             boolean isTimeLineView = (args.length > 0 && TIME_LINE_ARG.equalsIgnoreCase(args[0]));
1643 
1644             final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1645             if (mCallsManager != null) {
1646                 pw.println("CallsManager: ");
1647                 pw.increaseIndent();
1648                 mCallsManager.dump(pw);
1649                 pw.decreaseIndent();
1650 
1651                 pw.println("PhoneAccountRegistrar: ");
1652                 pw.increaseIndent();
1653                 mPhoneAccountRegistrar.dump(pw);
1654                 pw.decreaseIndent();
1655 
1656                 pw.println("Analytics:");
1657                 pw.increaseIndent();
1658                 Analytics.dump(pw);
1659                 pw.decreaseIndent();
1660             }
1661             if (isTimeLineView) {
1662                 Log.dumpEventsTimeline(pw);
1663             } else {
1664                 Log.dumpEvents(pw);
1665             }
1666         }
1667 
1668         /**
1669          * @see android.telecom.TelecomManager#createManageBlockedNumbersIntent
1670          */
1671         @Override
1672         public Intent createManageBlockedNumbersIntent() {
1673             return BlockedNumbersActivity.getIntentForStartingActivity();
1674         }
1675 
1676 
1677         @Override
1678         public Intent createLaunchEmergencyDialerIntent(String number) {
1679             String packageName = mContext.getApplicationContext().getString(
1680                     com.android.internal.R.string.config_emergency_dialer_package);
1681             Intent intent = new Intent(Intent.ACTION_DIAL_EMERGENCY)
1682                     .setPackage(packageName);
1683             ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0 /* flags*/);
1684             if (resolveInfo == null) {
1685                 // No matching activity from config, fallback to default platform implementation
1686                 intent.setPackage(null);
1687             }
1688             if (!TextUtils.isEmpty(number) && TextUtils.isDigitsOnly(number)) {
1689                 intent.setData(Uri.parse("tel:" + number));
1690             }
1691             return intent;
1692         }
1693 
1694         /**
1695          * @see android.telecom.TelecomManager#isIncomingCallPermitted(PhoneAccountHandle)
1696          */
1697         @Override
1698         public boolean isIncomingCallPermitted(PhoneAccountHandle phoneAccountHandle) {
1699             try {
1700                 Log.startSession("TSI.iICP");
1701                 enforcePermission(android.Manifest.permission.MANAGE_OWN_CALLS);
1702                 synchronized (mLock) {
1703                     long token = Binder.clearCallingIdentity();
1704                     try {
1705                         return mCallsManager.isIncomingCallPermitted(phoneAccountHandle);
1706                     } finally {
1707                         Binder.restoreCallingIdentity(token);
1708                     }
1709                 }
1710             } finally {
1711                 Log.endSession();
1712             }
1713         }
1714 
1715         /**
1716          * @see android.telecom.TelecomManager#isOutgoingCallPermitted(PhoneAccountHandle)
1717          */
1718         @Override
1719         public boolean isOutgoingCallPermitted(PhoneAccountHandle phoneAccountHandle) {
1720             try {
1721                 Log.startSession("TSI.iOCP");
1722                 enforcePermission(android.Manifest.permission.MANAGE_OWN_CALLS);
1723                 synchronized (mLock) {
1724                     long token = Binder.clearCallingIdentity();
1725                     try {
1726                         return mCallsManager.isOutgoingCallPermitted(phoneAccountHandle);
1727                     } finally {
1728                         Binder.restoreCallingIdentity(token);
1729                     }
1730                 }
1731             } finally {
1732                 Log.endSession();
1733             }
1734         }
1735 
1736         /**
1737          * Blocks until all Telecom handlers have completed their current work.
1738          *
1739          * See {@link com.android.commands.telecom.Telecom}.
1740          */
1741         @Override
1742         public void waitOnHandlers() {
1743             try {
1744                 Log.startSession("TSI.wOH");
1745                 enforceModifyPermission();
1746                 synchronized (mLock) {
1747                     long token = Binder.clearCallingIdentity();
1748                     try {
1749                         Log.i(this, "waitOnHandlers");
1750                         mCallsManager.waitOnHandlers();
1751                     } finally {
1752                         Binder.restoreCallingIdentity(token);
1753                     }
1754                 }
1755             } finally {
1756                 Log.endSession();
1757             }
1758         }
1759 
1760         @Override
1761         public void setTestEmergencyPhoneAccountPackageNameFilter(String packageName) {
1762             try {
1763                 Log.startSession("TSI.sTPAPNF");
1764                 enforceModifyPermission();
1765                 enforceShellOnly(Binder.getCallingUid(),
1766                         "setTestEmergencyPhoneAccountPackageNameFilter");
1767                 synchronized (mLock) {
1768                     long token = Binder.clearCallingIdentity();
1769                     try {
1770                         mPhoneAccountRegistrar.setTestPhoneAccountPackageNameFilter(packageName);
1771                     } finally {
1772                         Binder.restoreCallingIdentity(token);
1773                     }
1774                 }
1775             } finally {
1776                 Log.endSession();
1777             }
1778         }
1779 
1780         /**
1781          * See {@link TelecomManager#isInEmergencyCall()}
1782          */
1783         @Override
1784         public boolean isInEmergencyCall() {
1785             try {
1786                 Log.startSession("TSI.iIEC");
1787                 enforceModifyPermission();
1788                 synchronized (mLock) {
1789                     long token = Binder.clearCallingIdentity();
1790                     try {
1791                         boolean isInEmergencyCall = mCallsManager.isInEmergencyCall();
1792                         Log.i(this, "isInEmergencyCall: %b", isInEmergencyCall);
1793                         return isInEmergencyCall;
1794                     } finally {
1795                         Binder.restoreCallingIdentity(token);
1796                     }
1797                 }
1798             } finally {
1799                 Log.endSession();
1800             }
1801         }
1802 
1803         /**
1804          * See {@link TelecomManager#handleCallIntent(Intent, String)}
1805          */
1806         @Override
1807         public void handleCallIntent(Intent intent, String callingPackage) {
1808             try {
1809                 Log.startSession("TSI.hCI");
1810                 synchronized (mLock) {
1811                     mContext.enforceCallingOrSelfPermission(PERMISSION_HANDLE_CALL_INTENT,
1812                             "handleCallIntent is for internal use only.");
1813 
1814                     long token = Binder.clearCallingIdentity();
1815                     try {
1816                         Log.i(this, "handleCallIntent: handling call intent");
1817                         mCallIntentProcessorAdapter.processOutgoingCallIntent(mContext,
1818                                 mCallsManager, intent, callingPackage);
1819                     } finally {
1820                         Binder.restoreCallingIdentity(token);
1821                     }
1822                 }
1823             } finally {
1824                 Log.endSession();
1825             }
1826         }
1827 
1828         /**
1829          * A method intended for use in testing to clean up any calls that get stuck in the
1830          * {@link CallState#DISCONNECTED} or {@link CallState#DISCONNECTING} states. Stuck calls
1831          * during CTS cause cascading failures, so if the CTS test detects such a state, it should
1832          * call this method via a shell command to clean up before moving on to the next test.
1833          * Also cleans up any pending futures related to
1834          * {@link android.telecom.CallDiagnosticService}s.
1835          */
1836         @Override
1837         public void cleanupStuckCalls() {
1838             Log.startSession("TCI.cSC");
1839             try {
1840                 synchronized (mLock) {
1841                     enforceShellOnly(Binder.getCallingUid(), "cleanupStuckCalls");
1842                     Binder.withCleanCallingIdentity(() -> {
1843                         for (Call call : mCallsManager.getCalls()) {
1844                             call.cleanup();
1845                             if (call.getState() == CallState.DISCONNECTED
1846                                     || call.getState() == CallState.DISCONNECTING) {
1847                                 mCallsManager.markCallAsRemoved(call);
1848                             }
1849                         }
1850                         mCallsManager.getInCallController().unbindFromServices();
1851                     });
1852                 }
1853             } finally {
1854                 Log.endSession();
1855             }
1856         }
1857 
1858         /**
1859          * A method intended for use in testing to reset car mode at all priorities.
1860          *
1861          * Runs during setup to avoid cascading failures from failing car mode CTS.
1862          */
1863         @Override
1864         public void resetCarMode() {
1865             Log.startSession("TCI.rCM");
1866             try {
1867                 synchronized (mLock) {
1868                     enforceShellOnly(Binder.getCallingUid(), "resetCarMode");
1869                     Binder.withCleanCallingIdentity(() -> {
1870                         UiModeManager uiModeManager =
1871                                 mContext.getSystemService(UiModeManager.class);
1872                         uiModeManager.disableCarMode(UiModeManager.DISABLE_CAR_MODE_ALL_PRIORITIES);
1873                     });
1874                 }
1875             } finally {
1876                 Log.endSession();
1877             }
1878         }
1879 
1880         @Override
1881         public void setTestDefaultCallRedirectionApp(String packageName) {
1882             try {
1883                 Log.startSession("TSI.sTDCRA");
1884                 enforceModifyPermission();
1885                 if (!Build.IS_USERDEBUG) {
1886                     throw new SecurityException("Test-only API.");
1887                 }
1888                 synchronized (mLock) {
1889                     long token = Binder.clearCallingIdentity();
1890                     try {
1891                         mCallsManager.getRoleManagerAdapter().setTestDefaultCallRedirectionApp(
1892                                 packageName);
1893                     } finally {
1894                         Binder.restoreCallingIdentity(token);
1895                     }
1896                 }
1897             } finally {
1898                 Log.endSession();
1899             }
1900         }
1901 
1902         @Override
1903         public void setTestDefaultCallScreeningApp(String packageName) {
1904             try {
1905                 Log.startSession("TSI.sTDCSA");
1906                 enforceModifyPermission();
1907                 if (!Build.IS_USERDEBUG) {
1908                     throw new SecurityException("Test-only API.");
1909                 }
1910                 synchronized (mLock) {
1911                     long token = Binder.clearCallingIdentity();
1912                     try {
1913                         mCallsManager.getRoleManagerAdapter().setTestDefaultCallScreeningApp(
1914                                 packageName);
1915                     } finally {
1916                         Binder.restoreCallingIdentity(token);
1917                     }
1918                 }
1919             } finally {
1920                 Log.endSession();
1921             }
1922         }
1923 
1924         @Override
1925         public void addOrRemoveTestCallCompanionApp(String packageName, boolean isAdded) {
1926             try {
1927                 Log.startSession("TSI.aORTCCA");
1928                 enforceModifyPermission();
1929                 enforceShellOnly(Binder.getCallingUid(), "addOrRemoveTestCallCompanionApp");
1930                 synchronized (mLock) {
1931                     long token = Binder.clearCallingIdentity();
1932                     try {
1933                         mCallsManager.getRoleManagerAdapter().addOrRemoveTestCallCompanionApp(
1934                                 packageName, isAdded);
1935                     } finally {
1936                         Binder.restoreCallingIdentity(token);
1937                     }
1938                 }
1939             } finally {
1940                 Log.endSession();
1941             }
1942         }
1943 
1944         @Override
1945         public void setTestPhoneAcctSuggestionComponent(String flattenedComponentName) {
1946             try {
1947                 Log.startSession("TSI.sPASA");
1948                 enforceModifyPermission();
1949                 if (Binder.getCallingUid() != Process.SHELL_UID
1950                         && Binder.getCallingUid() != Process.ROOT_UID) {
1951                     throw new SecurityException("Shell-only API.");
1952                 }
1953                 synchronized (mLock) {
1954                     PhoneAccountSuggestionHelper.setOverrideServiceName(flattenedComponentName);
1955                 }
1956             } finally {
1957                 Log.endSession();
1958             }
1959         }
1960 
1961         @Override
1962         public void setTestDefaultDialer(String packageName) {
1963             try {
1964                 Log.startSession("TSI.sTDD");
1965                 enforceModifyPermission();
1966                 if (Binder.getCallingUid() != Process.SHELL_UID
1967                         && Binder.getCallingUid() != Process.ROOT_UID) {
1968                     throw new SecurityException("Shell-only API.");
1969                 }
1970                 synchronized (mLock) {
1971                     long token = Binder.clearCallingIdentity();
1972                     try {
1973                         mCallsManager.getRoleManagerAdapter().setTestDefaultDialer(packageName);
1974                     } finally {
1975                         Binder.restoreCallingIdentity(token);
1976                     }
1977                 }
1978             } finally {
1979                 Log.endSession();
1980             }
1981         }
1982 
1983         @Override
1984         public void setTestCallDiagnosticService(String packageName) {
1985             try {
1986                 Log.startSession("TSI.sTCDS");
1987                 enforceModifyPermission();
1988                 enforceShellOnly(Binder.getCallingUid(), "setTestCallDiagnosticService is for "
1989                         + "shell use only.");
1990                 synchronized (mLock) {
1991                     long token = Binder.clearCallingIdentity();
1992                     try {
1993                         CallDiagnosticServiceController controller =
1994                                 mCallsManager.getCallDiagnosticServiceController();
1995                         if (controller != null) {
1996                             controller.setTestCallDiagnosticService(packageName);
1997                         }
1998                     } finally {
1999                         Binder.restoreCallingIdentity(token);
2000                     }
2001                 }
2002             } finally {
2003                 Log.endSession();
2004             }
2005         }
2006     };
2007 
2008     /**
2009      * @return whether to return early without doing the action/throwing
2010      * @throws SecurityException same as {@link Context#enforceCallingOrSelfPermission}
2011      */
enforceAnswerCallPermission(String packageName, int uid)2012     private boolean enforceAnswerCallPermission(String packageName, int uid) {
2013         try {
2014             enforceModifyPermission();
2015         } catch (SecurityException e) {
2016             final String permission = Manifest.permission.ANSWER_PHONE_CALLS;
2017             enforcePermission(permission);
2018 
2019             final int opCode = AppOpsManager.permissionToOpCode(permission);
2020             if (opCode != AppOpsManager.OP_NONE
2021                     && mAppOpsManager.checkOp(opCode, uid, packageName)
2022                         != AppOpsManager.MODE_ALLOWED) {
2023                 return false;
2024             }
2025         }
2026         return true;
2027     }
2028 
2029     /**
2030      * @return {@code true} if the app has the handover permission and has received runtime
2031      * permission to perform that operation, {@code false}.
2032      * @throws SecurityException same as {@link Context#enforceCallingOrSelfPermission}
2033      */
enforceAcceptHandoverPermission(String packageName, int uid)2034     private boolean enforceAcceptHandoverPermission(String packageName, int uid) {
2035         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCEPT_HANDOVER,
2036                 "App requires ACCEPT_HANDOVER permission to accept handovers.");
2037 
2038         final int opCode = AppOpsManager.permissionToOpCode(Manifest.permission.ACCEPT_HANDOVER);
2039         if (opCode != AppOpsManager.OP_ACCEPT_HANDOVER || (
2040                 mAppOpsManager.checkOp(opCode, uid, packageName)
2041                         != AppOpsManager.MODE_ALLOWED)) {
2042             return false;
2043         }
2044         return true;
2045     }
2046 
2047     private Context mContext;
2048     private AppOpsManager mAppOpsManager;
2049     private PackageManager mPackageManager;
2050     private CallsManager mCallsManager;
2051     private final PhoneAccountRegistrar mPhoneAccountRegistrar;
2052     private final CallIntentProcessor.Adapter mCallIntentProcessorAdapter;
2053     private final UserCallIntentProcessorFactory mUserCallIntentProcessorFactory;
2054     private final DefaultDialerCache mDefaultDialerCache;
2055     private final SubscriptionManagerAdapter mSubscriptionManagerAdapter;
2056     private final SettingsSecureAdapter mSettingsSecureAdapter;
2057     private final TelecomSystem.SyncRoot mLock;
2058 
TelecomServiceImpl( Context context, CallsManager callsManager, PhoneAccountRegistrar phoneAccountRegistrar, CallIntentProcessor.Adapter callIntentProcessorAdapter, UserCallIntentProcessorFactory userCallIntentProcessorFactory, DefaultDialerCache defaultDialerCache, SubscriptionManagerAdapter subscriptionManagerAdapter, SettingsSecureAdapter settingsSecureAdapter, TelecomSystem.SyncRoot lock)2059     public TelecomServiceImpl(
2060             Context context,
2061             CallsManager callsManager,
2062             PhoneAccountRegistrar phoneAccountRegistrar,
2063             CallIntentProcessor.Adapter callIntentProcessorAdapter,
2064             UserCallIntentProcessorFactory userCallIntentProcessorFactory,
2065             DefaultDialerCache defaultDialerCache,
2066             SubscriptionManagerAdapter subscriptionManagerAdapter,
2067             SettingsSecureAdapter settingsSecureAdapter,
2068             TelecomSystem.SyncRoot lock) {
2069         mContext = context;
2070         mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
2071 
2072         mPackageManager = mContext.getPackageManager();
2073 
2074         mCallsManager = callsManager;
2075         mLock = lock;
2076         mPhoneAccountRegistrar = phoneAccountRegistrar;
2077         mUserCallIntentProcessorFactory = userCallIntentProcessorFactory;
2078         mDefaultDialerCache = defaultDialerCache;
2079         mCallIntentProcessorAdapter = callIntentProcessorAdapter;
2080         mSubscriptionManagerAdapter = subscriptionManagerAdapter;
2081         mSettingsSecureAdapter = settingsSecureAdapter;
2082 
2083         mDefaultDialerCache.observeDefaultDialerApplication(mContext.getMainExecutor(), userId -> {
2084             String defaultDialer = mDefaultDialerCache.getDefaultDialerApplication(userId);
2085             if (defaultDialer == null) {
2086                 // We are replacing the dialer, just wait for the upcoming callback.
2087                 return;
2088             }
2089             final Intent intent = new Intent(TelecomManager.ACTION_DEFAULT_DIALER_CHANGED)
2090                     .putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,
2091                             defaultDialer);
2092             mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
2093         });
2094     }
2095 
getBinder()2096     public ITelecomService.Stub getBinder() {
2097         return mBinderImpl;
2098     }
2099 
2100     //
2101     // Supporting methods for the ITelecomService interface implementation.
2102     //
2103 
isPhoneAccountHandleVisibleToCallingUser( PhoneAccountHandle phoneAccountUserHandle, UserHandle callingUser)2104     private boolean isPhoneAccountHandleVisibleToCallingUser(
2105             PhoneAccountHandle phoneAccountUserHandle, UserHandle callingUser) {
2106         synchronized (mLock) {
2107             return mPhoneAccountRegistrar.getPhoneAccount(phoneAccountUserHandle, callingUser)
2108                     != null;
2109         }
2110     }
2111 
isCallerSystemApp()2112     private boolean isCallerSystemApp() {
2113         int uid = Binder.getCallingUid();
2114         String[] packages = mPackageManager.getPackagesForUid(uid);
2115         for (String packageName : packages) {
2116             if (isPackageSystemApp(packageName)) {
2117                 return true;
2118             }
2119         }
2120         return false;
2121     }
2122 
isPackageSystemApp(String packageName)2123     private boolean isPackageSystemApp(String packageName) {
2124         try {
2125             ApplicationInfo applicationInfo = mPackageManager.getApplicationInfo(packageName,
2126                     PackageManager.GET_META_DATA);
2127             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
2128                 return true;
2129             }
2130         } catch (PackageManager.NameNotFoundException e) {
2131         }
2132         return false;
2133     }
2134 
acceptRingingCallInternal(int videoState, String packageName)2135     private void acceptRingingCallInternal(int videoState, String packageName) {
2136         Call call = mCallsManager.getFirstCallWithState(CallState.RINGING,
2137                 CallState.SIMULATED_RINGING);
2138         if (call != null) {
2139             if (call.isSelfManaged()) {
2140                 Log.addEvent(call, LogUtils.Events.REQUEST_ACCEPT,
2141                         "self-mgd accept ignored from " + packageName);
2142                 return;
2143             }
2144 
2145             if (videoState == DEFAULT_VIDEO_STATE || !isValidAcceptVideoState(videoState)) {
2146                 videoState = call.getVideoState();
2147             }
2148             mCallsManager.answerCall(call, videoState);
2149         }
2150     }
2151 
endCallInternal(String callingPackage)2152     private boolean endCallInternal(String callingPackage) {
2153         // Always operate on the foreground call if one exists, otherwise get the first call in
2154         // priority order by call-state.
2155         Call call = mCallsManager.getForegroundCall();
2156         if (call == null) {
2157             call = mCallsManager.getFirstCallWithState(
2158                     CallState.ACTIVE,
2159                     CallState.DIALING,
2160                     CallState.PULLING,
2161                     CallState.RINGING,
2162                     CallState.SIMULATED_RINGING,
2163                     CallState.ON_HOLD);
2164         }
2165 
2166         if (call != null) {
2167             if (call.isEmergencyCall()) {
2168                 android.util.EventLog.writeEvent(0x534e4554, "132438333", -1, "");
2169                 return false;
2170             }
2171 
2172             if (call.isSelfManaged()) {
2173                 Log.addEvent(call, LogUtils.Events.REQUEST_DISCONNECT,
2174                         "self-mgd disconnect ignored from " + callingPackage);
2175                 return false;
2176             }
2177 
2178             if (call.getState() == CallState.RINGING
2179                     || call.getState() == CallState.SIMULATED_RINGING) {
2180                 mCallsManager.rejectCall(call, false /* rejectWithMessage */, null);
2181             } else {
2182                 mCallsManager.disconnectCall(call);
2183             }
2184             return true;
2185         }
2186 
2187         return false;
2188     }
2189 
2190     // Enforce that the PhoneAccountHandle being passed in is both registered to the current user
2191     // and enabled.
enforcePhoneAccountIsRegisteredEnabled(PhoneAccountHandle phoneAccountHandle, UserHandle callingUserHandle)2192     private void enforcePhoneAccountIsRegisteredEnabled(PhoneAccountHandle phoneAccountHandle,
2193                                                         UserHandle callingUserHandle) {
2194         PhoneAccount phoneAccount = mPhoneAccountRegistrar.getPhoneAccount(phoneAccountHandle,
2195                 callingUserHandle);
2196         if(phoneAccount == null) {
2197             EventLog.writeEvent(0x534e4554, "26864502", Binder.getCallingUid(), "R");
2198             throw new SecurityException("This PhoneAccountHandle is not registered for this user!");
2199         }
2200         if(!phoneAccount.isEnabled()) {
2201             EventLog.writeEvent(0x534e4554, "26864502", Binder.getCallingUid(), "E");
2202             throw new SecurityException("This PhoneAccountHandle is not enabled for this user!");
2203         }
2204     }
2205 
enforcePhoneAccountModificationForPackage(String packageName)2206     private void enforcePhoneAccountModificationForPackage(String packageName) {
2207         // TODO: Use a new telecomm permission for this instead of reusing modify.
2208 
2209         int result = mContext.checkCallingOrSelfPermission(MODIFY_PHONE_STATE);
2210 
2211         // Callers with MODIFY_PHONE_STATE can use the PhoneAccount mechanism to implement
2212         // built-in behavior even when PhoneAccounts are not exposed as a third-part API. They
2213         // may also modify PhoneAccounts on behalf of any 'packageName'.
2214 
2215         if (result != PackageManager.PERMISSION_GRANTED) {
2216             // Other callers are only allowed to modify PhoneAccounts if the relevant system
2217             // feature is enabled ...
2218             enforceConnectionServiceFeature();
2219             // ... and the PhoneAccounts they refer to are for their own package.
2220             enforceCallingPackage(packageName);
2221         }
2222     }
2223 
enforcePermissionOrPrivilegedDialer(String permission, String packageName)2224     private void enforcePermissionOrPrivilegedDialer(String permission, String packageName) {
2225         if (!isPrivilegedDialerCalling(packageName)) {
2226             try {
2227                 enforcePermission(permission);
2228             } catch (SecurityException e) {
2229                 Log.e(this, e, "Caller must be the default or system dialer, or have the permission"
2230                         + " %s to perform this operation.", permission);
2231                 throw e;
2232             }
2233         }
2234     }
2235 
enforceCallingPackage(String packageName)2236     private void enforceCallingPackage(String packageName) {
2237         mAppOpsManager.checkPackage(Binder.getCallingUid(), packageName);
2238     }
2239 
enforceConnectionServiceFeature()2240     private void enforceConnectionServiceFeature() {
2241         enforceFeature(PackageManager.FEATURE_CONNECTION_SERVICE);
2242     }
2243 
enforceRegisterSimSubscriptionPermission()2244     private void enforceRegisterSimSubscriptionPermission() {
2245         enforcePermission(REGISTER_SIM_SUBSCRIPTION);
2246     }
2247 
enforceModifyPermission()2248     private void enforceModifyPermission() {
2249         enforcePermission(MODIFY_PHONE_STATE);
2250     }
2251 
enforceModifyPermission(String message)2252     private void enforceModifyPermission(String message) {
2253         mContext.enforceCallingOrSelfPermission(MODIFY_PHONE_STATE, message);
2254     }
2255 
enforcePermission(String permission)2256     private void enforcePermission(String permission) {
2257         mContext.enforceCallingOrSelfPermission(permission, null);
2258     }
2259 
enforceRegisterSelfManaged()2260     private void enforceRegisterSelfManaged() {
2261         mContext.enforceCallingPermission(android.Manifest.permission.MANAGE_OWN_CALLS, null);
2262     }
2263 
enforceRegisterMultiUser()2264     private void enforceRegisterMultiUser() {
2265         if (!isCallerSystemApp()) {
2266             throw new SecurityException("CAPABILITY_MULTI_USER is only available to system apps.");
2267         }
2268     }
2269 
enforceRegisterSkipCallFiltering()2270     private void enforceRegisterSkipCallFiltering() {
2271         if (!isCallerSystemApp()) {
2272             throw new SecurityException(
2273                 "EXTRA_SKIP_CALL_FILTERING is only available to system apps.");
2274         }
2275     }
2276 
enforceUserHandleMatchesCaller(PhoneAccountHandle accountHandle)2277     private void enforceUserHandleMatchesCaller(PhoneAccountHandle accountHandle) {
2278         if (!Binder.getCallingUserHandle().equals(accountHandle.getUserHandle())) {
2279             throw new SecurityException("Calling UserHandle does not match PhoneAccountHandle's");
2280         }
2281     }
2282 
enforceCrossUserPermission(int callingUid)2283     private void enforceCrossUserPermission(int callingUid) {
2284         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2285             mContext.enforceCallingOrSelfPermission(
2286                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have"
2287                             + " INTERACT_ACROSS_USERS_FULL permission");
2288         }
2289     }
2290 
enforceFeature(String feature)2291     private void enforceFeature(String feature) {
2292         PackageManager pm = mContext.getPackageManager();
2293         if (!pm.hasSystemFeature(feature)) {
2294             throw new UnsupportedOperationException(
2295                     "System does not support feature " + feature);
2296         }
2297     }
2298 
2299     // to be used for TestApi methods that can only be called with SHELL UID.
enforceShellOnly(int callingUid, String message)2300     private void enforceShellOnly(int callingUid, String message) {
2301         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
2302             return; // okay
2303         }
2304 
2305         throw new SecurityException(message + ": Only shell user can call it");
2306     }
2307 
canReadPhoneState(String callingPackage, String callingFeatureId, String message)2308     private boolean canReadPhoneState(String callingPackage, String callingFeatureId,
2309             String message) {
2310         // The system/default dialer can always read phone state - so that emergency calls will
2311         // still work.
2312         if (isPrivilegedDialerCalling(callingPackage)) {
2313             return true;
2314         }
2315 
2316         try {
2317             mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, message);
2318             // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2319             // permission
2320             return true;
2321         } catch (SecurityException e) {
2322             // Accessing phone state is gated by a special permission.
2323             mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, message);
2324 
2325             // Some apps that have the permission can be restricted via app ops.
2326             return mAppOpsManager.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2327                     callingPackage, callingFeatureId, message) == AppOpsManager.MODE_ALLOWED;
2328         }
2329     }
2330 
canReadPhoneNumbers(String callingPackage, String callingFeatureId, String message)2331     private boolean canReadPhoneNumbers(String callingPackage, String callingFeatureId,
2332             String message) {
2333         boolean targetSdkPreR = false;
2334         int uid = Binder.getCallingUid();
2335         try {
2336             ApplicationInfo applicationInfo = mPackageManager.getApplicationInfoAsUser(
2337                     callingPackage, 0, UserHandle.getUserHandleForUid(Binder.getCallingUid()));
2338             targetSdkPreR = applicationInfo != null
2339                     && applicationInfo.targetSdkVersion < Build.VERSION_CODES.R;
2340         } catch (PackageManager.NameNotFoundException e) {
2341             // In the case that the PackageManager cannot find the specified calling package apply
2342             // the more restrictive target R+ requirements.
2343         }
2344         // Apps targeting pre-R can access phone numbers via READ_PHONE_STATE
2345         if (targetSdkPreR) {
2346             try {
2347                 return canReadPhoneState(callingPackage, callingFeatureId, message);
2348             } catch (SecurityException e) {
2349                 // Apps targeting pre-R can still access phone numbers via the additional checks
2350                 // below.
2351             }
2352         } else {
2353             // The system/default dialer can always read phone state - so that emergency calls will
2354             // still work.
2355             if (isPrivilegedDialerCalling(callingPackage)) {
2356                 return true;
2357             }
2358             if (mContext.checkCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE)
2359                     == PackageManager.PERMISSION_GRANTED) {
2360                 return true;
2361             }
2362         }
2363         if (mContext.checkCallingOrSelfPermission(READ_PHONE_NUMBERS)
2364                 == PackageManager.PERMISSION_GRANTED && mAppOpsManager.noteOpNoThrow(
2365                 AppOpsManager.OPSTR_READ_PHONE_NUMBERS, uid, callingPackage, callingFeatureId,
2366                 message) == AppOpsManager.MODE_ALLOWED) {
2367             return true;
2368         }
2369         if (mContext.checkCallingOrSelfPermission(READ_SMS) == PackageManager.PERMISSION_GRANTED
2370                 && mAppOpsManager.noteOpNoThrow(AppOpsManager.OPSTR_READ_SMS, uid, callingPackage,
2371                 callingFeatureId, message) == AppOpsManager.MODE_ALLOWED) {
2372             return true;
2373         }
2374         // The default SMS app with the WRITE_SMS appop granted can access phone numbers.
2375         if (mAppOpsManager.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SMS, uid, callingPackage,
2376                 callingFeatureId, message) == AppOpsManager.MODE_ALLOWED) {
2377             return true;
2378         }
2379         throw new SecurityException("Package " + callingPackage
2380                 + " does not meet the requirements to access the phone number");
2381     }
2382 
2383 
2384     private boolean canReadPrivilegedPhoneState(String callingPackage, String message) {
2385         // The system/default dialer can always read phone state - so that emergency calls will
2386         // still work.
2387         if (isPrivilegedDialerCalling(callingPackage)) {
2388             return true;
2389         }
2390 
2391         mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, message);
2392         return true;
2393     }
2394 
2395     private boolean isDialerOrPrivileged(String callingPackage, String message) {
2396         // The system/default dialer can always read phone state - so that emergency calls will
2397         // still work.
2398         if (isPrivilegedDialerCalling(callingPackage)) {
2399             return true;
2400         }
2401 
2402         mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, message);
2403         // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2404         // permission
2405         return true;
2406     }
2407 
2408     private boolean isSelfManagedConnectionService(PhoneAccountHandle phoneAccountHandle) {
2409         if (phoneAccountHandle != null) {
2410                 PhoneAccount phoneAccount = mPhoneAccountRegistrar.getPhoneAccountUnchecked(
2411                         phoneAccountHandle);
2412                 return phoneAccount != null && phoneAccount.isSelfManaged();
2413         }
2414         return false;
2415     }
2416 
2417     private boolean canCallPhone(String callingPackage, String message) {
2418         return canCallPhone(callingPackage, null /* featureId */, message);
2419     }
2420 
2421     private boolean canCallPhone(String callingPackage, String callingFeatureId, String message) {
2422         // The system/default dialer can always read phone state - so that emergency calls will
2423         // still work.
2424         if (isPrivilegedDialerCalling(callingPackage)) {
2425             return true;
2426         }
2427 
2428         // Accessing phone state is gated by a special permission.
2429         mContext.enforceCallingOrSelfPermission(CALL_PHONE, message);
2430 
2431         // Some apps that have the permission can be restricted via app ops.
2432         return mAppOpsManager.noteOp(AppOpsManager.OP_CALL_PHONE,
2433                 Binder.getCallingUid(), callingPackage, callingFeatureId, message)
2434                 == AppOpsManager.MODE_ALLOWED;
2435     }
2436 
2437     private boolean canGetPhoneAccount(String callingPackage, PhoneAccountHandle accountHandle) {
2438         // Allow default dialer, system dialer and sim call manager to be able to do this without
2439         // extra permission
2440         try {
2441             if (isPrivilegedDialerCalling(callingPackage) || isCallerSimCallManager(
2442                     accountHandle)) {
2443                 return true;
2444             }
2445         } catch (SecurityException e) {
2446             // ignore
2447         }
2448 
2449         try {
2450             mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, null);
2451             return true;
2452         } catch (SecurityException e) {
2453             // Accessing phone state is gated by a special permission.
2454             mContext.enforceCallingOrSelfPermission(READ_PHONE_NUMBERS, null);
2455             return true;
2456         }
2457     }
2458 
2459     private boolean isCallerSimCallManager(PhoneAccountHandle targetPhoneAccount) {
2460         long token = Binder.clearCallingIdentity();
2461         PhoneAccountHandle accountHandle = null;
2462         try {
2463             accountHandle = mPhoneAccountRegistrar.getSimCallManagerFromHandle(targetPhoneAccount,
2464                     mCallsManager.getCurrentUserHandle());
2465         } finally {
2466             Binder.restoreCallingIdentity(token);
2467         }
2468 
2469         if (accountHandle != null) {
2470             try {
2471                 mAppOpsManager.checkPackage(
2472                         Binder.getCallingUid(), accountHandle.getComponentName().getPackageName());
2473                 return true;
2474             } catch (SecurityException e) {
2475             }
2476         }
2477         return false;
2478     }
2479 
2480     private boolean isPrivilegedDialerCalling(String callingPackage) {
2481         mAppOpsManager.checkPackage(Binder.getCallingUid(), callingPackage);
2482 
2483         // Note: Important to clear the calling identity since the code below calls into RoleManager
2484         // to check who holds the dialer role, and that requires MANAGE_ROLE_HOLDERS permission
2485         // which is a system permission.
2486         long token = Binder.clearCallingIdentity();
2487         try {
2488             return mDefaultDialerCache.isDefaultOrSystemDialer(
2489                     callingPackage, Binder.getCallingUserHandle().getIdentifier());
2490         } finally {
2491             Binder.restoreCallingIdentity(token);
2492         }
2493     }
2494 
2495     private TelephonyManager getTelephonyManager(int subId) {
2496         return ((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE))
2497                 .createForSubscriptionId(subId);
2498     }
2499 
2500     /**
2501      * Determines if a video state is valid for accepting an incoming call.
2502      * For the purpose of accepting a call, states {@link VideoProfile#STATE_AUDIO_ONLY}, and
2503      * any combination of {@link VideoProfile#STATE_RX_ENABLED} and
2504      * {@link VideoProfile#STATE_TX_ENABLED} are considered valid.
2505      *
2506      * @param videoState The video state.
2507      * @return {@code true} if the video state is valid, {@code false} otherwise.
2508      */
2509     private boolean isValidAcceptVideoState(int videoState) {
2510         // Given a video state input, turn off TX and RX so that we can determine if those were the
2511         // only bits set.
2512         int remainingState = videoState & ~VideoProfile.STATE_TX_ENABLED;
2513         remainingState = remainingState & ~VideoProfile.STATE_RX_ENABLED;
2514 
2515         // If only TX or RX were set (or neither), the video state is valid.
2516         return remainingState == 0;
2517     }
2518 
2519     private void broadcastCallScreeningAppChangedIntent(String componentName,
2520         boolean isDefault) {
2521         if (TextUtils.isEmpty(componentName)) {
2522             return;
2523         }
2524 
2525         ComponentName broadcastComponentName = ComponentName.unflattenFromString(componentName);
2526 
2527         if (broadcastComponentName != null) {
2528             Intent intent = new Intent(TelecomManager
2529                 .ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED);
2530             intent.putExtra(TelecomManager
2531                 .EXTRA_IS_DEFAULT_CALL_SCREENING_APP, isDefault);
2532             intent.putExtra(TelecomManager
2533                 .EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME, componentName);
2534             intent.setPackage(broadcastComponentName.getPackageName());
2535             mContext.sendBroadcast(intent);
2536         }
2537     }
2538 }
2539