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