Merge "packages/services/Telephony: Set LOCAL_SDK_VERSION where possible."
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 3665284..f86cdef 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -181,6 +181,7 @@
     <uses-permission android:name="android.permission.MANAGE_NETWORK_POLICY" />
     <uses-permission android:name="android.permission.READ_NETWORK_USAGE_HISTORY" />
     <uses-permission android:name="android.permission.BIND_TELEPHONY_DATA_SERVICE" />
+    <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
 
     <application android:name="PhoneApp"
             android:persistent="true"
diff --git a/src/com/android/phone/LocationAccessPolicy.java b/src/com/android/phone/LocationAccessPolicy.java
deleted file mode 100644
index 6f2a5ec..0000000
--- a/src/com/android/phone/LocationAccessPolicy.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.phone;
-
-import android.Manifest;
-import android.annotation.NonNull;
-import android.annotation.UserIdInt;
-import android.app.ActivityManager;
-import android.app.AppOpsManager;
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.content.pm.UserInfo;
-import android.os.Build;
-import android.os.UserHandle;
-import android.os.UserManager;
-import android.provider.Settings;
-
-import java.util.List;
-
-/**
- * Helper for performing location access checks.
- */
-final class LocationAccessPolicy {
-
-    private LocationAccessPolicy() {
-        /* do nothing - hide ctor */
-    }
-
-    /**
-     * API to determine if the caller has permissions to get cell location.
-     *
-     * @param pkgName Package name of the application requesting access
-     * @param uid The uid of the package
-     * @param message Message to add to the exception if no location permission
-     * @return boolean true or false if permissions is granted
-     */
-    static boolean canAccessCellLocation(@NonNull Context context, @NonNull String pkgName,
-            int uid, String message) throws SecurityException {
-        context.getSystemService(AppOpsManager.class).checkPackage(uid, pkgName);
-        // We always require the location permission and also require the
-        // location mode to be on for non-legacy apps. Legacy apps are
-        // required to be in the foreground to at least mitigate the case
-        // where a legacy app the user is not using tracks their location.
-
-        // Grating ACCESS_FINE_LOCATION to an app automatically grants it ACCESS_COARSE_LOCATION.
-        context.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION, message);
-        final int opCode = AppOpsManager.permissionToOpCode(
-                Manifest.permission.ACCESS_COARSE_LOCATION);
-        if (opCode != AppOpsManager.OP_NONE && context.getSystemService(AppOpsManager.class)
-                .noteOp(opCode, uid, pkgName) != AppOpsManager.MODE_ALLOWED) {
-            return false;
-        }
-        if (!isLocationModeEnabled(context, UserHandle.getUserId(uid))
-                && !isLegacyForeground(context, pkgName)) {
-            return false;
-        }
-        // If the user or profile is current, permission is granted.
-        // Otherwise, uid must have INTERACT_ACROSS_USERS_FULL permission.
-        return isCurrentProfile(context, uid) || checkInteractAcrossUsersFull(context);
-    }
-
-    private static boolean isLocationModeEnabled(@NonNull Context context, @UserIdInt int userId) {
-        return Settings.Secure.getIntForUser(context.getContentResolver(),
-                Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF, userId)
-                != Settings.Secure.LOCATION_MODE_OFF;
-    }
-
-    private static boolean isLegacyForeground(@NonNull Context context, @NonNull String pkgName) {
-        return isLegacyVersion(context, pkgName) && isForegroundApp(context, pkgName);
-    }
-
-    private static boolean isLegacyVersion(@NonNull Context context, @NonNull String pkgName) {
-        try {
-            if (context.getPackageManager().getApplicationInfo(pkgName, 0)
-                    .targetSdkVersion <= Build.VERSION_CODES.O) {
-                return true;
-            }
-        } catch (PackageManager.NameNotFoundException e) {
-            // In case of exception, assume known app (more strict checking)
-            // Note: This case will never happen since checkPackage is
-            // called to verify validity before checking app's version.
-        }
-        return false;
-    }
-
-    private static boolean isForegroundApp(@NonNull Context context, @NonNull String pkgName) {
-        final ActivityManager am = context.getSystemService(ActivityManager.class);
-        final List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
-        if (!tasks.isEmpty()) {
-            return pkgName.equals(tasks.get(0).topActivity.getPackageName());
-        }
-        return false;
-    }
-
-    private static boolean checkInteractAcrossUsersFull(@NonNull Context context) {
-        return context.checkCallingOrSelfPermission(
-                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
-                == PackageManager.PERMISSION_GRANTED;
-    }
-
-    private static boolean isCurrentProfile(@NonNull Context context, int uid) {
-        final int currentUser = ActivityManager.getCurrentUser();
-        final int callingUserId = UserHandle.getUserId(uid);
-        if (callingUserId == currentUser) {
-            return true;
-        } else {
-            List<UserInfo> userProfiles = context.getSystemService(
-                    UserManager.class).getProfiles(currentUser);
-            for (UserInfo user: userProfiles) {
-                if (user.id == callingUserId) {
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-}
diff --git a/src/com/android/phone/PhoneInterfaceManager.java b/src/com/android/phone/PhoneInterfaceManager.java
old mode 100644
new mode 100755
index 8ed8a7c..e8d48b8
--- a/src/com/android/phone/PhoneInterfaceManager.java
+++ b/src/com/android/phone/PhoneInterfaceManager.java
@@ -55,6 +55,7 @@
 import android.telephony.CellInfo;
 import android.telephony.ClientRequestStats;
 import android.telephony.IccOpenLogicalChannelResponse;
+import android.telephony.LocationAccessPolicy;
 import android.telephony.ModemActivityInfo;
 import android.telephony.NeighboringCellInfo;
 import android.telephony.NetworkScanRequest;
@@ -101,6 +102,7 @@
 import com.android.internal.telephony.RIL;
 import com.android.internal.telephony.RILConstants;
 import com.android.internal.telephony.SubscriptionController;
+import com.android.internal.telephony.TelephonyPermissions;
 import com.android.internal.telephony.TelephonyProperties;
 import com.android.internal.telephony.euicc.EuiccConnector;
 import com.android.internal.telephony.uicc.IccIoResult;
@@ -109,6 +111,7 @@
 import com.android.internal.telephony.uicc.UiccCard;
 import com.android.internal.telephony.uicc.UiccCardApplication;
 import com.android.internal.telephony.uicc.UiccController;
+import com.android.internal.telephony.uicc.UiccProfile;
 import com.android.internal.telephony.uicc.UiccSlot;
 import com.android.internal.telephony.util.VoicemailNotificationSettingsUtil;
 import com.android.internal.util.HexDump;
@@ -624,7 +627,7 @@
                     uiccCard = getUiccCardFromRequest(request);
                     if (uiccCard == null) {
                         loge("iccCloseLogicalChannel: No UICC");
-                        request.result = new IccIoResult(0x6F, 0, (byte[])null);
+                        request.result = false;
                         synchronized (request) {
                             request.notifyAll();
                         }
@@ -1253,7 +1256,8 @@
 
     @Override
     public boolean isOffhookForSubscriber(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "isOffhookForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "isOffhookForSubscriber")) {
             return false;
         }
 
@@ -1272,7 +1276,8 @@
 
     @Override
     public boolean isRingingForSubscriber(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "isRingingForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "isRingingForSubscriber")) {
             return false;
         }
 
@@ -1291,7 +1296,8 @@
 
     @Override
     public boolean isIdleForSubscriber(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "isIdleForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "isIdleForSubscriber")) {
             return false;
         }
 
@@ -1466,7 +1472,8 @@
 
     @Override
     public boolean isRadioOnForSubscriber(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "isRadioOnForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "isRadioOnForSubscriber")) {
             return false;
         }
         return isRadioOnForSubscriber(subId);
@@ -1653,8 +1660,10 @@
 
     @Override
     public Bundle getCellLocation(String callingPackage) {
+        mPhone.getContext().getSystemService(AppOpsManager.class)
+                .checkPackage(Binder.getCallingUid(), callingPackage);
         if (!LocationAccessPolicy.canAccessCellLocation(mPhone.getContext(),
-                callingPackage, Binder.getCallingUid(), "getCellLocation")) {
+                callingPackage, Binder.getCallingUid(),Binder.getCallingPid())) {
             return null;
         }
 
@@ -1721,8 +1730,10 @@
     @Override
     @SuppressWarnings("unchecked")
     public List<NeighboringCellInfo> getNeighboringCellInfo(String callingPackage) {
+        mPhone.getContext().getSystemService(AppOpsManager.class)
+                .checkPackage(Binder.getCallingUid(), callingPackage);
         if (!LocationAccessPolicy.canAccessCellLocation(mPhone.getContext(),
-                callingPackage, Binder.getCallingUid(), "getNeighboringCellInfo")) {
+                callingPackage, Binder.getCallingUid(), Binder.getCallingPid())) {
             return null;
         }
 
@@ -1749,8 +1760,10 @@
 
     @Override
     public List<CellInfo> getAllCellInfo(String callingPackage) {
+        mPhone.getContext().getSystemService(AppOpsManager.class)
+                .checkPackage(Binder.getCallingUid(), callingPackage);
         if (!LocationAccessPolicy.canAccessCellLocation(mPhone.getContext(),
-                callingPackage, Binder.getCallingUid(), "getAllCellInfo")) {
+                callingPackage, Binder.getCallingUid(), Binder.getCallingPid())) {
             return null;
         }
 
@@ -1773,16 +1786,18 @@
 
     @Override
     public String getImeiForSlot(int slotIndex, String callingPackage) {
-      if (!canReadPhoneState(callingPackage, "getImeiForSlot")) {
-          return null;
-      }
-      Phone phone = PhoneFactory.getPhone(slotIndex);
-      return phone == null ? null : phone.getImei();
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getImeiForSlot")) {
+            return null;
+        }
+        Phone phone = PhoneFactory.getPhone(slotIndex);
+        return phone == null ? null : phone.getImei();
     }
 
     @Override
     public String getMeidForSlot(int slotIndex, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getMeidForSlot")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getMeidForSlot")) {
             return null;
         }
         Phone phone = PhoneFactory.getPhone(slotIndex);
@@ -1791,11 +1806,12 @@
 
     @Override
     public String getDeviceSoftwareVersionForSlot(int slotIndex, String callingPackage) {
-      if (!canReadPhoneState(callingPackage, "getDeviceSoftwareVersionForSlot")) {
-          return null;
-      }
-      Phone phone = PhoneFactory.getPhone(slotIndex);
-      return phone == null ? null : phone.getDeviceSvn();
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getDeviceSoftwareVersionForSlot")) {
+            return null;
+        }
+        Phone phone = PhoneFactory.getPhone(slotIndex);
+        return phone == null ? null : phone.getDeviceSvn();
     }
 
     @Override
@@ -1824,35 +1840,6 @@
     }
 
     /**
-     * Make sure either system app or the caller has carrier privilege.
-     *
-     * @throws SecurityException if the caller does not have the required permission/privilege
-     */
-    private void enforceModifyPermissionOrCarrierPrivilege(int subId) {
-        int permission = mApp.checkCallingOrSelfPermission(
-                android.Manifest.permission.MODIFY_PHONE_STATE);
-        if (permission == PackageManager.PERMISSION_GRANTED) {
-            return;
-        }
-
-        log("No modify permission, check carrier privilege next.");
-        enforceCarrierPrivilege(subId);
-    }
-
-    /**
-     * Make sure the caller has carrier privilege.
-     *
-     * @throws SecurityException if the caller does not have the required permission
-     */
-    private void enforceCarrierPrivilege(int subId) {
-        if (getCarrierPrivilegeStatus(subId) !=
-                    TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
-            loge("No Carrier Privilege.");
-            throw new SecurityException("No Carrier Privilege.");
-        }
-    }
-
-    /**
      * Make sure the caller has the CALL_PHONE permission.
      *
      * @throws SecurityException if the caller does not have the required permission
@@ -1912,7 +1899,8 @@
 
     @Override
     public int getCdmaEriIconIndexForSubscriber(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getCdmaEriIconIndexForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getCdmaEriIconIndexForSubscriber")) {
             return -1;
         }
         final Phone phone = getPhone(subId);
@@ -1935,7 +1923,8 @@
 
     @Override
     public int getCdmaEriIconModeForSubscriber(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getCdmaEriIconModeForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getCdmaEriIconModeForSubscriber")) {
             return -1;
         }
         final Phone phone = getPhone(subId);
@@ -1956,7 +1945,8 @@
 
     @Override
     public String getCdmaEriTextForSubscriber(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getCdmaEriIconTextForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getCdmaEriIconTextForSubscriber")) {
             return null;
         }
         final Phone phone = getPhone(subId);
@@ -1972,7 +1962,8 @@
      */
     @Override
     public String getCdmaMdn(int subId) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "getCdmaMdn");
         final Phone phone = getPhone(subId);
         if (mPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA && phone != null) {
             return phone.getLine1Number();
@@ -1986,7 +1977,8 @@
      */
     @Override
     public String getCdmaMin(int subId) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "getCdmaMin");
         final Phone phone = getPhone(subId);
         if (phone != null && phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
             return phone.getCdmaMin();
@@ -2007,7 +1999,7 @@
      */
     @Override
     public boolean setVoiceMailNumber(int subId, String alphaTag, String number) {
-        enforceCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfCarrierPrivilege(subId, "setVoiceMailNumber");
         Boolean success = (Boolean) sendRequest(CMD_SET_VOICEMAIL_NUMBER,
                 new Pair<String, String>(alphaTag, number), new Integer(subId));
         return success;
@@ -2030,7 +2022,8 @@
     @Override
     public String getVisualVoicemailPackageName(String callingPackage, int subId) {
         mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
-        if (!canReadPhoneState(callingPackage, "getVisualVoicemailPackageName")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getVisualVoicemailPackageName")) {
             return null;
         }
         return RemoteVvmTaskManager.getRemotePackage(mPhone.getContext(), subId).getPackageName();
@@ -2094,7 +2087,8 @@
      */
     @Override
     public void setVoiceActivationState(int subId, int activationState) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "setVoiceActivationState");
         final Phone phone = getPhone(subId);
         if (phone != null) {
             phone.setVoiceActivationState(activationState);
@@ -2108,7 +2102,8 @@
      */
     @Override
     public void setDataActivationState(int subId, int activationState) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "setDataActivationState");
         final Phone phone = getPhone(subId);
         if (phone != null) {
             phone.setDataActivationState(activationState);
@@ -2122,7 +2117,8 @@
      */
     @Override
     public int getVoiceActivationState(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getVoiceActivationStateForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getVoiceActivationStateForSubscriber")) {
             return TelephonyManager.SIM_ACTIVATION_STATE_UNKNOWN;
         }
         final Phone phone = getPhone(subId);
@@ -2138,7 +2134,8 @@
      */
     @Override
     public int getDataActivationState(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getDataActivationStateForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getDataActivationStateForSubscriber")) {
             return TelephonyManager.SIM_ACTIVATION_STATE_UNKNOWN;
         }
         final Phone phone = getPhone(subId);
@@ -2189,7 +2186,8 @@
         mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
         String defaultDialer = TelecomManager.from(mPhone.getContext()).getDefaultDialerPackage();
         if (!TextUtils.equals(callingPackage, defaultDialer)) {
-            enforceCarrierPrivilege(getDefaultSubscription());
+            TelephonyPermissions.enforceCallingOrSelfCarrierPrivilege(
+                    getDefaultSubscription(), "sendDialerSpecialCode");
         }
         mPhone.sendDialerSpecialCode(inputCode);
     }
@@ -2215,7 +2213,8 @@
      */
     @Override
     public int getNetworkTypeForSubscriber(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getNetworkTypeForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getNetworkTypeForSubscriber")) {
             return TelephonyManager.NETWORK_TYPE_UNKNOWN;
         }
 
@@ -2240,7 +2239,8 @@
      */
     @Override
     public int getDataNetworkTypeForSubscriber(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getDataNetworkTypeForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getDataNetworkTypeForSubscriber")) {
             return TelephonyManager.NETWORK_TYPE_UNKNOWN;
         }
 
@@ -2257,7 +2257,8 @@
      */
     @Override
     public int getVoiceNetworkTypeForSubscriber(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getDataNetworkTypeForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getDataNetworkTypeForSubscriber")) {
             return TelephonyManager.NETWORK_TYPE_UNKNOWN;
         }
 
@@ -2307,7 +2308,8 @@
 
     @Override
     public int getLteOnCdmaModeForSubscriber(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getLteOnCdmaModeForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getLteOnCdmaModeForSubscriber")) {
             return PhoneConstants.LTE_ON_CDMA_UNKNOWN;
         }
 
@@ -2364,7 +2366,8 @@
     @Override
     public IccOpenLogicalChannelResponse iccOpenLogicalChannel(
             int subId, String callingPackage, String aid, int p2) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "iccOpenLogicalChannel");
 
         if (TextUtils.equals(ISDR_AID, aid)) {
             // Only allows LPA to open logical channel to ISD-R.
@@ -2387,7 +2390,8 @@
 
     @Override
     public boolean iccCloseLogicalChannel(int subId, int channel) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "iccCloseLogicalChannel");
 
         if (DBG) log("iccCloseLogicalChannel: subId=" + subId + " chnl=" + channel);
         if (channel < 0) {
@@ -2401,7 +2405,8 @@
     @Override
     public String iccTransmitApduLogicalChannel(int subId, int channel, int cla,
             int command, int p1, int p2, int p3, String data) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "iccTransmitApduLogicalChannel");
 
         if (DBG) {
             log("iccTransmitApduLogicalChannel: subId=" + subId + " chnl=" + channel +
@@ -2429,7 +2434,8 @@
     @Override
     public String iccTransmitApduBasicChannel(int subId, String callingPackage, int cla,
             int command, int p1, int p2, int p3, String data) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "iccTransmitApduBasicChannel");
 
         if (command == SELECT_COMMAND && p1 == SELECT_P1 && p2 == SELECT_P2 && p3 == SELECT_P3
                 && TextUtils.equals(ISDR_AID, data)) {
@@ -2465,7 +2471,8 @@
     @Override
     public byte[] iccExchangeSimIO(int subId, int fileID, int command, int p1, int p2, int p3,
             String filePath) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "iccExchangeSimIO");
 
         if (DBG) {
             log("Exchange SIM_IO " + subId + ":" + fileID + ":" + command + " " +
@@ -2518,7 +2525,8 @@
 
     @Override
     public String sendEnvelopeWithStatus(int subId, String content) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "sendEnvelopeWithStatus");
 
         IccIoResult response = (IccIoResult)sendRequest(CMD_SEND_ENVELOPE, content, subId);
         if (response.payload == null) {
@@ -2541,7 +2549,8 @@
      */
     @Override
     public String nvReadItem(int itemID) {
-        enforceModifyPermissionOrCarrierPrivilege(getDefaultSubscription());
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, getDefaultSubscription(), "nvReadItem");
         if (DBG) log("nvReadItem: item " + itemID);
         String value = (String) sendRequest(CMD_NV_READ_ITEM, itemID);
         if (DBG) log("nvReadItem: item " + itemID + " is \"" + value + '"');
@@ -2558,7 +2567,8 @@
      */
     @Override
     public boolean nvWriteItem(int itemID, String itemValue) {
-        enforceModifyPermissionOrCarrierPrivilege(getDefaultSubscription());
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, getDefaultSubscription(), "nvWriteItem");
         if (DBG) log("nvWriteItem: item " + itemID + " value \"" + itemValue + '"');
         Boolean success = (Boolean) sendRequest(CMD_NV_WRITE_ITEM,
                 new Pair<Integer, String>(itemID, itemValue));
@@ -2575,7 +2585,8 @@
      */
     @Override
     public boolean nvWriteCdmaPrl(byte[] preferredRoamingList) {
-        enforceModifyPermissionOrCarrierPrivilege(getDefaultSubscription());
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, getDefaultSubscription(), "nvWriteCdmaPrl");
         if (DBG) log("nvWriteCdmaPrl: value: " + HexDump.toHexString(preferredRoamingList));
         Boolean success = (Boolean) sendRequest(CMD_NV_WRITE_CDMA_PRL, preferredRoamingList);
         if (DBG) log("nvWriteCdmaPrl: " + (success ? "ok" : "fail"));
@@ -2591,7 +2602,8 @@
      */
     @Override
     public boolean nvResetConfig(int resetType) {
-        enforceModifyPermissionOrCarrierPrivilege(getDefaultSubscription());
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, getDefaultSubscription(), "nvResetConfig");
         if (DBG) log("nvResetConfig: type " + resetType);
         Boolean success = (Boolean) sendRequest(CMD_NV_RESET_CONFIG, resetType);
         if (DBG) log("nvResetConfig: type " + resetType + ' ' + (success ? "ok" : "fail"));
@@ -2608,7 +2620,8 @@
     }
 
     public String[] getPcscfAddress(String apnType, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getPcscfAddress")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getPcscfAddress")) {
             return new String[0];
         }
 
@@ -2685,7 +2698,8 @@
      */
     @Override
     public void setNetworkSelectionModeAutomatic(int subId) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "setNetworkSelectionModeAutomatic");
         if (DBG) log("setNetworkSelectionModeAutomatic: subId " + subId);
         sendRequest(CMD_SET_NETWORK_SELECTION_MODE_AUTOMATIC, null, subId);
     }
