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