DO NOT MERGE Use E PhoneAccount for MT ECM Call

Use the correct Emergency PhoneAccount for a MT call on a phone with no
SIM that is in ECM. Also, reject incoming SIP calls that are received on
an incorrect PhoneAccount instead of crashing the Phone process.

Bug: 27820226
Change-Id: I81d58d1123535d53ef263c6e0ea8756d69a81eae
(cherry picked from commit 481e3203a402c744d45dd385fb1258890b2d71b2)
diff --git a/sip/src/com/android/services/telephony/sip/SipBroadcastReceiver.java b/sip/src/com/android/services/telephony/sip/SipBroadcastReceiver.java
index 0b701ce..0f20c29 100644
--- a/sip/src/com/android/services/telephony/sip/SipBroadcastReceiver.java
+++ b/sip/src/com/android/services/telephony/sip/SipBroadcastReceiver.java
@@ -21,6 +21,7 @@
 import android.content.Intent;
 import android.net.sip.SipManager;
 import android.os.Bundle;
+import android.telecom.PhoneAccount;
 import android.telecom.PhoneAccountHandle;
 import android.telecom.TelecomManager;
 import android.util.Log;
@@ -62,7 +63,13 @@
         if (accountHandle != null) {
             Bundle extras = new Bundle();
             extras.putParcelable(SipUtil.EXTRA_INCOMING_CALL_INTENT, intent);
-            TelecomManager.from(context).addNewIncomingCall(accountHandle, extras);
+            TelecomManager tm = TelecomManager.from(context);
+            PhoneAccount phoneAccount = tm.getPhoneAccount(accountHandle);
+            if (phoneAccount != null) {
+                tm.addNewIncomingCall(accountHandle, extras);
+            } else {
+                log("takeCall, PhoneAccount is not registered. Not accepting incoming call...");
+            }
         }
     }
 
diff --git a/src/com/android/services/telephony/PstnIncomingCallNotifier.java b/src/com/android/services/telephony/PstnIncomingCallNotifier.java
index cbcf8bb..49eb7db 100644
--- a/src/com/android/services/telephony/PstnIncomingCallNotifier.java
+++ b/src/com/android/services/telephony/PstnIncomingCallNotifier.java
@@ -26,16 +26,19 @@
 import android.os.Handler;
 import android.os.Message;
 import android.telecom.PhoneAccount;
+import android.telecom.PhoneAccountHandle;
 import android.telecom.TelecomManager;
 import android.telephony.TelephonyManager;
 import android.text.TextUtils;
 
 import com.android.internal.telephony.Call;
+import com.android.internal.telephony.CallStateException;
 import com.android.internal.telephony.Connection;
 import com.android.internal.telephony.Phone;
 import com.android.internal.telephony.PhoneConstants;
 import com.android.internal.telephony.PhoneProxy;
 import com.android.internal.telephony.TelephonyIntents;
+import com.android.internal.telephony.cdma.CDMAPhone;
 import com.android.internal.telephony.cdma.CdmaCallWaitingNotification;
 import com.android.phone.PhoneUtils;
 
@@ -220,8 +223,16 @@
                 Uri uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, connection.getAddress(), null);
                 extras.putParcelable(TelecomManager.EXTRA_UNKNOWN_CALL_HANDLE, uri);
             }
-            TelecomManager.from(mPhoneProxy.getContext()).addNewUnknownCall(
-                    PhoneUtils.makePstnPhoneAccountHandle(mPhoneProxy), extras);
+            PhoneAccountHandle handle = findCorrectPhoneAccountHandle();
+            if (handle == null) {
+                try {
+                    connection.hangup();
+                } catch (CallStateException e) {
+                    // connection already disconnected. Do nothing
+                }
+            } else {
+                TelecomManager.from(mPhoneProxy.getContext()).addNewUnknownCall(handle, extras);
+            }
         } else {
             Log.i(this, "swapped an old connection, new one is: %s", connection);
         }
@@ -238,8 +249,16 @@
             Uri uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, connection.getAddress(), null);
             extras.putParcelable(TelephonyManager.EXTRA_INCOMING_NUMBER, uri);
         }
-        TelecomManager.from(mPhoneProxy.getContext()).addNewIncomingCall(
-                PhoneUtils.makePstnPhoneAccountHandle(mPhoneProxy), extras);
+        PhoneAccountHandle handle = findCorrectPhoneAccountHandle();
+        if (handle == null) {
+            try {
+                connection.hangup();
+            } catch (CallStateException e) {
+                // connection already disconnected. Do nothing
+            }
+        } else {
+            TelecomManager.from(mPhoneProxy.getContext()).addNewIncomingCall(handle, extras);
+        }
     }
 
     /**
@@ -282,4 +301,33 @@
         }
         return false;
     }
+
+    /**
+     * Returns the PhoneAccount associated with this {@code PstnIncomingCallNotifier}'s phone. On a
+     * device with No SIM or in airplane mode, it can return an Emergency-only PhoneAccount. If no
+     * PhoneAccount is registered with telecom, return null.
+     * @return A valid PhoneAccountHandle that is registered to Telecom or null if there is none
+     * registered.
+     */
+    private PhoneAccountHandle findCorrectPhoneAccountHandle() {
+        TelecomAccountRegistry telecomAccountRegistry = TelecomAccountRegistry.getInstance(null);
+        // Check to see if a the SIM PhoneAccountHandle Exists for the Call.
+        PhoneAccountHandle handle = TelecomAccountRegistry.makePstnPhoneAccountHandle(mPhoneBase);
+        if (telecomAccountRegistry.hasAccountEntryForPhoneAccount(handle)) {
+            return handle;
+        }
+        // The PhoneAccountHandle does not match any PhoneAccount registered in Telecom.
+        // This is only known to happen if there is no SIM card in the device and the device
+        // receives an MT call while in ECM. Use the Emergency PhoneAccount to receive the account
+        // if it exists.
+        PhoneAccountHandle emergencyHandle =
+                TelecomAccountRegistry.makePstnPhoneAccountHandleWithPrefix(mPhoneBase, "",
+                        true /*isEmergency*/);
+        if(telecomAccountRegistry.hasAccountEntryForPhoneAccount(emergencyHandle)) {
+            Log.i(this, "Receiving MT call in ECM. Using Emergency PhoneAccount Instead.");
+            return emergencyHandle;
+        }
+        Log.w(this, "PhoneAccount not found.");
+        return null;
+    }
 }