@@ -2696,7 +2710,8 @@
     @Override
     public boolean setNetworkSelectionModeManual(int subId, String operatorNumeric,
             boolean persistSelection) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "setNetworkSelectionModeManual");
         OperatorInfo operator = new OperatorInfo(
                 /* operatorAlphaLong */ "",
                 /* operatorAlphaShort */ "",
@@ -2712,7 +2727,8 @@
      */
     @Override
     public CellNetworkScanResult getCellNetworkScanResults(int subId) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "getCellNetworkScanResults");
         if (DBG) log("getCellNetworkScanResults: subId " + subId);
         CellNetworkScanResult result = (CellNetworkScanResult) sendRequest(
                 CMD_PERFORM_NETWORK_SCAN, null, subId);
@@ -2731,7 +2747,8 @@
     @Override
     public int requestNetworkScan(int subId, NetworkScanRequest request, Messenger messenger,
             IBinder binder) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "requestNetworkScan");
         return mNetworkScanRequestTracker.startNetworkScan(
                 request, messenger, binder, getPhone(subId));
     }
@@ -2744,7 +2761,8 @@
      */
     @Override
     public void stopNetworkScan(int subId, int scanId) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "stopNetworkScan");
         mNetworkScanRequestTracker.stopNetworkScan(scanId);
     }
 
