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