diff --git a/src/com/android/services/telephony/TelecomAccountRegistry.java b/src/com/android/services/telephony/TelecomAccountRegistry.java
index 1cb6442..9414862 100644
--- a/src/com/android/services/telephony/TelecomAccountRegistry.java
+++ b/src/com/android/services/telephony/TelecomAccountRegistry.java
@@ -48,6 +48,7 @@
  */
 final class TelecomAccountRegistry {
     private static final boolean DBG = false; /* STOP SHIP if true */
+    public static final String EMERGENCY_ACCOUNT_HANDLE_ID = "E";
 
     // This icon is the one that is used when the Slot ID that we have for a particular SIM
     // is not supported, i.e. SubscriptionManager.INVALID_SLOT_ID or the 5th SIM in a phone.
@@ -248,6 +249,22 @@
         // because this could signal a removal or addition of a SIM in a single SIM phone.
         mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE);
     }
+
+    static PhoneAccountHandle makePstnPhoneAccountHandle(Phone phone) {
+        return makePstnPhoneAccountHandleWithPrefix(phone, "", false);
+    }
+
+    static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
+            Phone phone, String prefix, boolean isEmergency) {
+        ComponentName pstnConnectionServiceName =
+                new ComponentName(phone.getContext(), TelephonyConnectionService.class);
+        // TODO: Should use some sort of special hidden flag to decorate this account as
+        // an emergency-only account
+        String id = isEmergency ? EMERGENCY_ACCOUNT_HANDLE_ID : prefix +
+                String.valueOf(phone.getSubId());
+        return new PhoneAccountHandle(pstnConnectionServiceName, id);
+    }
+
     /**
      * Determines if the list of {@link AccountEntry}(s) contains an {@link AccountEntry} with a
      * specified {@link PhoneAccountHandle}.
@@ -255,7 +272,7 @@
      * @param handle The {@link PhoneAccountHandle}.
      * @return {@code True} if an entry exists.
      */
-    private boolean hasAccountEntryForPhoneAccount(PhoneAccountHandle handle) {
+    boolean hasAccountEntryForPhoneAccount(PhoneAccountHandle handle) {
         for (AccountEntry entry : mAccounts) {
             if (entry.getPhoneAccountHandle().equals(handle)) {
                 return true;
diff --git a/src/com/android/services/telephony/TelephonyConnectionService.java b/src/com/android/services/telephony/TelephonyConnectionService.java
index 57f40e9..4f45322 100644
--- a/src/com/android/services/telephony/TelephonyConnectionService.java
+++ b/src/com/android/services/telephony/TelephonyConnectionService.java
@@ -230,7 +230,16 @@
             ConnectionRequest request) {
         Log.i(this, "onCreateIncomingConnection, request: " + request);
 
-        Phone phone = getPhoneForAccount(request.getAccountHandle(), false);
+        // Check if Incoming Emergency Call is being placed on the Telephony Emergency PhoneAccount
+        PhoneAccountHandle accountHandle = request.getAccountHandle();
+        boolean isEmergency = false;
+        if (accountHandle != null && TelecomAccountRegistry.EMERGENCY_ACCOUNT_HANDLE_ID.equals(
+                accountHandle.getId())) {
+            Log.i(this, "Emergency PhoneAccountHandle is being used for incoming call... " +
+                    "Treat as an Emergency Call.");
+            isEmergency = true;
+        }
+        Phone phone = getPhoneForAccount(accountHandle, isEmergency);
         if (phone == null) {
             return Connection.createFailedConnection(
                     DisconnectCauseUtil.toTelecomDisconnectCause(
@@ -268,8 +277,16 @@
     public Connection onCreateUnknownConnection(PhoneAccountHandle connectionManagerPhoneAccount,
             ConnectionRequest request) {
         Log.i(this, "onCreateUnknownConnection, request: " + request);
-
-        Phone phone = getPhoneForAccount(request.getAccountHandle(), false);
+        // Check if Unknown Call is being placed on the Telephony Emergency PhoneAccount
+        PhoneAccountHandle accountHandle = request.getAccountHandle();
+        boolean isEmergency = false;
+        if (accountHandle != null && TelecomAccountRegistry.EMERGENCY_ACCOUNT_HANDLE_ID.equals(
+                accountHandle.getId())) {
+            Log.i(this, "Emergency PhoneAccountHandle is being used for unknown call... " +
+                    "Treat as an Emergency Call.");
+            isEmergency = true;
+        }
+        Phone phone = getPhoneForAccount(accountHandle, isEmergency);
         if (phone == null) {
             return Connection.createFailedConnection(
                     DisconnectCauseUtil.toTelecomDisconnectCause(