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