Make requests for restricted networks not require unrestricted access.

Currently, calling startUsingNetworkFeature for a restricted APN
type (e.g., IMS or FOTA) will create a request that requires
NET_CAPABILITY_NOT_RESTRICTED. Because these APNs are restricted,
when we bring them up we conclude that it does not match the
unrestricted requirement, and we tear them down.

1. Clear the NET_CAPABILITY_NOT_RESTRICTED capability when
   creating requests in startUsingNetworkFeature.
2. Refactor the code to a common function so this cannot happen
   again.

Bug: 15191336
Change-Id: Id1ec79c58ff79b1a83457ffaecc57d50b61ed4e4
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index a48a388..c4cbdd5 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -870,6 +870,26 @@
         return 1;
     }
 
+    /**
+     * Removes the NET_CAPABILITY_NOT_RESTRICTED capability from the given
+     * NetworkCapabilities object if it lists any capabilities that are
+     * typically provided by retricted networks.
+     * @hide
+     */
+    public static void maybeMarkCapabilitiesRestricted(NetworkCapabilities nc) {
+        for (Integer capability: nc.getNetworkCapabilities()) {
+            switch (capability.intValue()) {
+                case NetworkCapabilities.NET_CAPABILITY_CBS:
+                case NetworkCapabilities.NET_CAPABILITY_DUN:
+                case NetworkCapabilities.NET_CAPABILITY_FOTA:
+                case NetworkCapabilities.NET_CAPABILITY_IA:
+                case NetworkCapabilities.NET_CAPABILITY_IMS:
+                    nc.removeNetworkCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
+                    break;
+            }
+        }
+    }
+
     private NetworkCapabilities networkCapabilitiesForFeature(int networkType, String feature) {
         if (networkType == TYPE_MOBILE) {
             int cap = -1;
@@ -893,12 +913,14 @@
             NetworkCapabilities netCap = new NetworkCapabilities();
             netCap.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
             netCap.addNetworkCapability(cap);
+            maybeMarkCapabilitiesRestricted(netCap);
             return netCap;
         } else if (networkType == TYPE_WIFI) {
             if ("p2p".equals(feature)) {
                 NetworkCapabilities netCap = new NetworkCapabilities();
                 netCap.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
                 netCap.addNetworkCapability(NetworkCapabilities.NET_CAPABILITY_WIFI_P2P);
+                maybeMarkCapabilitiesRestricted(netCap);
                 return netCap;
             }
         }