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