@@ -2756,7 +2774,8 @@
      */
     @Override
     public int getCalculatedPreferredNetworkType(String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getCalculatedPreferredNetworkType")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getCalculatedPreferredNetworkType")) {
             return RILConstants.PREFERRED_NETWORK_MODE;
         }
 
@@ -2771,7 +2790,8 @@
      */
     @Override
     public int getPreferredNetworkType(int subId) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "getPreferredNetworkType");
         if (DBG) log("getPreferredNetworkType");
         int[] result = (int[]) sendRequest(CMD_GET_PREFERRED_NETWORK_TYPE, null, subId);
         int networkType = (result != null ? result[0] : -1);
@@ -2788,7 +2808,8 @@
      */
     @Override
     public boolean setPreferredNetworkType(int subId, int networkType) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "setPreferredNetworkType");
         if (DBG) log("setPreferredNetworkType: subId " + subId + " type " + networkType);
         Boolean success = (Boolean) sendRequest(CMD_SET_PREFERRED_NETWORK_TYPE, networkType, subId);
         if (DBG) log("setPreferredNetworkType: " + (success ? "ok" : "fail"));
@@ -2828,7 +2849,8 @@
      */
     @Override
     public void setUserDataEnabled(int subId, boolean enable) {
-        enforceModifyPermissionOrCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, subId, "setUserDataEnabled");
         int phoneId = mSubscriptionController.getPhoneId(subId);
         if (DBG) log("setUserDataEnabled: subId=" + subId + " phoneId=" + phoneId);
         Phone phone = PhoneFactory.getPhone(phoneId);
