Allow PSTN phone account for incoming calls from connection manager

Currently the phone account specified for an incoming call must
match belong to the calling app.

This CL relaxes that restricition a little. Now connection managers
can specify PSTN phone accounts when adding a new incoming call.

This is necessary so that incoming calls from the connection manager
are displayed the same way as outgoing calls from the connection
manager.

Bug: 19591608, 19217193
Change-Id: I856ada853865c0ca01a2c3f9baede354f0855ea8
diff --git a/src/com/android/server/telecom/TelecomService.java b/src/com/android/server/telecom/TelecomService.java
index 0e0f0a1..e914f32 100644
--- a/src/com/android/server/telecom/TelecomService.java
+++ b/src/com/android/server/telecom/TelecomService.java
@@ -657,11 +657,16 @@
         public void addNewIncomingCall(PhoneAccountHandle phoneAccountHandle, Bundle extras) {
             Log.i(this, "Adding new incoming call with phoneAccountHandle %s", phoneAccountHandle);
             if (phoneAccountHandle != null && phoneAccountHandle.getComponentName() != null) {
-                mAppOpsManager.checkPackage(
-                        Binder.getCallingUid(), phoneAccountHandle.getComponentName().getPackageName());
-
-                // Make sure it doesn't cross the UserHandle boundary
-                enforceUserHandleMatchesCaller(phoneAccountHandle);
+                // TODO(sail): Add unit tests for adding incoming calls from a SIM call manager.
+                if (isCallerSimCallManager() && TelephonyUtil.isPstnComponentName(
+                        phoneAccountHandle.getComponentName())) {
+                    Log.v(this, "Allowing call manager to add incoming call with PSTN handle");
+                } else {
+                    mAppOpsManager.checkPackage(Binder.getCallingUid(),
+                            phoneAccountHandle.getComponentName().getPackageName());
+                    // Make sure it doesn't cross the UserHandle boundary
+                    enforceUserHandleMatchesCaller(phoneAccountHandle);
+                }
 
                 Intent intent = new Intent(TelecomManager.ACTION_INCOMING_CALL);
                 intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle);
@@ -932,6 +937,19 @@
         }
     }
 
+    private boolean isCallerSimCallManager() {
+        PhoneAccountHandle accountHandle = mPhoneAccountRegistrar.getSimCallManager();
+        if (accountHandle != null) {
+            try {
+                mAppOpsManager.checkPackage(
+                        Binder.getCallingUid(), accountHandle.getComponentName().getPackageName());
+                return true;
+            } catch (SecurityException e) {
+            }
+        }
+        return false;
+    }
+
     private boolean isDefaultDialerCalling() {
         ComponentName defaultDialerComponent = getDefaultPhoneAppInternal();
         if (defaultDialerComponent != null) {