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