@@ -2871,7 +2893,8 @@
             mApp.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NETWORK_STATE,
                     null);
         } catch (Exception e) {
-            enforceModifyPermissionOrCarrierPrivilege(subId);
+            TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                    mApp, subId, "isUserDataEnabled");
         }
         int phoneId = mSubscriptionController.getPhoneId(subId);
         if (DBG) log("isUserDataEnabled: subId=" + subId + " phoneId=" + phoneId);
@@ -2902,7 +2925,8 @@
             mApp.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NETWORK_STATE,
                     null);
         } catch (Exception e) {
-            enforceModifyPermissionOrCarrierPrivilege(subId);
+            TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                    mApp, subId, "isDataEnabled");
         }
         int phoneId = mSubscriptionController.getPhoneId(subId);
         if (DBG) log("isDataEnabled: subId=" + subId + " phoneId=" + phoneId);
@@ -2934,6 +2958,22 @@
     }
 
     @Override
+    public int getCarrierPrivilegeStatusForUid(int subId, int uid) {
+        final Phone phone = getPhone(subId);
+        if (phone == null) {
+            loge("getCarrierPrivilegeStatus: Invalid subId");
+            return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
+        }
+        UiccProfile profile =
+                UiccController.getInstance().getUiccProfileForPhone(phone.getPhoneId());
+        if (profile == null) {
+            loge("getCarrierPrivilegeStatus: No UICC");
+            return TelephonyManager.CARRIER_PRIVILEGE_STATUS_RULES_NOT_LOADED;
+        }
+        return profile.getCarrierPrivilegeStatusForUid(phone.getContext().getPackageManager(), uid);
+    }
+
+    @Override
     public int checkCarrierPrivilegesForPackage(String pkgName) {
         if (TextUtils.isEmpty(pkgName))
             return TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS;
@@ -3032,7 +3072,8 @@
     @Override
     public boolean setLine1NumberForDisplayForSubscriber(int subId, String alphaTag,
             String number) {
-        enforceCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfCarrierPrivilege(
+                subId, "setLine1NumberForDisplayForSubscriber");
 
         final String iccId = getIccId(subId);
         final Phone phone = getPhone(subId);
@@ -3078,7 +3119,8 @@
     @Override
     public String getLine1NumberForDisplay(int subId, String callingPackage) {
         // This is open to apps with WRITE_SMS.
-        if (!canReadPhoneNumber(callingPackage, "getLine1NumberForDisplay")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneNumber(
+                mApp, callingPackage, "getLine1NumberForDisplay")) {
             if (DBG_MERGE) log("getLine1NumberForDisplay returning null due to permission");
             return null;
         }
@@ -3098,7 +3140,8 @@
 
     @Override
     public String getLine1AlphaTagForDisplay(int subId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getLine1AlphaTagForDisplay")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getLine1AlphaTagForDisplay")) {
             return null;
         }
 
@@ -3112,7 +3155,8 @@
 
     @Override
     public String[] getMergedSubscriberIds(String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getMergedSubscriberIds")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getMergedSubscriberIds")) {
             return null;
         }
         final Context context = mPhone.getContext();
@@ -3185,7 +3229,8 @@
 
     @Override
     public boolean setOperatorBrandOverride(int subId, String brand) {
-        enforceCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfCarrierPrivilege(
+                subId, "setOperatorBrandOverride");
         final Phone phone = getPhone(subId);
         return phone == null ? false : phone.setOperatorBrandOverride(brand);
     }
@@ -3194,7 +3239,7 @@
     public boolean setRoamingOverride(int subId, List<String> gsmRoamingList,
             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
             List<String> cdmaNonRoamingList) {
-        enforceCarrierPrivilege(subId);
+        TelephonyPermissions.enforceCallingOrSelfCarrierPrivilege(subId, "setRoamingOverride");
         final Phone phone = getPhone(subId);
         if (phone == null) {
             return false;
@@ -3214,7 +3259,8 @@
 
     @Override
     public int getRadioAccessFamily(int phoneId, String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getRadioAccessFamily")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getRadioAccessFamily")) {
             return RadioAccessFamily.RAF_UNKNOWN;
         }
 
@@ -3229,7 +3275,8 @@
 
     @Override
     public boolean isVideoCallingEnabled(String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "isVideoCallingEnabled")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "isVideoCallingEnabled")) {
             return false;
         }
 
