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