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