@@ -3283,7 +3330,8 @@
      */
     @Override
     public String getDeviceId(String callingPackage) {
-        if (!canReadPhoneState(callingPackage, "getDeviceId")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getDeviceId")) {
             return null;
         }
 
@@ -3364,72 +3412,6 @@
         }
     }
 
-    private boolean canReadPhoneState(String callingPackage, String message) {
-        try {
-            mApp.enforceCallingOrSelfPermission(
-                    android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, message);
-
-            // SKIP checking for run-time permission since caller or self has PRIVILEDGED permission
-            return true;
-        } catch (SecurityException e) {
-            mApp.enforceCallingOrSelfPermission(android.Manifest.permission.READ_PHONE_STATE,
-                    message);
-        }
-
-        if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
-                callingPackage) != AppOpsManager.MODE_ALLOWED) {
-            return false;
-        }
-
-        return true;
-    }
-
-    /**
-     * Besides READ_PHONE_STATE, WRITE_SMS and READ_SMS also allow apps to get phone numbers.
-     */
-    private boolean canReadPhoneNumber(String callingPackage, String message) {
-        // Default SMS app can always read it.
-        if (mAppOps.noteOp(AppOpsManager.OP_WRITE_SMS,
-                Binder.getCallingUid(), callingPackage) == AppOpsManager.MODE_ALLOWED) {
-            return true;
-        }
-
-        try {
-            return canReadPhoneState(callingPackage, message);
-        } catch (SecurityException readPhoneStateSecurityException) {
-        }
-        // Can be read with READ_SMS too.
-        try {
-            mApp.enforceCallingOrSelfPermission(android.Manifest.permission.READ_SMS, message);
-            int opCode = mAppOps.permissionToOpCode(android.Manifest.permission.READ_SMS);
-            if (opCode != AppOpsManager.OP_NONE) {
-                return mAppOps.noteOp(opCode, Binder.getCallingUid(), callingPackage)
-                        == AppOpsManager.MODE_ALLOWED;
-            } else {
-                return true;
-            }
-        } catch (SecurityException readSmsSecurityException) {
-        }
-        // Can be read with READ_PHONE_NUMBERS too.
-        try {
-            mApp.enforceCallingOrSelfPermission(android.Manifest.permission.READ_PHONE_NUMBERS,
-                    message);
-            int opCode = mAppOps.permissionToOpCode(android.Manifest.permission.READ_PHONE_NUMBERS);
-            if (opCode != AppOpsManager.OP_NONE) {
-                return mAppOps.noteOp(opCode, Binder.getCallingUid(), callingPackage)
-                        == AppOpsManager.MODE_ALLOWED;
-            } else {
-                return true;
-            }
-        } catch (SecurityException readPhoneNumberSecurityException) {
-        }
-
-        throw new SecurityException(message + ": Neither user " + Binder.getCallingUid() +
-                " nor current process has" + android.Manifest.permission.READ_PHONE_STATE +
-                ", " + android.Manifest.permission.READ_SMS + ", or " +
-                android.Manifest.permission.READ_PHONE_NUMBERS);
-    }
-
     @Override
     public void factoryReset(int subId) {
         enforceConnectivityInternalPermission();
@@ -3560,7 +3542,8 @@
     @Override
     public ServiceState getServiceStateForSubscriber(int subId, String callingPackage) {
 
-        if (!canReadPhoneState(callingPackage, "getServiceStateForSubscriber")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getServiceStateForSubscriber")) {
             return null;
         }
 
@@ -3607,8 +3590,9 @@
         mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
         if (!TextUtils.equals(callingPackage,
                 TelecomManager.from(mPhone.getContext()).getDefaultDialerPackage())) {
-            enforceModifyPermissionOrCarrierPrivilege(
-                    PhoneUtils.getSubIdForPhoneAccountHandle(phoneAccountHandle));
+            TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                    mApp, PhoneUtils.getSubIdForPhoneAccountHandle(phoneAccountHandle),
+                    "setVoicemailRingtoneUri");
         }
         Phone phone = PhoneUtils.getPhoneForPhoneAccountHandle(phoneAccountHandle);
         if (phone == null){
@@ -3651,8 +3635,9 @@
         mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
         if (!TextUtils.equals(callingPackage,
                 TelecomManager.from(mPhone.getContext()).getDefaultDialerPackage())) {
-            enforceModifyPermissionOrCarrierPrivilege(
-                    PhoneUtils.getSubIdForPhoneAccountHandle(phoneAccountHandle));
+            TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                    mApp, PhoneUtils.getSubIdForPhoneAccountHandle(phoneAccountHandle),
+                    "setVoicemailVibrationEnabled");
         }
 
         Phone phone = PhoneUtils.getPhoneForPhoneAccountHandle(phoneAccountHandle);
@@ -3775,7 +3760,8 @@
      */
     @Override
     public List<TelephonyHistogram> getTelephonyHistograms() {
-        enforceModifyPermissionOrCarrierPrivilege(getDefaultSubscription());
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(
+                mApp, getDefaultSubscription(), "getTelephonyHistograms");
         return RIL.getTelephonyRILTimingHistograms();
     }
 
@@ -3942,7 +3928,8 @@
      */
     @Override
     public List<ClientRequestStats> getClientRequestStats(String callingPackage, int subId) {
-        if (!canReadPhoneState(callingPackage, "getClientRequestStats")) {
+        if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
+                mApp, callingPackage, "getClientRequestStats")) {
             return null;
         }
 
diff --git a/src/com/android/phone/settings/AccessibilitySettingsFragment.java b/src/com/android/phone/settings/AccessibilitySettingsFragment.java
index 7ede23a..8ec747c 100644
--- a/src/com/android/phone/settings/AccessibilitySettingsFragment.java
+++ b/src/com/android/phone/settings/AccessibilitySettingsFragment.java
@@ -106,9 +106,7 @@
             // TODO: this is going to be a on/off switch for now. Ask UX about how to integrate
             // this settings with TTY
             boolean rttOn = Settings.System.getInt(
-                    mContext.getContentResolver(), Settings.System.RTT_CALLING_MODE,
-                    TelecomManager.TTY_MODE_OFF)
-                    != TelecomManager.TTY_MODE_OFF;
+                    mContext.getContentResolver(), Settings.System.RTT_CALLING_MODE, 0) != 0;
             mButtonRtt.setChecked(rttOn);
         } else {
             getPreferenceScreen().removePreference(mButtonRtt);
@@ -149,8 +147,7 @@
             return true;
         } else if (preference == mButtonRtt) {
             Log.i(LOG_TAG, "RTT setting changed -- now " + mButtonRtt.isChecked());
-            int rttMode = mButtonRtt.isChecked()
-                    ? TelecomManager.TTY_MODE_FULL : TelecomManager.TTY_MODE_OFF;
+            int rttMode = mButtonRtt.isChecked() ? 1 : 0;
             Settings.System.putInt(mContext.getContentResolver(), Settings.System.RTT_CALLING_MODE,
                     rttMode);
             // Update RTT config with IMS Manager
diff --git a/src/com/android/services/telephony/PstnIncomingCallNotifier.java b/src/com/android/services/telephony/PstnIncomingCallNotifier.java
index e007bb4..4dfaf44 100644
--- a/src/com/android/services/telephony/PstnIncomingCallNotifier.java
+++ b/src/com/android/services/telephony/PstnIncomingCallNotifier.java
@@ -36,6 +36,7 @@
 import com.android.internal.telephony.cdma.CdmaCallWaitingNotification;
 import com.android.internal.telephony.imsphone.ImsExternalCallTracker;
 import com.android.internal.telephony.imsphone.ImsExternalConnection;
+import com.android.internal.telephony.imsphone.ImsPhoneConnection;
 import com.android.phone.PhoneUtils;
 
 import com.google.common.base.Preconditions;
@@ -243,6 +244,11 @@
         extras.putLong(TelecomManager.EXTRA_CALL_CREATED_TIME_MILLIS,
                 SystemClock.elapsedRealtime());
 
+        if (connection.getPhoneType() == PhoneConstants.PHONE_TYPE_IMS) {
+            if (((ImsPhoneConnection) connection).isRttEnabledForCall()) {
+                extras.putBoolean(TelecomManager.EXTRA_START_CALL_WITH_RTT, true);
+            }
+        }
         PhoneAccountHandle handle = findCorrectPhoneAccountHandle();
         if (handle == null) {
             try {
diff --git a/src/com/android/services/telephony/TelephonyConnection.java b/src/com/android/services/telephony/TelephonyConnection.java
index b27baed..0fe6980 100644
--- a/src/com/android/services/telephony/TelephonyConnection.java
+++ b/src/com/android/services/telephony/TelephonyConnection.java
@@ -546,6 +546,7 @@
 
         @Override
         public void onRttModifyResponseReceived(int status) {
+            updateConnectionProperties();
             if (status == RttModifyStatus.SESSION_MODIFY_REQUEST_SUCCESS) {
                 sendRttInitiationSuccess();
             } else {
@@ -562,11 +563,13 @@
 
         @Override
         public void onRttInitiated() {
+            updateConnectionProperties();
             sendRttInitiationSuccess();
         }
 
         @Override
         public void onRttTerminated() {
+            updateConnectionProperties();
             sendRttSessionRemotelyTerminated();
         }
     };
@@ -845,7 +848,7 @@
 
     @Override
     public void onStopRtt() {
-        // This is not supported by carriers/vendor yet. No-op for now.
+        Log.i(this, "Stopping RTT currently not supported. Doing nothing.");
     }
 
     @Override
@@ -1003,8 +1006,7 @@
                 mIsCdmaVoicePrivacyEnabled);
         newProperties = changeBitmask(newProperties, PROPERTY_ASSISTED_DIALING_USED,
                 mIsUsingAssistedDialing);
-        newProperties = changeBitmask(newProperties, PROPERTY_IS_RTT,
-                (getConnectionProperties() & PROPERTY_IS_RTT) != 0);
+        newProperties = changeBitmask(newProperties, PROPERTY_IS_RTT, isRtt());
 
         if (getConnectionProperties() != newProperties) {
             setConnectionProperties(newProperties);
@@ -1691,6 +1693,15 @@
     }
 
     /**
+     * Determines if the current connection has RTT enabled.
+     */
+    private boolean isRtt() {
+        return mOriginalConnection != null
+                && mOriginalConnection.getPhoneType() == PhoneConstants.PHONE_TYPE_IMS
+                && ((ImsPhoneConnection) mOriginalConnection).isRttEnabledForCall();
+    }
+
+    /**
      * Determines if the current connection is pullable.
      *
      * A connection is deemed to be pullable if the original connection capabilities state that it
diff --git a/src/com/android/services/telephony/TelephonyConnectionService.java b/src/com/android/services/telephony/TelephonyConnectionService.java
index 2022733..6fd481b 100644
--- a/src/com/android/services/telephony/TelephonyConnectionService.java
+++ b/src/com/android/services/telephony/TelephonyConnectionService.java
@@ -52,6 +52,7 @@
 import com.android.internal.telephony.PhoneFactory;
 import com.android.internal.telephony.imsphone.ImsExternalCallTracker;
 import com.android.internal.telephony.imsphone.ImsPhone;
+import com.android.internal.telephony.imsphone.ImsPhoneConnection;
 import com.android.phone.MMIDialogActivity;
 import com.android.phone.PhoneUtils;
 import com.android.phone.R;
@@ -700,10 +701,11 @@
         int videoState = originalConnection != null ? originalConnection.getVideoState() :
                 VideoProfile.STATE_AUDIO_ONLY;
 
-        Connection connection =
+        TelephonyConnection connection =
                 createConnectionFor(phone, originalConnection, false /* isOutgoing */,
                         request.getAccountHandle(), request.getTelecomCallId(),
                         request.getAddress(), videoState);
+        handleIncomingRtt(request, originalConnection);
         if (connection == null) {
             return Connection.createCanceledConnection();
         } else {
@@ -711,6 +713,36 @@
         }
     }
 
+    private void handleIncomingRtt(ConnectionRequest request,
+            com.android.internal.telephony.Connection originalConnection) {
+        if (originalConnection == null
+                || originalConnection.getPhoneType() != PhoneConstants.PHONE_TYPE_IMS) {
+            if (request.isRequestingRtt()) {
+                Log.w(this, "Requesting RTT on non-IMS call, ignoring");
+            }
+            return;
+        }
+
+        ImsPhoneConnection imsOriginalConnection = (ImsPhoneConnection) originalConnection;
+        if (!request.isRequestingRtt()) {
+            if (imsOriginalConnection.isRttEnabledForCall()) {
+                Log.i(this, "Incoming call requested RTT but was declined");
+            }
+            return;
+        }
+
+        if (!imsOriginalConnection.isRttEnabledForCall()) {
+            if (request.isRequestingRtt()) {
+                Log.w(this, "Incoming call processed as RTT but did not come in as one. Ignoring");
+            }
+            return;
+        }
+
+        Log.i(this, "Setting RTT stream on ImsPhoneConnection");
+        imsOriginalConnection.setCurrentRttTextStream(request.getRttTextStream());
+        imsOriginalConnection.getImsCall().setAnswerWithRtt();
+    }
+
     /**
      * Called by the {@link ConnectionService} when a newly created {@link Connection} has been
      * added to the {@link ConnectionService} and sent to Telecom.  Here it is safe to send
diff --git a/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/EmbmsSampleDownloadService.java b/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/EmbmsSampleDownloadService.java
index 128793f..7bd0f70 100644
--- a/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/EmbmsSampleDownloadService.java
+++ b/testapps/EmbmsServiceTestApp/src/com/android/phone/testapps/embmsmw/EmbmsSampleDownloadService.java
@@ -371,11 +371,8 @@
             c.onProgressUpdated(request, fileToDownload, 10, 10, 10, 10);
         }
         // Take a round-trip through the download request serialization to exercise it
-        DownloadRequest request1 = new DownloadRequest.Builder(request.getSourceUri())
-                .setSubscriptionId(request.getSubscriptionId())
-                .setServiceId(request.getFileServiceId())
-                .setOpaqueData(request.getOpaqueData())
-                .build();
+        DownloadRequest request1 = DownloadRequest.Builder.fromSerializedRequest(
+                request.toByteArray()).build();
 
         Intent downloadResultIntent =
                 new Intent(VendorUtils.ACTION_DOWNLOAD_RESULT_INTERNAL);
diff --git a/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/DownloadCompletionReceiver.java b/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/DownloadCompletionReceiver.java
index 3c94b76..736b912 100644
--- a/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/DownloadCompletionReceiver.java
+++ b/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/DownloadCompletionReceiver.java
@@ -21,14 +21,12 @@
 import android.content.Intent;
 import android.net.Uri;
 import android.telephony.MbmsDownloadSession;
-import android.telephony.mbms.DownloadRequest;
 import android.telephony.mbms.FileInfo;
 
 import java.io.IOException;
 import java.nio.file.FileSystems;
 import java.nio.file.Files;
 import java.nio.file.Path;
-import java.nio.file.StandardCopyOption;
 
 public class DownloadCompletionReceiver extends BroadcastReceiver {
     @Override
@@ -41,22 +39,8 @@
             }
             Uri completedFile = intent.getParcelableExtra(
                     MbmsDownloadSession.EXTRA_MBMS_COMPLETED_FILE_URI);
-            FileInfo completedFileInfo = intent.getParcelableExtra(
-                    MbmsDownloadSession.EXTRA_MBMS_FILE_INFO);
-            DownloadRequest request = intent.getParcelableExtra(
-                    MbmsDownloadSession.EXTRA_MBMS_DOWNLOAD_REQUEST);
 
-            Path destinationFile = getDestinationFile(context,
-                    request.getFileServiceId(), completedFileInfo);
-            Path sourceFile = FileSystems.getDefault().getPath(completedFile.getPath());
-            try {
-                Files.move(sourceFile, destinationFile, StandardCopyOption.REPLACE_EXISTING);
-            } catch (IOException e) {
-                return;
-            }
-
-            EmbmsTestDownloadApp.getInstance().onDownloadDone(
-                    Uri.fromFile(destinationFile.toFile()));
+            EmbmsTestDownloadApp.getInstance().onDownloadDone(completedFile);
         }
     }
 
diff --git a/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/EmbmsTestDownloadApp.java b/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/EmbmsTestDownloadApp.java
index 4083f67..76baf05 100644
--- a/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/EmbmsTestDownloadApp.java
+++ b/testapps/EmbmsTestDownloadApp/src/com/android/phone/testapps/embmsdownload/EmbmsTestDownloadApp.java
@@ -44,6 +44,7 @@
 import android.widget.Toast;
 
 import java.io.File;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
@@ -203,7 +204,7 @@
 
         Button bindButton = (Button) findViewById(R.id.bind_button);
         bindButton.setOnClickListener((view) -> {
-            mDownloadManager = MbmsDownloadSession.create(this, mCallback, mHandler);
+            mDownloadManager = MbmsDownloadSession.create(this, mHandler::post, mCallback);
         });
 
         Button setTempFileRootButton = (Button) findViewById(R.id.set_temp_root_button);
@@ -291,26 +292,28 @@
                         "No DownloadRequest Pending for progress...", Toast.LENGTH_SHORT).show();
                 return;
             }
-            mDownloadManager.registerStateCallback(req, new DownloadStateCallback(
-                    DownloadStateCallback.PROGRESS_UPDATES) {
-                @Override
-                public void onProgressUpdated(DownloadRequest request, FileInfo fileInfo,
-                        int currentDownloadSize, int fullDownloadSize, int currentDecodedSize,
-                        int fullDecodedSize) {
-                    Toast.makeText(EmbmsTestDownloadApp.this,
-                            "Progress Updated (" + fileInfo + ") cd: " + currentDecodedSize
-                                    + " fd: " + fullDownloadSize, Toast.LENGTH_SHORT).show();
-                }
+            mDownloadManager.registerStateCallback(req, sInstance.getMainThreadHandler()::post,
+                    new DownloadStateCallback(DownloadStateCallback.PROGRESS_UPDATES) {
+                        @Override
+                        public void onProgressUpdated(DownloadRequest request, FileInfo fileInfo,
+                                int currentDownloadSize, int fullDownloadSize,
+                                int currentDecodedSize, int fullDecodedSize) {
+                            Toast.makeText(EmbmsTestDownloadApp.this,
+                                    "Progress Updated (" + fileInfo + ") cd: " + currentDecodedSize
+                                            + " fd: " + fullDownloadSize, Toast.LENGTH_SHORT)
+                                    .show();
+                        }
 
-                @Override
-                public void onStateUpdated(DownloadRequest request, FileInfo fileInfo,
-                        @MbmsDownloadSession.DownloadStatus int state) {
-                    // only registered for state callback, this shouldn't happen!
-                    Toast.makeText(EmbmsTestDownloadApp.this,
-                            "State ERROR: received state update for callback that didn't filter it",
-                            Toast.LENGTH_SHORT).show();
-                }
-            }, sInstance.getMainThreadHandler());
+                        @Override
+                        public void onStateUpdated(DownloadRequest request, FileInfo fileInfo,
+                                @MbmsDownloadSession.DownloadStatus int state) {
+                            // only registered for state callback, this shouldn't happen!
+                            Toast.makeText(EmbmsTestDownloadApp.this,
+                                    "State ERROR: received state update for callback that didn't"
+                                            + " filter it",
+                                    Toast.LENGTH_SHORT).show();
+                        }
+                    });
         });
 
         Button registerStateCallback =
@@ -327,26 +330,27 @@
                         "No DownloadRequest Pending for state...", Toast.LENGTH_SHORT).show();
                 return;
             }
-            mDownloadManager.registerStateCallback(req, new DownloadStateCallback(
-                    DownloadStateCallback.STATE_UPDATES) {
-                @Override
-                public void onProgressUpdated(DownloadRequest request, FileInfo fileInfo,
-                        int currentDownloadSize, int fullDownloadSize, int currentDecodedSize,
-                        int fullDecodedSize) {
-                    // only registered for state callback, this shouldn't happen!
-                    Toast.makeText(EmbmsTestDownloadApp.this,
-                            "Progress ERROR: received progress update for callback that didn't "
-                                    + "filter it", Toast.LENGTH_SHORT).show();
-                }
+            mDownloadManager.registerStateCallback(req, sInstance.getMainThreadHandler()::post,
+                    new DownloadStateCallback(DownloadStateCallback.STATE_UPDATES) {
+                        @Override
+                        public void onProgressUpdated(DownloadRequest request, FileInfo fileInfo,
+                                int currentDownloadSize, int fullDownloadSize,
+                                int currentDecodedSize, int fullDecodedSize) {
+                            // only registered for state callback, this shouldn't happen!
+                            Toast.makeText(EmbmsTestDownloadApp.this,
+                                    "Progress ERROR: received progress update for"
+                                            + " callback that didn't "
+                                            + "filter it", Toast.LENGTH_SHORT).show();
+                        }
 
-                @Override
-                public void onStateUpdated(DownloadRequest request, FileInfo fileInfo,
-                        @MbmsDownloadSession.DownloadStatus int state) {
-                    Toast.makeText(EmbmsTestDownloadApp.this,
-                            "State Updated (" + fileInfo + ") state: " + state,
-                            Toast.LENGTH_SHORT).show();
-                }
-            }, sInstance.getMainThreadHandler());
+                        @Override
+                        public void onStateUpdated(DownloadRequest request, FileInfo fileInfo,
+                                @MbmsDownloadSession.DownloadStatus int state) {
+                            Toast.makeText(EmbmsTestDownloadApp.this,
+                                    "State Updated (" + fileInfo + ") state: " + state,
+                                    Toast.LENGTH_SHORT).show();
+                        }
+                    });
         });
 
         Button registerAllCallbacks =
@@ -363,24 +367,26 @@
                         "No DownloadRequest Pending for state...", Toast.LENGTH_SHORT).show();
                 return;
             }
-            mDownloadManager.registerStateCallback(req, new DownloadStateCallback() {
-                @Override
-                public void onProgressUpdated(DownloadRequest request, FileInfo fileInfo,
-                        int currentDownloadSize, int fullDownloadSize, int currentDecodedSize,
-                        int fullDecodedSize) {
-                    Toast.makeText(EmbmsTestDownloadApp.this,
-                            "Progress Updated (" + fileInfo + ") cd: " + currentDecodedSize
-                                    + " fd: " + fullDownloadSize, Toast.LENGTH_SHORT).show();
-                }
+            mDownloadManager.registerStateCallback(req, sInstance.getMainThreadHandler()::post,
+                    new DownloadStateCallback() {
+                        @Override
+                        public void onProgressUpdated(DownloadRequest request, FileInfo fileInfo,
+                                int currentDownloadSize, int fullDownloadSize,
+                                int currentDecodedSize, int fullDecodedSize) {
+                            Toast.makeText(EmbmsTestDownloadApp.this,
+                                    "Progress Updated (" + fileInfo + ") cd: " + currentDecodedSize
+                                            + " fd: " + fullDownloadSize, Toast.LENGTH_SHORT)
+                                    .show();
+                        }
 
-                @Override
-                public void onStateUpdated(DownloadRequest request, FileInfo fileInfo,
-                        @MbmsDownloadSession.DownloadStatus int state) {
-                    Toast.makeText(EmbmsTestDownloadApp.this,
-                            "State Updated (" + fileInfo + ") state: " + state,
-                            Toast.LENGTH_SHORT).show();
-                }
-            }, sInstance.getMainThreadHandler());
+                        @Override
+                        public void onStateUpdated(DownloadRequest request, FileInfo fileInfo,
+                                @MbmsDownloadSession.DownloadStatus int state) {
+                            Toast.makeText(EmbmsTestDownloadApp.this,
+                                    "State Updated (" + fileInfo + ") state: " + state,
+                                    Toast.LENGTH_SHORT).show();
+                        }
+                    });
         });
     }
 
@@ -429,7 +435,8 @@
         Intent completionIntent = new Intent(DOWNLOAD_DONE_ACTION);
         completionIntent.setClass(this, DownloadCompletionReceiver.class);
 
-        DownloadRequest request = new DownloadRequest.Builder(sourceUriBuilder.build())
+        DownloadRequest request = new DownloadRequest.Builder(sourceUriBuilder.build(),
+                getDestination(info.getServiceId()))
                 .setServiceInfo(info)
                 .setAppIntent(completionIntent)
                 .setSubscriptionId(SubscriptionManager.getDefaultSubscriptionId())
@@ -438,4 +445,24 @@
         mDownloadManager.download(request);
         mDownloadRequestAdapter.add(request);
     }
+
+    private Uri getDestination(String serviceId) {
+        File dest;
+        try {
+            if (serviceId.contains("2")) {
+                dest = new File(getFilesDir().getCanonicalFile(), "images/animals/");
+                if (!dest.exists()) {
+                    dest.mkdirs();
+                }
+            } else {
+                dest = new File(getFilesDir().getCanonicalFile(), "images/");
+                if (!dest.exists()) {
+                    dest.mkdirs();
+                }
+            }
+            return Uri.fromFile(dest);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
 }
diff --git a/testapps/EmbmsTestStreamingApp/src/com/android/phone/testapps/embmsfrontend/EmbmsTestStreamingApp.java b/testapps/EmbmsTestStreamingApp/src/com/android/phone/testapps/embmsfrontend/EmbmsTestStreamingApp.java
index 0546c9d..75febda 100644
--- a/testapps/EmbmsTestStreamingApp/src/com/android/phone/testapps/embmsfrontend/EmbmsTestStreamingApp.java
+++ b/testapps/EmbmsTestStreamingApp/src/com/android/phone/testapps/embmsfrontend/EmbmsTestStreamingApp.java
@@ -154,7 +154,7 @@
         Button bindButton = (Button) findViewById(R.id.bind_button);
         bindButton.setOnClickListener((view) -> {
             mStreamingManager = MbmsStreamingSession.create(
-                    EmbmsTestStreamingApp.this, mStreamingListener, mHandler);
+                    EmbmsTestStreamingApp.this, mHandler::post, mStreamingListener);
         });
 
         Button getStreamingServicesButton = (Button)
diff --git a/testapps/EmbmsTestStreamingApp/src/com/android/phone/testapps/embmsfrontend/StreamingServiceTracker.java b/testapps/EmbmsTestStreamingApp/src/com/android/phone/testapps/embmsfrontend/StreamingServiceTracker.java
index 5244d30..d45b5fd 100644
--- a/testapps/EmbmsTestStreamingApp/src/com/android/phone/testapps/embmsfrontend/StreamingServiceTracker.java
+++ b/testapps/EmbmsTestStreamingApp/src/com/android/phone/testapps/embmsfrontend/StreamingServiceTracker.java
@@ -60,13 +60,13 @@
      * Start streaming using the provided streaming session
      */
     public boolean startStreaming(MbmsStreamingSession streamingManager) {
-        mStreamingService =
-                streamingManager.startStreaming(mStreamingServiceInfo, new Callback(), null);
+        mStreamingService = streamingManager.startStreaming(mStreamingServiceInfo,
+                mActivity.getMainThreadHandler()::post, new Callback());
         return true;
     }
 
     public void stopStreaming() {
-        mStreamingService.stopStreaming();
+        mStreamingService.close();
     }
 
     public String getServiceId() {