Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2008 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 | |
| 17 | package com.android.server; |
| 18 | |
| 19 | import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE; |
| 20 | import static android.content.pm.PackageManager.FEATURE_BLUETOOTH; |
| 21 | import static android.content.pm.PackageManager.FEATURE_WATCH; |
| 22 | import static android.content.pm.PackageManager.FEATURE_WIFI; |
| 23 | import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT; |
| 24 | import static android.content.pm.PackageManager.PERMISSION_GRANTED; |
| 25 | import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK; |
| 26 | import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK; |
| 27 | import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT; |
| 28 | import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS; |
| 29 | import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS; |
| 30 | import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS; |
| 31 | import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS; |
| 32 | import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE; |
| 33 | import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK; |
| 34 | import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN; |
| 35 | import static android.net.ConnectivityManager.BLOCKED_REASON_NONE; |
| 36 | import static android.net.ConnectivityManager.CONNECTIVITY_ACTION; |
| 37 | import static android.net.ConnectivityManager.TYPE_BLUETOOTH; |
| 38 | import static android.net.ConnectivityManager.TYPE_ETHERNET; |
| 39 | import static android.net.ConnectivityManager.TYPE_MOBILE; |
| 40 | import static android.net.ConnectivityManager.TYPE_MOBILE_CBS; |
| 41 | import static android.net.ConnectivityManager.TYPE_MOBILE_DUN; |
| 42 | import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY; |
| 43 | import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA; |
| 44 | import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI; |
| 45 | import static android.net.ConnectivityManager.TYPE_MOBILE_IA; |
| 46 | import static android.net.ConnectivityManager.TYPE_MOBILE_IMS; |
| 47 | import static android.net.ConnectivityManager.TYPE_MOBILE_MMS; |
| 48 | import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL; |
| 49 | import static android.net.ConnectivityManager.TYPE_NONE; |
| 50 | import static android.net.ConnectivityManager.TYPE_PROXY; |
| 51 | import static android.net.ConnectivityManager.TYPE_VPN; |
| 52 | import static android.net.ConnectivityManager.TYPE_WIFI; |
| 53 | import static android.net.ConnectivityManager.TYPE_WIFI_P2P; |
| 54 | import static android.net.ConnectivityManager.getNetworkTypeName; |
| 55 | import static android.net.ConnectivityManager.isNetworkTypeValid; |
| 56 | import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC; |
| 57 | import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS; |
| 58 | import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL; |
| 59 | import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID; |
| 60 | import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL; |
| 61 | import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE; |
| 62 | import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND; |
| 63 | import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET; |
| 64 | import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED; |
| 65 | import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED; |
| 66 | import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED; |
| 67 | import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING; |
| 68 | import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED; |
| 69 | import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED; |
| 70 | import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN; |
| 71 | import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID; |
| 72 | import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE; |
| 73 | import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY; |
| 74 | import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED; |
| 75 | import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION; |
| 76 | import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS; |
| 77 | import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS; |
| 78 | import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR; |
| 79 | import static android.net.NetworkCapabilities.TRANSPORT_TEST; |
| 80 | import static android.net.NetworkCapabilities.TRANSPORT_VPN; |
Treehugger Robot | 27b6888 | 2021-06-07 19:42:39 +0000 | [diff] [blame] | 81 | import static android.net.NetworkCapabilities.TRANSPORT_WIFI; |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 82 | import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST; |
James Mattis | b7ca034 | 2021-06-16 01:30:05 +0000 | [diff] [blame] | 83 | import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST; |
| 84 | import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY; |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 85 | import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired; |
| 86 | import static android.os.Process.INVALID_UID; |
| 87 | import static android.os.Process.VPN_UID; |
| 88 | import static android.system.OsConstants.IPPROTO_TCP; |
| 89 | import static android.system.OsConstants.IPPROTO_UDP; |
| 90 | |
| 91 | import static java.util.Map.Entry; |
| 92 | |
| 93 | import android.Manifest; |
| 94 | import android.annotation.NonNull; |
| 95 | import android.annotation.Nullable; |
| 96 | import android.app.AppOpsManager; |
| 97 | import android.app.BroadcastOptions; |
| 98 | import android.app.PendingIntent; |
| 99 | import android.app.usage.NetworkStatsManager; |
| 100 | import android.content.BroadcastReceiver; |
| 101 | import android.content.ComponentName; |
| 102 | import android.content.ContentResolver; |
| 103 | import android.content.Context; |
| 104 | import android.content.Intent; |
| 105 | import android.content.IntentFilter; |
| 106 | import android.content.pm.PackageManager; |
| 107 | import android.database.ContentObserver; |
| 108 | import android.net.CaptivePortal; |
| 109 | import android.net.CaptivePortalData; |
| 110 | import android.net.ConnectionInfo; |
| 111 | import android.net.ConnectivityDiagnosticsManager.ConnectivityReport; |
| 112 | import android.net.ConnectivityDiagnosticsManager.DataStallReport; |
| 113 | import android.net.ConnectivityManager; |
| 114 | import android.net.ConnectivityManager.BlockedReason; |
| 115 | import android.net.ConnectivityManager.NetworkCallback; |
Aaron Huang | cff2294 | 2021-05-27 16:31:26 +0800 | [diff] [blame] | 116 | import android.net.ConnectivityManager.RestrictBackgroundStatus; |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 117 | import android.net.ConnectivityResources; |
| 118 | import android.net.ConnectivitySettingsManager; |
| 119 | import android.net.DataStallReportParcelable; |
| 120 | import android.net.DnsResolverServiceManager; |
| 121 | import android.net.ICaptivePortal; |
| 122 | import android.net.IConnectivityDiagnosticsCallback; |
| 123 | import android.net.IConnectivityManager; |
| 124 | import android.net.IDnsResolver; |
| 125 | import android.net.INetd; |
| 126 | import android.net.INetworkActivityListener; |
| 127 | import android.net.INetworkAgent; |
| 128 | import android.net.INetworkMonitor; |
| 129 | import android.net.INetworkMonitorCallbacks; |
| 130 | import android.net.INetworkOfferCallback; |
| 131 | import android.net.IOnCompleteListener; |
| 132 | import android.net.IQosCallback; |
| 133 | import android.net.ISocketKeepaliveCallback; |
| 134 | import android.net.InetAddresses; |
| 135 | import android.net.IpMemoryStore; |
| 136 | import android.net.IpPrefix; |
| 137 | import android.net.LinkProperties; |
| 138 | import android.net.MatchAllNetworkSpecifier; |
| 139 | import android.net.NativeNetworkConfig; |
| 140 | import android.net.NativeNetworkType; |
| 141 | import android.net.NattSocketKeepalive; |
| 142 | import android.net.Network; |
| 143 | import android.net.NetworkAgent; |
| 144 | import android.net.NetworkAgentConfig; |
| 145 | import android.net.NetworkCapabilities; |
| 146 | import android.net.NetworkInfo; |
| 147 | import android.net.NetworkInfo.DetailedState; |
| 148 | import android.net.NetworkMonitorManager; |
| 149 | import android.net.NetworkPolicyManager; |
| 150 | import android.net.NetworkPolicyManager.NetworkPolicyCallback; |
| 151 | import android.net.NetworkProvider; |
| 152 | import android.net.NetworkRequest; |
| 153 | import android.net.NetworkScore; |
| 154 | import android.net.NetworkSpecifier; |
| 155 | import android.net.NetworkStack; |
| 156 | import android.net.NetworkState; |
| 157 | import android.net.NetworkStateSnapshot; |
| 158 | import android.net.NetworkTestResultParcelable; |
| 159 | import android.net.NetworkUtils; |
| 160 | import android.net.NetworkWatchlistManager; |
| 161 | import android.net.OemNetworkPreferences; |
| 162 | import android.net.PrivateDnsConfigParcel; |
| 163 | import android.net.ProxyInfo; |
| 164 | import android.net.QosCallbackException; |
| 165 | import android.net.QosFilter; |
| 166 | import android.net.QosSocketFilter; |
| 167 | import android.net.QosSocketInfo; |
| 168 | import android.net.RouteInfo; |
| 169 | import android.net.RouteInfoParcel; |
| 170 | import android.net.SocketKeepalive; |
| 171 | import android.net.TetheringManager; |
| 172 | import android.net.TransportInfo; |
| 173 | import android.net.UidRange; |
| 174 | import android.net.UidRangeParcel; |
| 175 | import android.net.UnderlyingNetworkInfo; |
| 176 | import android.net.Uri; |
| 177 | import android.net.VpnManager; |
| 178 | import android.net.VpnTransportInfo; |
| 179 | import android.net.metrics.IpConnectivityLog; |
| 180 | import android.net.metrics.NetworkEvent; |
| 181 | import android.net.netlink.InetDiagMessage; |
| 182 | import android.net.networkstack.ModuleNetworkStackClient; |
| 183 | import android.net.networkstack.NetworkStackClientBase; |
| 184 | import android.net.resolv.aidl.DnsHealthEventParcel; |
| 185 | import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener; |
| 186 | import android.net.resolv.aidl.Nat64PrefixEventParcel; |
| 187 | import android.net.resolv.aidl.PrivateDnsValidationEventParcel; |
| 188 | import android.net.shared.PrivateDnsConfig; |
| 189 | import android.net.util.MultinetworkPolicyTracker; |
| 190 | import android.os.BatteryStatsManager; |
| 191 | import android.os.Binder; |
| 192 | import android.os.Build; |
| 193 | import android.os.Bundle; |
| 194 | import android.os.Handler; |
| 195 | import android.os.HandlerThread; |
| 196 | import android.os.IBinder; |
| 197 | import android.os.Looper; |
| 198 | import android.os.Message; |
| 199 | import android.os.Messenger; |
| 200 | import android.os.ParcelFileDescriptor; |
| 201 | import android.os.Parcelable; |
| 202 | import android.os.PersistableBundle; |
| 203 | import android.os.PowerManager; |
| 204 | import android.os.Process; |
| 205 | import android.os.RemoteCallbackList; |
| 206 | import android.os.RemoteException; |
| 207 | import android.os.ServiceSpecificException; |
| 208 | import android.os.SystemClock; |
| 209 | import android.os.SystemProperties; |
| 210 | import android.os.UserHandle; |
| 211 | import android.os.UserManager; |
| 212 | import android.provider.Settings; |
| 213 | import android.sysprop.NetworkProperties; |
| 214 | import android.telephony.TelephonyManager; |
| 215 | import android.text.TextUtils; |
| 216 | import android.util.ArrayMap; |
| 217 | import android.util.ArraySet; |
| 218 | import android.util.LocalLog; |
| 219 | import android.util.Log; |
| 220 | import android.util.Pair; |
| 221 | import android.util.SparseArray; |
| 222 | import android.util.SparseIntArray; |
| 223 | |
| 224 | import com.android.connectivity.resources.R; |
| 225 | import com.android.internal.annotations.GuardedBy; |
| 226 | import com.android.internal.annotations.VisibleForTesting; |
| 227 | import com.android.internal.util.IndentingPrintWriter; |
| 228 | import com.android.internal.util.MessageUtils; |
| 229 | import com.android.modules.utils.BasicShellCommandHandler; |
| 230 | import com.android.net.module.util.BaseNetdUnsolicitedEventListener; |
| 231 | import com.android.net.module.util.CollectionUtils; |
| 232 | import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult; |
| 233 | import com.android.net.module.util.LinkPropertiesUtils.CompareResult; |
| 234 | import com.android.net.module.util.LocationPermissionChecker; |
| 235 | import com.android.net.module.util.NetworkCapabilitiesUtils; |
| 236 | import com.android.net.module.util.PermissionUtils; |
| 237 | import com.android.server.connectivity.AutodestructReference; |
| 238 | import com.android.server.connectivity.DnsManager; |
| 239 | import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate; |
| 240 | import com.android.server.connectivity.FullScore; |
| 241 | import com.android.server.connectivity.KeepaliveTracker; |
| 242 | import com.android.server.connectivity.LingerMonitor; |
| 243 | import com.android.server.connectivity.MockableSystemProperties; |
| 244 | import com.android.server.connectivity.NetworkAgentInfo; |
| 245 | import com.android.server.connectivity.NetworkDiagnostics; |
| 246 | import com.android.server.connectivity.NetworkNotificationManager; |
| 247 | import com.android.server.connectivity.NetworkNotificationManager.NotificationType; |
| 248 | import com.android.server.connectivity.NetworkOffer; |
| 249 | import com.android.server.connectivity.NetworkRanker; |
| 250 | import com.android.server.connectivity.PermissionMonitor; |
| 251 | import com.android.server.connectivity.ProfileNetworkPreferences; |
| 252 | import com.android.server.connectivity.ProxyTracker; |
| 253 | import com.android.server.connectivity.QosCallbackTracker; |
| 254 | |
| 255 | import libcore.io.IoUtils; |
| 256 | |
| 257 | import java.io.FileDescriptor; |
| 258 | import java.io.PrintWriter; |
| 259 | import java.net.Inet4Address; |
| 260 | import java.net.InetAddress; |
| 261 | import java.net.InetSocketAddress; |
| 262 | import java.net.UnknownHostException; |
| 263 | import java.util.ArrayList; |
| 264 | import java.util.Arrays; |
| 265 | import java.util.Collection; |
| 266 | import java.util.Collections; |
| 267 | import java.util.Comparator; |
| 268 | import java.util.ConcurrentModificationException; |
| 269 | import java.util.HashMap; |
| 270 | import java.util.HashSet; |
| 271 | import java.util.List; |
| 272 | import java.util.Map; |
| 273 | import java.util.Objects; |
| 274 | import java.util.Set; |
| 275 | import java.util.SortedSet; |
| 276 | import java.util.StringJoiner; |
| 277 | import java.util.TreeSet; |
| 278 | import java.util.concurrent.atomic.AtomicInteger; |
| 279 | |
| 280 | /** |
| 281 | * @hide |
| 282 | */ |
| 283 | public class ConnectivityService extends IConnectivityManager.Stub |
| 284 | implements PendingIntent.OnFinished { |
| 285 | private static final String TAG = ConnectivityService.class.getSimpleName(); |
| 286 | |
| 287 | private static final String DIAG_ARG = "--diag"; |
| 288 | public static final String SHORT_ARG = "--short"; |
| 289 | private static final String NETWORK_ARG = "networks"; |
| 290 | private static final String REQUEST_ARG = "requests"; |
| 291 | |
| 292 | private static final boolean DBG = true; |
| 293 | private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG); |
| 294 | private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE); |
| 295 | |
| 296 | private static final boolean LOGD_BLOCKED_NETWORKINFO = true; |
| 297 | |
| 298 | /** |
| 299 | * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed |
| 300 | * by OEMs for configuration purposes, as this value is overridden by |
| 301 | * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL. |
| 302 | * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose |
| 303 | * (preferably via runtime resource overlays). |
| 304 | */ |
| 305 | private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL = |
| 306 | "http://connectivitycheck.gstatic.com/generate_204"; |
| 307 | |
| 308 | // TODO: create better separation between radio types and network types |
| 309 | |
| 310 | // how long to wait before switching back to a radio's default network |
| 311 | private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000; |
| 312 | // system property that can override the above value |
| 313 | private static final String NETWORK_RESTORE_DELAY_PROP_NAME = |
| 314 | "android.telephony.apn-restore"; |
| 315 | |
| 316 | // How long to wait before putting up a "This network doesn't have an Internet connection, |
| 317 | // connect anyway?" dialog after the user selects a network that doesn't validate. |
| 318 | private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000; |
| 319 | |
| 320 | // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing. |
| 321 | private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger"; |
| 322 | private static final int DEFAULT_LINGER_DELAY_MS = 30_000; |
| 323 | private static final int DEFAULT_NASCENT_DELAY_MS = 5_000; |
| 324 | |
| 325 | // The maximum number of network request allowed per uid before an exception is thrown. |
| 326 | private static final int MAX_NETWORK_REQUESTS_PER_UID = 100; |
| 327 | |
| 328 | // The maximum number of network request allowed for system UIDs before an exception is thrown. |
| 329 | @VisibleForTesting |
| 330 | static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250; |
| 331 | |
| 332 | @VisibleForTesting |
| 333 | protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it. |
| 334 | @VisibleForTesting |
| 335 | protected int mNascentDelayMs; |
| 336 | |
| 337 | // How long to delay to removal of a pending intent based request. |
| 338 | // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS |
| 339 | private final int mReleasePendingIntentDelayMs; |
| 340 | |
| 341 | private MockableSystemProperties mSystemProperties; |
| 342 | |
| 343 | @VisibleForTesting |
| 344 | protected final PermissionMonitor mPermissionMonitor; |
| 345 | |
| 346 | private final PerUidCounter mNetworkRequestCounter; |
| 347 | @VisibleForTesting |
| 348 | final PerUidCounter mSystemNetworkRequestCounter; |
| 349 | |
| 350 | private volatile boolean mLockdownEnabled; |
| 351 | |
| 352 | /** |
| 353 | * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in |
| 354 | * internal handler thread, they don't need a lock. |
| 355 | */ |
| 356 | private SparseIntArray mUidBlockedReasons = new SparseIntArray(); |
| 357 | |
| 358 | private final Context mContext; |
| 359 | private final ConnectivityResources mResources; |
| 360 | // The Context is created for UserHandle.ALL. |
| 361 | private final Context mUserAllContext; |
| 362 | private final Dependencies mDeps; |
| 363 | // 0 is full bad, 100 is full good |
| 364 | private int mDefaultInetConditionPublished = 0; |
| 365 | |
| 366 | @VisibleForTesting |
| 367 | protected IDnsResolver mDnsResolver; |
| 368 | @VisibleForTesting |
| 369 | protected INetd mNetd; |
| 370 | private NetworkStatsManager mStatsManager; |
| 371 | private NetworkPolicyManager mPolicyManager; |
| 372 | private final NetdCallback mNetdCallback; |
| 373 | |
| 374 | /** |
| 375 | * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple |
| 376 | * instances. |
| 377 | */ |
| 378 | @GuardedBy("mTNSLock") |
| 379 | private TestNetworkService mTNS; |
| 380 | |
| 381 | private final Object mTNSLock = new Object(); |
| 382 | |
| 383 | private String mCurrentTcpBufferSizes; |
| 384 | |
| 385 | private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames( |
| 386 | new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class }); |
| 387 | |
| 388 | private enum ReapUnvalidatedNetworks { |
| 389 | // Tear down networks that have no chance (e.g. even if validated) of becoming |
| 390 | // the highest scoring network satisfying a NetworkRequest. This should be passed when |
| 391 | // all networks have been rematched against all NetworkRequests. |
| 392 | REAP, |
| 393 | // Don't reap networks. This should be passed when some networks have not yet been |
| 394 | // rematched against all NetworkRequests. |
| 395 | DONT_REAP |
| 396 | } |
| 397 | |
| 398 | private enum UnneededFor { |
| 399 | LINGER, // Determine whether this network is unneeded and should be lingered. |
| 400 | TEARDOWN, // Determine whether this network is unneeded and should be torn down. |
| 401 | } |
| 402 | |
| 403 | /** |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 404 | * The priority value is used when issue uid ranges rules to netd. Netd will use the priority |
| 405 | * value and uid ranges to generate corresponding ip rules specific to the given preference. |
| 406 | * Thus, any device originated data traffic of the applied uids can be routed to the altered |
| 407 | * default network which has highest priority. |
| 408 | * |
| 409 | * Note: The priority value should be in 0~1000. Larger value means lower priority, see |
| 410 | * {@link NativeUidRangeConfig}. |
| 411 | */ |
| 412 | // This is default priority value for those NetworkRequests which doesn't have preference to |
| 413 | // alter default network and use the global one. |
| 414 | @VisibleForTesting |
| 415 | static final int DEFAULT_NETWORK_PRIORITY_NONE = 0; |
| 416 | // Used by automotive devices to set the network preferences used to direct traffic at an |
| 417 | // application level. See {@link #setOemNetworkPreference}. |
| 418 | @VisibleForTesting |
| 419 | static final int DEFAULT_NETWORK_PRIORITY_OEM = 10; |
| 420 | // Request that a user profile is put by default on a network matching a given preference. |
| 421 | // See {@link #setProfileNetworkPreference}. |
| 422 | @VisibleForTesting |
| 423 | static final int DEFAULT_NETWORK_PRIORITY_PROFILE = 20; |
| 424 | // Set by MOBILE_DATA_PREFERRED_UIDS setting. Use mobile data in preference even when |
| 425 | // higher-priority networks are connected. |
| 426 | @VisibleForTesting |
| 427 | static final int DEFAULT_NETWORK_PRIORITY_MOBILE_DATA_PREFERRED = 30; |
| 428 | |
| 429 | /** |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 430 | * used internally to clear a wakelock when transitioning |
| 431 | * from one net to another. Clear happens when we get a new |
| 432 | * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens |
| 433 | * after a timeout if no network is found (typically 1 min). |
| 434 | */ |
| 435 | private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8; |
| 436 | |
| 437 | /** |
| 438 | * used internally to reload global proxy settings |
| 439 | */ |
| 440 | private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9; |
| 441 | |
| 442 | /** |
| 443 | * PAC manager has received new port. |
| 444 | */ |
| 445 | private static final int EVENT_PROXY_HAS_CHANGED = 16; |
| 446 | |
| 447 | /** |
| 448 | * used internally when registering NetworkProviders |
| 449 | * obj = NetworkProviderInfo |
| 450 | */ |
| 451 | private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17; |
| 452 | |
| 453 | /** |
| 454 | * used internally when registering NetworkAgents |
| 455 | * obj = Messenger |
| 456 | */ |
| 457 | private static final int EVENT_REGISTER_NETWORK_AGENT = 18; |
| 458 | |
| 459 | /** |
| 460 | * used to add a network request |
| 461 | * includes a NetworkRequestInfo |
| 462 | */ |
| 463 | private static final int EVENT_REGISTER_NETWORK_REQUEST = 19; |
| 464 | |
| 465 | /** |
| 466 | * indicates a timeout period is over - check if we had a network yet or not |
| 467 | * and if not, call the timeout callback (but leave the request live until they |
| 468 | * cancel it. |
| 469 | * includes a NetworkRequestInfo |
| 470 | */ |
| 471 | private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20; |
| 472 | |
| 473 | /** |
| 474 | * used to add a network listener - no request |
| 475 | * includes a NetworkRequestInfo |
| 476 | */ |
| 477 | private static final int EVENT_REGISTER_NETWORK_LISTENER = 21; |
| 478 | |
| 479 | /** |
| 480 | * used to remove a network request, either a listener or a real request |
| 481 | * arg1 = UID of caller |
| 482 | * obj = NetworkRequest |
| 483 | */ |
| 484 | private static final int EVENT_RELEASE_NETWORK_REQUEST = 22; |
| 485 | |
| 486 | /** |
| 487 | * used internally when registering NetworkProviders |
| 488 | * obj = Messenger |
| 489 | */ |
| 490 | private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23; |
| 491 | |
| 492 | /** |
| 493 | * used internally to expire a wakelock when transitioning |
| 494 | * from one net to another. Expire happens when we fail to find |
| 495 | * a new network (typically after 1 minute) - |
| 496 | * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found |
| 497 | * a replacement network. |
| 498 | */ |
| 499 | private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24; |
| 500 | |
| 501 | /** |
| 502 | * used to add a network request with a pending intent |
| 503 | * obj = NetworkRequestInfo |
| 504 | */ |
| 505 | private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26; |
| 506 | |
| 507 | /** |
| 508 | * used to remove a pending intent and its associated network request. |
| 509 | * arg1 = UID of caller |
| 510 | * obj = PendingIntent |
| 511 | */ |
| 512 | private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27; |
| 513 | |
| 514 | /** |
| 515 | * used to specify whether a network should be used even if unvalidated. |
| 516 | * arg1 = whether to accept the network if it's unvalidated (1 or 0) |
| 517 | * arg2 = whether to remember this choice in the future (1 or 0) |
| 518 | * obj = network |
| 519 | */ |
| 520 | private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28; |
| 521 | |
| 522 | /** |
| 523 | * used to ask the user to confirm a connection to an unvalidated network. |
| 524 | * obj = network |
| 525 | */ |
| 526 | private static final int EVENT_PROMPT_UNVALIDATED = 29; |
| 527 | |
| 528 | /** |
| 529 | * used internally to (re)configure always-on networks. |
| 530 | */ |
| 531 | private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30; |
| 532 | |
| 533 | /** |
| 534 | * used to add a network listener with a pending intent |
| 535 | * obj = NetworkRequestInfo |
| 536 | */ |
| 537 | private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31; |
| 538 | |
| 539 | /** |
| 540 | * used to specify whether a network should not be penalized when it becomes unvalidated. |
| 541 | */ |
| 542 | private static final int EVENT_SET_AVOID_UNVALIDATED = 35; |
| 543 | |
| 544 | /** |
| 545 | * used to trigger revalidation of a network. |
| 546 | */ |
| 547 | private static final int EVENT_REVALIDATE_NETWORK = 36; |
| 548 | |
| 549 | // Handle changes in Private DNS settings. |
| 550 | private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37; |
| 551 | |
| 552 | // Handle private DNS validation status updates. |
| 553 | private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38; |
| 554 | |
| 555 | /** |
| 556 | * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has |
| 557 | * been tested. |
| 558 | * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor. |
| 559 | * data = PersistableBundle of extras passed from NetworkMonitor. If {@link |
| 560 | * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null. |
| 561 | */ |
| 562 | private static final int EVENT_NETWORK_TESTED = 41; |
| 563 | |
| 564 | /** |
| 565 | * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS |
| 566 | * config was resolved. |
| 567 | * obj = PrivateDnsConfig |
| 568 | * arg2 = netid |
| 569 | */ |
| 570 | private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42; |
| 571 | |
| 572 | /** |
| 573 | * Request ConnectivityService display provisioning notification. |
| 574 | * arg1 = Whether to make the notification visible. |
| 575 | * arg2 = NetID. |
| 576 | * obj = Intent to be launched when notification selected by user, null if !arg1. |
| 577 | */ |
| 578 | private static final int EVENT_PROVISIONING_NOTIFICATION = 43; |
| 579 | |
| 580 | /** |
| 581 | * Used to specify whether a network should be used even if connectivity is partial. |
| 582 | * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for |
| 583 | * false) |
| 584 | * arg2 = whether to remember this choice in the future (1 for true or 0 for false) |
| 585 | * obj = network |
| 586 | */ |
| 587 | private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44; |
| 588 | |
| 589 | /** |
| 590 | * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed. |
| 591 | * Both of the arguments are bitmasks, and the value of bits come from |
| 592 | * INetworkMonitor.NETWORK_VALIDATION_PROBE_*. |
| 593 | * arg1 = A bitmask to describe which probes are completed. |
| 594 | * arg2 = A bitmask to describe which probes are successful. |
| 595 | */ |
| 596 | public static final int EVENT_PROBE_STATUS_CHANGED = 45; |
| 597 | |
| 598 | /** |
| 599 | * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed. |
| 600 | * arg1 = unused |
| 601 | * arg2 = netId |
| 602 | * obj = captive portal data |
| 603 | */ |
| 604 | private static final int EVENT_CAPPORT_DATA_CHANGED = 46; |
| 605 | |
| 606 | /** |
| 607 | * Used by setRequireVpnForUids. |
| 608 | * arg1 = whether the specified UID ranges are required to use a VPN. |
| 609 | * obj = Array of UidRange objects. |
| 610 | */ |
| 611 | private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47; |
| 612 | |
| 613 | /** |
| 614 | * Used internally when setting the default networks for OemNetworkPreferences. |
| 615 | * obj = Pair<OemNetworkPreferences, listener> |
| 616 | */ |
| 617 | private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48; |
| 618 | |
| 619 | /** |
| 620 | * Used to indicate the system default network becomes active. |
| 621 | */ |
| 622 | private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49; |
| 623 | |
| 624 | /** |
| 625 | * Used internally when setting a network preference for a user profile. |
| 626 | * obj = Pair<ProfileNetworkPreference, Listener> |
| 627 | */ |
| 628 | private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50; |
| 629 | |
| 630 | /** |
| 631 | * Event to specify that reasons for why an uid is blocked changed. |
| 632 | * arg1 = uid |
| 633 | * arg2 = blockedReasons |
| 634 | */ |
| 635 | private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51; |
| 636 | |
| 637 | /** |
| 638 | * Event to register a new network offer |
| 639 | * obj = NetworkOffer |
| 640 | */ |
| 641 | private static final int EVENT_REGISTER_NETWORK_OFFER = 52; |
| 642 | |
| 643 | /** |
| 644 | * Event to unregister an existing network offer |
| 645 | * obj = INetworkOfferCallback |
| 646 | */ |
| 647 | private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53; |
| 648 | |
| 649 | /** |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 650 | * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed. |
| 651 | */ |
| 652 | private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54; |
| 653 | |
| 654 | /** |
Chiachang Wang | fad30e3 | 2021-06-23 02:08:44 +0000 | [diff] [blame] | 655 | * Event to set temporary allow bad wifi within a limited time to override |
| 656 | * {@code config_networkAvoidBadWifi}. |
| 657 | */ |
| 658 | private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55; |
| 659 | |
| 660 | /** |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 661 | * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification |
| 662 | * should be shown. |
| 663 | */ |
| 664 | private static final int PROVISIONING_NOTIFICATION_SHOW = 1; |
| 665 | |
| 666 | /** |
| 667 | * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification |
| 668 | * should be hidden. |
| 669 | */ |
| 670 | private static final int PROVISIONING_NOTIFICATION_HIDE = 0; |
| 671 | |
Chiachang Wang | fad30e3 | 2021-06-23 02:08:44 +0000 | [diff] [blame] | 672 | /** |
| 673 | * The maximum alive time to allow bad wifi configuration for testing. |
| 674 | */ |
| 675 | private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L; |
| 676 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 677 | private static String eventName(int what) { |
| 678 | return sMagicDecoderRing.get(what, Integer.toString(what)); |
| 679 | } |
| 680 | |
| 681 | private static IDnsResolver getDnsResolver(Context context) { |
| 682 | final DnsResolverServiceManager dsm = context.getSystemService( |
| 683 | DnsResolverServiceManager.class); |
| 684 | return IDnsResolver.Stub.asInterface(dsm.getService()); |
| 685 | } |
| 686 | |
| 687 | /** Handler thread used for all of the handlers below. */ |
| 688 | @VisibleForTesting |
| 689 | protected final HandlerThread mHandlerThread; |
| 690 | /** Handler used for internal events. */ |
| 691 | final private InternalHandler mHandler; |
| 692 | /** Handler used for incoming {@link NetworkStateTracker} events. */ |
| 693 | final private NetworkStateTrackerHandler mTrackerHandler; |
| 694 | /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */ |
| 695 | @VisibleForTesting |
| 696 | final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler; |
| 697 | |
| 698 | private final DnsManager mDnsManager; |
| 699 | private final NetworkRanker mNetworkRanker; |
| 700 | |
| 701 | private boolean mSystemReady; |
| 702 | private Intent mInitialBroadcast; |
| 703 | |
| 704 | private PowerManager.WakeLock mNetTransitionWakeLock; |
| 705 | private final PowerManager.WakeLock mPendingIntentWakeLock; |
| 706 | |
| 707 | // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell |
| 708 | // the world when it changes. |
| 709 | @VisibleForTesting |
| 710 | protected final ProxyTracker mProxyTracker; |
| 711 | |
| 712 | final private SettingsObserver mSettingsObserver; |
| 713 | |
| 714 | private UserManager mUserManager; |
| 715 | |
| 716 | // the set of network types that can only be enabled by system/sig apps |
| 717 | private List<Integer> mProtectedNetworks; |
| 718 | |
| 719 | private Set<String> mWolSupportedInterfaces; |
| 720 | |
| 721 | private final TelephonyManager mTelephonyManager; |
| 722 | private final AppOpsManager mAppOpsManager; |
| 723 | |
| 724 | private final LocationPermissionChecker mLocationPermissionChecker; |
| 725 | |
| 726 | private KeepaliveTracker mKeepaliveTracker; |
| 727 | private QosCallbackTracker mQosCallbackTracker; |
| 728 | private NetworkNotificationManager mNotifier; |
| 729 | private LingerMonitor mLingerMonitor; |
| 730 | |
| 731 | // sequence number of NetworkRequests |
| 732 | private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID; |
| 733 | |
| 734 | // Sequence number for NetworkProvider IDs. |
| 735 | private final AtomicInteger mNextNetworkProviderId = new AtomicInteger( |
| 736 | NetworkProvider.FIRST_PROVIDER_ID); |
| 737 | |
| 738 | // NetworkRequest activity String log entries. |
| 739 | private static final int MAX_NETWORK_REQUEST_LOGS = 20; |
| 740 | private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS); |
| 741 | |
| 742 | // NetworkInfo blocked and unblocked String log entries |
| 743 | private static final int MAX_NETWORK_INFO_LOGS = 40; |
| 744 | private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS); |
| 745 | |
| 746 | private static final int MAX_WAKELOCK_LOGS = 20; |
| 747 | private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS); |
| 748 | private int mTotalWakelockAcquisitions = 0; |
| 749 | private int mTotalWakelockReleases = 0; |
| 750 | private long mTotalWakelockDurationMs = 0; |
| 751 | private long mMaxWakelockDurationMs = 0; |
| 752 | private long mLastWakeLockAcquireTimestamp = 0; |
| 753 | |
| 754 | private final IpConnectivityLog mMetricsLog; |
| 755 | |
| 756 | @GuardedBy("mBandwidthRequests") |
| 757 | private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10); |
| 758 | |
| 759 | @VisibleForTesting |
| 760 | final MultinetworkPolicyTracker mMultinetworkPolicyTracker; |
| 761 | |
| 762 | @VisibleForTesting |
| 763 | final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks = |
| 764 | new HashMap<>(); |
| 765 | |
| 766 | /** |
| 767 | * Implements support for the legacy "one network per network type" model. |
| 768 | * |
| 769 | * We used to have a static array of NetworkStateTrackers, one for each |
| 770 | * network type, but that doesn't work any more now that we can have, |
| 771 | * for example, more that one wifi network. This class stores all the |
| 772 | * NetworkAgentInfo objects that support a given type, but the legacy |
| 773 | * API will only see the first one. |
| 774 | * |
| 775 | * It serves two main purposes: |
| 776 | * |
| 777 | * 1. Provide information about "the network for a given type" (since this |
| 778 | * API only supports one). |
| 779 | * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if |
| 780 | * the first network for a given type changes, or if the default network |
| 781 | * changes. |
| 782 | */ |
| 783 | @VisibleForTesting |
| 784 | static class LegacyTypeTracker { |
| 785 | |
| 786 | private static final boolean DBG = true; |
| 787 | private static final boolean VDBG = false; |
| 788 | |
| 789 | /** |
| 790 | * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS). |
| 791 | * Each list holds references to all NetworkAgentInfos that are used to |
| 792 | * satisfy requests for that network type. |
| 793 | * |
| 794 | * This array is built out at startup such that an unsupported network |
| 795 | * doesn't get an ArrayList instance, making this a tristate: |
| 796 | * unsupported, supported but not active and active. |
| 797 | * |
| 798 | * The actual lists are populated when we scan the network types that |
| 799 | * are supported on this device. |
| 800 | * |
| 801 | * Threading model: |
| 802 | * - addSupportedType() is only called in the constructor |
| 803 | * - add(), update(), remove() are only called from the ConnectivityService handler thread. |
| 804 | * They are therefore not thread-safe with respect to each other. |
| 805 | * - getNetworkForType() can be called at any time on binder threads. It is synchronized |
| 806 | * on mTypeLists to be thread-safe with respect to a concurrent remove call. |
| 807 | * - getRestoreTimerForType(type) is also synchronized on mTypeLists. |
| 808 | * - dump is thread-safe with respect to concurrent add and remove calls. |
| 809 | */ |
| 810 | private final ArrayList<NetworkAgentInfo> mTypeLists[]; |
| 811 | @NonNull |
| 812 | private final ConnectivityService mService; |
| 813 | |
| 814 | // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without |
| 815 | // an entry have no timer (equivalent to -1). Lazily loaded. |
| 816 | @NonNull |
| 817 | private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>(); |
| 818 | |
| 819 | LegacyTypeTracker(@NonNull ConnectivityService service) { |
| 820 | mService = service; |
| 821 | mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1]; |
| 822 | } |
| 823 | |
| 824 | public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) { |
| 825 | final PackageManager pm = ctx.getPackageManager(); |
| 826 | if (pm.hasSystemFeature(FEATURE_WIFI)) { |
| 827 | addSupportedType(TYPE_WIFI); |
| 828 | } |
| 829 | if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) { |
| 830 | addSupportedType(TYPE_WIFI_P2P); |
| 831 | } |
| 832 | if (tm.isDataCapable()) { |
| 833 | // Telephony does not have granular support for these types: they are either all |
| 834 | // supported, or none is supported |
| 835 | addSupportedType(TYPE_MOBILE); |
| 836 | addSupportedType(TYPE_MOBILE_MMS); |
| 837 | addSupportedType(TYPE_MOBILE_SUPL); |
| 838 | addSupportedType(TYPE_MOBILE_DUN); |
| 839 | addSupportedType(TYPE_MOBILE_HIPRI); |
| 840 | addSupportedType(TYPE_MOBILE_FOTA); |
| 841 | addSupportedType(TYPE_MOBILE_IMS); |
| 842 | addSupportedType(TYPE_MOBILE_CBS); |
| 843 | addSupportedType(TYPE_MOBILE_IA); |
| 844 | addSupportedType(TYPE_MOBILE_EMERGENCY); |
| 845 | } |
| 846 | if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) { |
| 847 | addSupportedType(TYPE_BLUETOOTH); |
| 848 | } |
| 849 | if (pm.hasSystemFeature(FEATURE_WATCH)) { |
| 850 | // TYPE_PROXY is only used on Wear |
| 851 | addSupportedType(TYPE_PROXY); |
| 852 | } |
| 853 | // Ethernet is often not specified in the configs, although many devices can use it via |
| 854 | // USB host adapters. Add it as long as the ethernet service is here. |
| 855 | if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) { |
| 856 | addSupportedType(TYPE_ETHERNET); |
| 857 | } |
| 858 | |
| 859 | // Always add TYPE_VPN as a supported type |
| 860 | addSupportedType(TYPE_VPN); |
| 861 | } |
| 862 | |
| 863 | private void addSupportedType(int type) { |
| 864 | if (mTypeLists[type] != null) { |
| 865 | throw new IllegalStateException( |
| 866 | "legacy list for type " + type + "already initialized"); |
| 867 | } |
| 868 | mTypeLists[type] = new ArrayList<>(); |
| 869 | } |
| 870 | |
| 871 | public boolean isTypeSupported(int type) { |
| 872 | return isNetworkTypeValid(type) && mTypeLists[type] != null; |
| 873 | } |
| 874 | |
| 875 | public NetworkAgentInfo getNetworkForType(int type) { |
| 876 | synchronized (mTypeLists) { |
| 877 | if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) { |
| 878 | return mTypeLists[type].get(0); |
| 879 | } |
| 880 | } |
| 881 | return null; |
| 882 | } |
| 883 | |
| 884 | public int getRestoreTimerForType(int type) { |
| 885 | synchronized (mTypeLists) { |
| 886 | if (mRestoreTimers == null) { |
| 887 | mRestoreTimers = loadRestoreTimers(); |
| 888 | } |
| 889 | return mRestoreTimers.getOrDefault(type, -1); |
| 890 | } |
| 891 | } |
| 892 | |
| 893 | private ArrayMap<Integer, Integer> loadRestoreTimers() { |
| 894 | final String[] configs = mService.mResources.get().getStringArray( |
| 895 | R.array.config_legacy_networktype_restore_timers); |
| 896 | final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length); |
| 897 | for (final String config : configs) { |
| 898 | final String[] splits = TextUtils.split(config, ","); |
| 899 | if (splits.length != 2) { |
| 900 | logwtf("Invalid restore timer token count: " + config); |
| 901 | continue; |
| 902 | } |
| 903 | try { |
| 904 | ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1])); |
| 905 | } catch (NumberFormatException e) { |
| 906 | logwtf("Invalid restore timer number format: " + config, e); |
| 907 | } |
| 908 | } |
| 909 | return ret; |
| 910 | } |
| 911 | |
| 912 | private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type, |
| 913 | boolean isDefaultNetwork) { |
| 914 | if (DBG) { |
| 915 | log("Sending " + state |
| 916 | + " broadcast for type " + type + " " + nai.toShortString() |
| 917 | + " isDefaultNetwork=" + isDefaultNetwork); |
| 918 | } |
| 919 | } |
| 920 | |
| 921 | // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying |
| 922 | // network type, to preserve previous behaviour. |
| 923 | private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) { |
| 924 | if (vpnNai != mService.getLegacyLockdownNai()) return; |
| 925 | |
| 926 | if (vpnNai.declaredUnderlyingNetworks == null |
| 927 | || vpnNai.declaredUnderlyingNetworks.length != 1) { |
| 928 | Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: " |
| 929 | + Arrays.toString(vpnNai.declaredUnderlyingNetworks)); |
| 930 | return; |
| 931 | } |
| 932 | final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork( |
| 933 | vpnNai.declaredUnderlyingNetworks[0]); |
| 934 | if (underlyingNai == null) return; |
| 935 | |
| 936 | final int type = underlyingNai.networkInfo.getType(); |
| 937 | final DetailedState state = DetailedState.CONNECTED; |
| 938 | maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */); |
| 939 | mService.sendLegacyNetworkBroadcast(underlyingNai, state, type); |
| 940 | } |
| 941 | |
| 942 | /** Adds the given network to the specified legacy type list. */ |
| 943 | public void add(int type, NetworkAgentInfo nai) { |
| 944 | if (!isTypeSupported(type)) { |
| 945 | return; // Invalid network type. |
| 946 | } |
| 947 | if (VDBG) log("Adding agent " + nai + " for legacy network type " + type); |
| 948 | |
| 949 | ArrayList<NetworkAgentInfo> list = mTypeLists[type]; |
| 950 | if (list.contains(nai)) { |
| 951 | return; |
| 952 | } |
| 953 | synchronized (mTypeLists) { |
| 954 | list.add(nai); |
| 955 | } |
| 956 | |
| 957 | // Send a broadcast if this is the first network of its type or if it's the default. |
| 958 | final boolean isDefaultNetwork = mService.isDefaultNetwork(nai); |
| 959 | |
| 960 | // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts |
| 961 | // to preserve previous behaviour. |
| 962 | final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED); |
| 963 | if ((list.size() == 1) || isDefaultNetwork) { |
| 964 | maybeLogBroadcast(nai, state, type, isDefaultNetwork); |
| 965 | mService.sendLegacyNetworkBroadcast(nai, state, type); |
| 966 | } |
| 967 | |
| 968 | if (type == TYPE_VPN && state == DetailedState.CONNECTED) { |
| 969 | maybeSendLegacyLockdownBroadcast(nai); |
| 970 | } |
| 971 | } |
| 972 | |
| 973 | /** Removes the given network from the specified legacy type list. */ |
| 974 | public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) { |
| 975 | ArrayList<NetworkAgentInfo> list = mTypeLists[type]; |
| 976 | if (list == null || list.isEmpty()) { |
| 977 | return; |
| 978 | } |
| 979 | final boolean wasFirstNetwork = list.get(0).equals(nai); |
| 980 | |
| 981 | synchronized (mTypeLists) { |
| 982 | if (!list.remove(nai)) { |
| 983 | return; |
| 984 | } |
| 985 | } |
| 986 | |
| 987 | if (wasFirstNetwork || wasDefault) { |
| 988 | maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault); |
| 989 | mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type); |
| 990 | } |
| 991 | |
| 992 | if (!list.isEmpty() && wasFirstNetwork) { |
| 993 | if (DBG) log("Other network available for type " + type + |
| 994 | ", sending connected broadcast"); |
| 995 | final NetworkAgentInfo replacement = list.get(0); |
| 996 | maybeLogBroadcast(replacement, DetailedState.CONNECTED, type, |
| 997 | mService.isDefaultNetwork(replacement)); |
| 998 | mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type); |
| 999 | } |
| 1000 | } |
| 1001 | |
| 1002 | /** Removes the given network from all legacy type lists. */ |
| 1003 | public void remove(NetworkAgentInfo nai, boolean wasDefault) { |
| 1004 | if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault); |
| 1005 | for (int type = 0; type < mTypeLists.length; type++) { |
| 1006 | remove(type, nai, wasDefault); |
| 1007 | } |
| 1008 | } |
| 1009 | |
| 1010 | // send out another legacy broadcast - currently only used for suspend/unsuspend |
| 1011 | // toggle |
| 1012 | public void update(NetworkAgentInfo nai) { |
| 1013 | final boolean isDefault = mService.isDefaultNetwork(nai); |
| 1014 | final DetailedState state = nai.networkInfo.getDetailedState(); |
| 1015 | for (int type = 0; type < mTypeLists.length; type++) { |
| 1016 | final ArrayList<NetworkAgentInfo> list = mTypeLists[type]; |
| 1017 | final boolean contains = (list != null && list.contains(nai)); |
| 1018 | final boolean isFirst = contains && (nai == list.get(0)); |
| 1019 | if (isFirst || contains && isDefault) { |
| 1020 | maybeLogBroadcast(nai, state, type, isDefault); |
| 1021 | mService.sendLegacyNetworkBroadcast(nai, state, type); |
| 1022 | } |
| 1023 | } |
| 1024 | } |
| 1025 | |
| 1026 | public void dump(IndentingPrintWriter pw) { |
| 1027 | pw.println("mLegacyTypeTracker:"); |
| 1028 | pw.increaseIndent(); |
| 1029 | pw.print("Supported types:"); |
| 1030 | for (int type = 0; type < mTypeLists.length; type++) { |
| 1031 | if (mTypeLists[type] != null) pw.print(" " + type); |
| 1032 | } |
| 1033 | pw.println(); |
| 1034 | pw.println("Current state:"); |
| 1035 | pw.increaseIndent(); |
| 1036 | synchronized (mTypeLists) { |
| 1037 | for (int type = 0; type < mTypeLists.length; type++) { |
| 1038 | if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue; |
| 1039 | for (NetworkAgentInfo nai : mTypeLists[type]) { |
| 1040 | pw.println(type + " " + nai.toShortString()); |
| 1041 | } |
| 1042 | } |
| 1043 | } |
| 1044 | pw.decreaseIndent(); |
| 1045 | pw.decreaseIndent(); |
| 1046 | pw.println(); |
| 1047 | } |
| 1048 | } |
| 1049 | private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this); |
| 1050 | |
| 1051 | final LocalPriorityDump mPriorityDumper = new LocalPriorityDump(); |
| 1052 | /** |
| 1053 | * Helper class which parses out priority arguments and dumps sections according to their |
| 1054 | * priority. If priority arguments are omitted, function calls the legacy dump command. |
| 1055 | */ |
| 1056 | private class LocalPriorityDump { |
| 1057 | private static final String PRIORITY_ARG = "--dump-priority"; |
| 1058 | private static final String PRIORITY_ARG_HIGH = "HIGH"; |
| 1059 | private static final String PRIORITY_ARG_NORMAL = "NORMAL"; |
| 1060 | |
| 1061 | LocalPriorityDump() {} |
| 1062 | |
| 1063 | private void dumpHigh(FileDescriptor fd, PrintWriter pw) { |
| 1064 | doDump(fd, pw, new String[] {DIAG_ARG}); |
| 1065 | doDump(fd, pw, new String[] {SHORT_ARG}); |
| 1066 | } |
| 1067 | |
| 1068 | private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) { |
| 1069 | doDump(fd, pw, args); |
| 1070 | } |
| 1071 | |
| 1072 | public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { |
| 1073 | if (args == null) { |
| 1074 | dumpNormal(fd, pw, args); |
| 1075 | return; |
| 1076 | } |
| 1077 | |
| 1078 | String priority = null; |
| 1079 | for (int argIndex = 0; argIndex < args.length; argIndex++) { |
| 1080 | if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) { |
| 1081 | argIndex++; |
| 1082 | priority = args[argIndex]; |
| 1083 | } |
| 1084 | } |
| 1085 | |
| 1086 | if (PRIORITY_ARG_HIGH.equals(priority)) { |
| 1087 | dumpHigh(fd, pw); |
| 1088 | } else if (PRIORITY_ARG_NORMAL.equals(priority)) { |
| 1089 | dumpNormal(fd, pw, args); |
| 1090 | } else { |
| 1091 | // ConnectivityService publishes binder service using publishBinderService() with |
| 1092 | // no priority assigned will be treated as NORMAL priority. Dumpsys does not send |
Chiachang Wang | 12d32a6 | 2021-05-17 16:57:15 +0800 | [diff] [blame] | 1093 | // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the |
| 1094 | // legacy output for dumpsys connectivity. |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 1095 | // TODO: Integrate into signal dump. |
| 1096 | dumpNormal(fd, pw, args); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 1097 | } |
| 1098 | } |
| 1099 | } |
| 1100 | |
| 1101 | /** |
| 1102 | * Keeps track of the number of requests made under different uids. |
| 1103 | */ |
| 1104 | public static class PerUidCounter { |
| 1105 | private final int mMaxCountPerUid; |
| 1106 | |
| 1107 | // Map from UID to number of NetworkRequests that UID has filed. |
| 1108 | @VisibleForTesting |
| 1109 | @GuardedBy("mUidToNetworkRequestCount") |
| 1110 | final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray(); |
| 1111 | |
| 1112 | /** |
| 1113 | * Constructor |
| 1114 | * |
| 1115 | * @param maxCountPerUid the maximum count per uid allowed |
| 1116 | */ |
| 1117 | public PerUidCounter(final int maxCountPerUid) { |
| 1118 | mMaxCountPerUid = maxCountPerUid; |
| 1119 | } |
| 1120 | |
| 1121 | /** |
| 1122 | * Increments the request count of the given uid. Throws an exception if the number |
| 1123 | * of open requests for the uid exceeds the value of maxCounterPerUid which is the value |
| 1124 | * passed into the constructor. see: {@link #PerUidCounter(int)}. |
| 1125 | * |
| 1126 | * @throws ServiceSpecificException with |
| 1127 | * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for |
| 1128 | * the uid exceed the allowed number. |
| 1129 | * |
| 1130 | * @param uid the uid that the request was made under |
| 1131 | */ |
| 1132 | public void incrementCountOrThrow(final int uid) { |
| 1133 | synchronized (mUidToNetworkRequestCount) { |
| 1134 | incrementCountOrThrow(uid, 1 /* numToIncrement */); |
| 1135 | } |
| 1136 | } |
| 1137 | |
| 1138 | private void incrementCountOrThrow(final int uid, final int numToIncrement) { |
| 1139 | final int newRequestCount = |
| 1140 | mUidToNetworkRequestCount.get(uid, 0) + numToIncrement; |
| 1141 | if (newRequestCount >= mMaxCountPerUid) { |
| 1142 | throw new ServiceSpecificException( |
| 1143 | ConnectivityManager.Errors.TOO_MANY_REQUESTS); |
| 1144 | } |
| 1145 | mUidToNetworkRequestCount.put(uid, newRequestCount); |
| 1146 | } |
| 1147 | |
| 1148 | /** |
| 1149 | * Decrements the request count of the given uid. |
| 1150 | * |
| 1151 | * @param uid the uid that the request was made under |
| 1152 | */ |
| 1153 | public void decrementCount(final int uid) { |
| 1154 | synchronized (mUidToNetworkRequestCount) { |
| 1155 | decrementCount(uid, 1 /* numToDecrement */); |
| 1156 | } |
| 1157 | } |
| 1158 | |
| 1159 | private void decrementCount(final int uid, final int numToDecrement) { |
| 1160 | final int newRequestCount = |
| 1161 | mUidToNetworkRequestCount.get(uid, 0) - numToDecrement; |
| 1162 | if (newRequestCount < 0) { |
| 1163 | logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid); |
| 1164 | } else if (newRequestCount == 0) { |
| 1165 | mUidToNetworkRequestCount.delete(uid); |
| 1166 | } else { |
| 1167 | mUidToNetworkRequestCount.put(uid, newRequestCount); |
| 1168 | } |
| 1169 | } |
| 1170 | |
| 1171 | /** |
| 1172 | * Used to adjust the request counter for the per-app API flows. Directly adjusting the |
| 1173 | * counter is not ideal however in the per-app flows, the nris can't be removed until they |
| 1174 | * are used to create the new nris upon set. Therefore the request count limit can be |
| 1175 | * artificially hit. This method is used as a workaround for this particular case so that |
| 1176 | * the request counts are accounted for correctly. |
| 1177 | * @param uid the uid to adjust counts for |
| 1178 | * @param numOfNewRequests the new request count to account for |
| 1179 | * @param r the runnable to execute |
| 1180 | */ |
| 1181 | public void transact(final int uid, final int numOfNewRequests, @NonNull final Runnable r) { |
| 1182 | // This should only be used on the handler thread as per all current and foreseen |
| 1183 | // use-cases. ensureRunningOnConnectivityServiceThread() can't be used because there is |
| 1184 | // no ref to the outer ConnectivityService. |
| 1185 | synchronized (mUidToNetworkRequestCount) { |
| 1186 | final int reqCountOverage = getCallingUidRequestCountOverage(uid, numOfNewRequests); |
| 1187 | decrementCount(uid, reqCountOverage); |
| 1188 | r.run(); |
| 1189 | incrementCountOrThrow(uid, reqCountOverage); |
| 1190 | } |
| 1191 | } |
| 1192 | |
| 1193 | private int getCallingUidRequestCountOverage(final int uid, final int numOfNewRequests) { |
| 1194 | final int newUidRequestCount = mUidToNetworkRequestCount.get(uid, 0) |
| 1195 | + numOfNewRequests; |
| 1196 | return newUidRequestCount >= MAX_NETWORK_REQUESTS_PER_SYSTEM_UID |
| 1197 | ? newUidRequestCount - (MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1) : 0; |
| 1198 | } |
| 1199 | } |
| 1200 | |
| 1201 | /** |
| 1202 | * Dependencies of ConnectivityService, for injection in tests. |
| 1203 | */ |
| 1204 | @VisibleForTesting |
| 1205 | public static class Dependencies { |
| 1206 | public int getCallingUid() { |
| 1207 | return Binder.getCallingUid(); |
| 1208 | } |
| 1209 | |
| 1210 | /** |
| 1211 | * Get system properties to use in ConnectivityService. |
| 1212 | */ |
| 1213 | public MockableSystemProperties getSystemProperties() { |
| 1214 | return new MockableSystemProperties(); |
| 1215 | } |
| 1216 | |
| 1217 | /** |
| 1218 | * Get the {@link ConnectivityResources} to use in ConnectivityService. |
| 1219 | */ |
| 1220 | public ConnectivityResources getResources(@NonNull Context ctx) { |
| 1221 | return new ConnectivityResources(ctx); |
| 1222 | } |
| 1223 | |
| 1224 | /** |
| 1225 | * Create a HandlerThread to use in ConnectivityService. |
| 1226 | */ |
| 1227 | public HandlerThread makeHandlerThread() { |
| 1228 | return new HandlerThread("ConnectivityServiceThread"); |
| 1229 | } |
| 1230 | |
| 1231 | /** |
| 1232 | * Get a reference to the ModuleNetworkStackClient. |
| 1233 | */ |
| 1234 | public NetworkStackClientBase getNetworkStack() { |
| 1235 | return ModuleNetworkStackClient.getInstance(null); |
| 1236 | } |
| 1237 | |
| 1238 | /** |
| 1239 | * @see ProxyTracker |
| 1240 | */ |
| 1241 | public ProxyTracker makeProxyTracker(@NonNull Context context, |
| 1242 | @NonNull Handler connServiceHandler) { |
| 1243 | return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED); |
| 1244 | } |
| 1245 | |
| 1246 | /** |
| 1247 | * @see NetIdManager |
| 1248 | */ |
| 1249 | public NetIdManager makeNetIdManager() { |
| 1250 | return new NetIdManager(); |
| 1251 | } |
| 1252 | |
| 1253 | /** |
| 1254 | * @see NetworkUtils#queryUserAccess(int, int) |
| 1255 | */ |
| 1256 | public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) { |
| 1257 | return cs.queryUserAccess(uid, network); |
| 1258 | } |
| 1259 | |
| 1260 | /** |
| 1261 | * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets |
| 1262 | * requires CAP_NET_ADMIN, which the unit tests do not have. |
| 1263 | */ |
| 1264 | public int getConnectionOwnerUid(int protocol, InetSocketAddress local, |
| 1265 | InetSocketAddress remote) { |
| 1266 | return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote); |
| 1267 | } |
| 1268 | |
| 1269 | /** |
| 1270 | * @see MultinetworkPolicyTracker |
| 1271 | */ |
| 1272 | public MultinetworkPolicyTracker makeMultinetworkPolicyTracker( |
| 1273 | @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) { |
| 1274 | return new MultinetworkPolicyTracker(c, h, r); |
| 1275 | } |
| 1276 | |
| 1277 | /** |
| 1278 | * @see BatteryStatsManager |
| 1279 | */ |
| 1280 | public void reportNetworkInterfaceForTransports(Context context, String iface, |
| 1281 | int[] transportTypes) { |
| 1282 | final BatteryStatsManager batteryStats = |
| 1283 | context.getSystemService(BatteryStatsManager.class); |
| 1284 | batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes); |
| 1285 | } |
| 1286 | |
| 1287 | public boolean getCellular464XlatEnabled() { |
| 1288 | return NetworkProperties.isCellular464XlatEnabled().orElse(true); |
| 1289 | } |
Remi NGUYEN VAN | ff55aeb | 2021-06-16 11:37:53 +0000 | [diff] [blame] | 1290 | |
| 1291 | /** |
| 1292 | * @see PendingIntent#intentFilterEquals |
| 1293 | */ |
| 1294 | public boolean intentFilterEquals(PendingIntent a, PendingIntent b) { |
| 1295 | return a.intentFilterEquals(b); |
| 1296 | } |
| 1297 | |
| 1298 | /** |
| 1299 | * @see LocationPermissionChecker |
| 1300 | */ |
| 1301 | public LocationPermissionChecker makeLocationPermissionChecker(Context context) { |
| 1302 | return new LocationPermissionChecker(context); |
| 1303 | } |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 1304 | } |
| 1305 | |
| 1306 | public ConnectivityService(Context context) { |
| 1307 | this(context, getDnsResolver(context), new IpConnectivityLog(), |
| 1308 | INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)), |
| 1309 | new Dependencies()); |
| 1310 | } |
| 1311 | |
| 1312 | @VisibleForTesting |
| 1313 | protected ConnectivityService(Context context, IDnsResolver dnsresolver, |
| 1314 | IpConnectivityLog logger, INetd netd, Dependencies deps) { |
| 1315 | if (DBG) log("ConnectivityService starting up"); |
| 1316 | |
| 1317 | mDeps = Objects.requireNonNull(deps, "missing Dependencies"); |
| 1318 | mSystemProperties = mDeps.getSystemProperties(); |
| 1319 | mNetIdManager = mDeps.makeNetIdManager(); |
| 1320 | mContext = Objects.requireNonNull(context, "missing Context"); |
| 1321 | mResources = deps.getResources(mContext); |
| 1322 | mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID); |
| 1323 | mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID); |
| 1324 | |
| 1325 | mMetricsLog = logger; |
| 1326 | mNetworkRanker = new NetworkRanker(); |
| 1327 | final NetworkRequest defaultInternetRequest = createDefaultRequest(); |
| 1328 | mDefaultRequest = new NetworkRequestInfo( |
| 1329 | Process.myUid(), defaultInternetRequest, null, |
| 1330 | new Binder(), NetworkCallback.FLAG_INCLUDE_LOCATION_INFO, |
| 1331 | null /* attributionTags */); |
| 1332 | mNetworkRequests.put(defaultInternetRequest, mDefaultRequest); |
| 1333 | mDefaultNetworkRequests.add(mDefaultRequest); |
| 1334 | mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest); |
| 1335 | |
| 1336 | mDefaultMobileDataRequest = createDefaultInternetRequestForTransport( |
| 1337 | NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST); |
| 1338 | |
| 1339 | // The default WiFi request is a background request so that apps using WiFi are |
| 1340 | // migrated to a better network (typically ethernet) when one comes up, instead |
| 1341 | // of staying on WiFi forever. |
| 1342 | mDefaultWifiRequest = createDefaultInternetRequestForTransport( |
| 1343 | NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST); |
| 1344 | |
| 1345 | mDefaultVehicleRequest = createAlwaysOnRequestForCapability( |
| 1346 | NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL, |
| 1347 | NetworkRequest.Type.BACKGROUND_REQUEST); |
| 1348 | |
| 1349 | mHandlerThread = mDeps.makeHandlerThread(); |
| 1350 | mHandlerThread.start(); |
| 1351 | mHandler = new InternalHandler(mHandlerThread.getLooper()); |
| 1352 | mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper()); |
| 1353 | mConnectivityDiagnosticsHandler = |
| 1354 | new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper()); |
| 1355 | |
| 1356 | mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(), |
| 1357 | ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000); |
| 1358 | |
| 1359 | mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS); |
| 1360 | // TODO: Consider making the timer customizable. |
| 1361 | mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS; |
| 1362 | |
| 1363 | mStatsManager = mContext.getSystemService(NetworkStatsManager.class); |
| 1364 | mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class); |
| 1365 | mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver"); |
| 1366 | mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler); |
| 1367 | |
| 1368 | mNetd = netd; |
| 1369 | mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); |
| 1370 | mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE); |
Remi NGUYEN VAN | ff55aeb | 2021-06-16 11:37:53 +0000 | [diff] [blame] | 1371 | mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 1372 | |
| 1373 | // To ensure uid state is synchronized with Network Policy, register for |
| 1374 | // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService |
| 1375 | // reading existing policy from disk. |
| 1376 | mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback); |
| 1377 | |
| 1378 | final PowerManager powerManager = (PowerManager) context.getSystemService( |
| 1379 | Context.POWER_SERVICE); |
| 1380 | mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); |
| 1381 | mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); |
| 1382 | |
| 1383 | mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager); |
| 1384 | mProtectedNetworks = new ArrayList<>(); |
| 1385 | int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks); |
| 1386 | for (int p : protectedNetworks) { |
| 1387 | if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) { |
| 1388 | mProtectedNetworks.add(p); |
| 1389 | } else { |
| 1390 | if (DBG) loge("Ignoring protectedNetwork " + p); |
| 1391 | } |
| 1392 | } |
| 1393 | |
| 1394 | mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE); |
| 1395 | |
| 1396 | mPermissionMonitor = new PermissionMonitor(mContext, mNetd); |
| 1397 | |
| 1398 | mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */); |
| 1399 | // Listen for user add/removes to inform PermissionMonitor. |
| 1400 | // Should run on mHandler to avoid any races. |
| 1401 | final IntentFilter userIntentFilter = new IntentFilter(); |
| 1402 | userIntentFilter.addAction(Intent.ACTION_USER_ADDED); |
| 1403 | userIntentFilter.addAction(Intent.ACTION_USER_REMOVED); |
| 1404 | mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter, |
| 1405 | null /* broadcastPermission */, mHandler); |
| 1406 | |
| 1407 | // Listen to package add/removes for netd |
| 1408 | final IntentFilter packageIntentFilter = new IntentFilter(); |
| 1409 | packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED); |
| 1410 | packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); |
| 1411 | packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED); |
| 1412 | packageIntentFilter.addDataScheme("package"); |
| 1413 | mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter, |
| 1414 | null /* broadcastPermission */, mHandler); |
| 1415 | |
| 1416 | mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd); |
| 1417 | |
| 1418 | mNetdCallback = new NetdCallback(); |
| 1419 | try { |
| 1420 | mNetd.registerUnsolicitedEventListener(mNetdCallback); |
| 1421 | } catch (RemoteException | ServiceSpecificException e) { |
| 1422 | loge("Error registering event listener :" + e); |
| 1423 | } |
| 1424 | |
| 1425 | mSettingsObserver = new SettingsObserver(mContext, mHandler); |
| 1426 | registerSettingsCallbacks(); |
| 1427 | |
| 1428 | mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler); |
| 1429 | mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager); |
| 1430 | mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter); |
| 1431 | |
| 1432 | final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(), |
| 1433 | ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT, |
| 1434 | LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT); |
| 1435 | final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(), |
| 1436 | ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS, |
| 1437 | LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS); |
| 1438 | mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit); |
| 1439 | |
| 1440 | mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker( |
| 1441 | mContext, mHandler, () -> updateAvoidBadWifi()); |
| 1442 | mMultinetworkPolicyTracker.start(); |
| 1443 | |
| 1444 | mDnsManager = new DnsManager(mContext, mDnsResolver); |
| 1445 | registerPrivateDnsSettingsCallbacks(); |
| 1446 | |
| 1447 | // This NAI is a sentinel used to offer no service to apps that are on a multi-layer |
| 1448 | // request that doesn't allow fallback to the default network. It should never be visible |
| 1449 | // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal |
| 1450 | // arguments like the handler or the DnsResolver. |
| 1451 | // TODO : remove this ; it is probably better handled with a sentinel request. |
| 1452 | mNoServiceNetwork = new NetworkAgentInfo(null, |
Ken Chen | 4f612fa | 2021-05-14 14:30:43 +0800 | [diff] [blame] | 1453 | new Network(INetd.UNREACHABLE_NET_ID), |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 1454 | new NetworkInfo(TYPE_NONE, 0, "", ""), |
| 1455 | new LinkProperties(), new NetworkCapabilities(), |
| 1456 | new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null, |
| 1457 | new NetworkAgentConfig(), this, null, null, 0, INVALID_UID, |
| 1458 | mLingerDelayMs, mQosCallbackTracker, mDeps); |
| 1459 | } |
| 1460 | |
| 1461 | private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) { |
| 1462 | return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid)); |
| 1463 | } |
| 1464 | |
| 1465 | private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange( |
| 1466 | @NonNull final UidRange uids) { |
| 1467 | final NetworkCapabilities netCap = new NetworkCapabilities(); |
| 1468 | netCap.addCapability(NET_CAPABILITY_INTERNET); |
| 1469 | netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED); |
| 1470 | netCap.removeCapability(NET_CAPABILITY_NOT_VPN); |
| 1471 | netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids))); |
| 1472 | return netCap; |
| 1473 | } |
| 1474 | |
| 1475 | private NetworkRequest createDefaultRequest() { |
| 1476 | return createDefaultInternetRequestForTransport( |
| 1477 | TYPE_NONE, NetworkRequest.Type.REQUEST); |
| 1478 | } |
| 1479 | |
| 1480 | private NetworkRequest createDefaultInternetRequestForTransport( |
| 1481 | int transportType, NetworkRequest.Type type) { |
| 1482 | final NetworkCapabilities netCap = new NetworkCapabilities(); |
| 1483 | netCap.addCapability(NET_CAPABILITY_INTERNET); |
| 1484 | netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED); |
| 1485 | netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName()); |
| 1486 | if (transportType > TYPE_NONE) { |
| 1487 | netCap.addTransportType(transportType); |
| 1488 | } |
| 1489 | return createNetworkRequest(type, netCap); |
| 1490 | } |
| 1491 | |
| 1492 | private NetworkRequest createNetworkRequest( |
| 1493 | NetworkRequest.Type type, NetworkCapabilities netCap) { |
| 1494 | return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type); |
| 1495 | } |
| 1496 | |
| 1497 | private NetworkRequest createAlwaysOnRequestForCapability(int capability, |
| 1498 | NetworkRequest.Type type) { |
| 1499 | final NetworkCapabilities netCap = new NetworkCapabilities(); |
| 1500 | netCap.clearAll(); |
| 1501 | netCap.addCapability(capability); |
| 1502 | netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName()); |
| 1503 | return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type); |
| 1504 | } |
| 1505 | |
| 1506 | // Used only for testing. |
| 1507 | // TODO: Delete this and either: |
| 1508 | // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires |
| 1509 | // changing ContentResolver to make registerContentObserver non-final). |
| 1510 | // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it |
| 1511 | // by subclassing SettingsObserver. |
| 1512 | @VisibleForTesting |
| 1513 | void updateAlwaysOnNetworks() { |
| 1514 | mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS); |
| 1515 | } |
| 1516 | |
| 1517 | // See FakeSettingsProvider comment above. |
| 1518 | @VisibleForTesting |
| 1519 | void updatePrivateDnsSettings() { |
| 1520 | mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED); |
| 1521 | } |
| 1522 | |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 1523 | @VisibleForTesting |
| 1524 | void updateMobileDataPreferredUids() { |
| 1525 | mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED); |
| 1526 | } |
| 1527 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 1528 | private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) { |
| 1529 | final boolean enable = mContext.getResources().getBoolean(id); |
| 1530 | handleAlwaysOnNetworkRequest(networkRequest, enable); |
| 1531 | } |
| 1532 | |
| 1533 | private void handleAlwaysOnNetworkRequest( |
| 1534 | NetworkRequest networkRequest, String settingName, boolean defaultValue) { |
| 1535 | final boolean enable = toBool(Settings.Global.getInt( |
| 1536 | mContext.getContentResolver(), settingName, encodeBool(defaultValue))); |
| 1537 | handleAlwaysOnNetworkRequest(networkRequest, enable); |
| 1538 | } |
| 1539 | |
| 1540 | private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) { |
| 1541 | final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null); |
| 1542 | if (enable == isEnabled) { |
| 1543 | return; // Nothing to do. |
| 1544 | } |
| 1545 | |
| 1546 | if (enable) { |
| 1547 | handleRegisterNetworkRequest(new NetworkRequestInfo( |
| 1548 | Process.myUid(), networkRequest, null, new Binder(), |
| 1549 | NetworkCallback.FLAG_INCLUDE_LOCATION_INFO, |
| 1550 | null /* attributionTags */)); |
| 1551 | } else { |
| 1552 | handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID, |
| 1553 | /* callOnUnavailable */ false); |
| 1554 | } |
| 1555 | } |
| 1556 | |
| 1557 | private void handleConfigureAlwaysOnNetworks() { |
| 1558 | handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest, |
| 1559 | ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */); |
| 1560 | handleAlwaysOnNetworkRequest(mDefaultWifiRequest, |
| 1561 | ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */); |
| 1562 | final boolean vehicleAlwaysRequested = mResources.get().getBoolean( |
| 1563 | R.bool.config_vehicleInternalNetworkAlwaysRequested); |
Remi NGUYEN VAN | 1423347 | 2021-05-19 12:05:13 +0900 | [diff] [blame] | 1564 | handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 1565 | } |
| 1566 | |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 1567 | // Note that registering observer for setting do not get initial callback when registering, |
paulhu | 7ed70a9 | 2021-05-26 12:22:38 +0800 | [diff] [blame] | 1568 | // callers must fetch the initial value of the setting themselves if needed. |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 1569 | private void registerSettingsCallbacks() { |
| 1570 | // Watch for global HTTP proxy changes. |
| 1571 | mSettingsObserver.observe( |
| 1572 | Settings.Global.getUriFor(Settings.Global.HTTP_PROXY), |
| 1573 | EVENT_APPLY_GLOBAL_HTTP_PROXY); |
| 1574 | |
| 1575 | // Watch for whether or not to keep mobile data always on. |
| 1576 | mSettingsObserver.observe( |
| 1577 | Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON), |
| 1578 | EVENT_CONFIGURE_ALWAYS_ON_NETWORKS); |
| 1579 | |
| 1580 | // Watch for whether or not to keep wifi always on. |
| 1581 | mSettingsObserver.observe( |
| 1582 | Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED), |
| 1583 | EVENT_CONFIGURE_ALWAYS_ON_NETWORKS); |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 1584 | |
| 1585 | // Watch for mobile data preferred uids changes. |
| 1586 | mSettingsObserver.observe( |
| 1587 | Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS), |
| 1588 | EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 1589 | } |
| 1590 | |
| 1591 | private void registerPrivateDnsSettingsCallbacks() { |
| 1592 | for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) { |
| 1593 | mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED); |
| 1594 | } |
| 1595 | } |
| 1596 | |
| 1597 | private synchronized int nextNetworkRequestId() { |
| 1598 | // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if |
| 1599 | // doing that. |
| 1600 | return mNextNetworkRequestId++; |
| 1601 | } |
| 1602 | |
| 1603 | @VisibleForTesting |
| 1604 | protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) { |
| 1605 | if (network == null) { |
| 1606 | return null; |
| 1607 | } |
| 1608 | return getNetworkAgentInfoForNetId(network.getNetId()); |
| 1609 | } |
| 1610 | |
| 1611 | private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) { |
| 1612 | synchronized (mNetworkForNetId) { |
| 1613 | return mNetworkForNetId.get(netId); |
| 1614 | } |
| 1615 | } |
| 1616 | |
| 1617 | // TODO: determine what to do when more than one VPN applies to |uid|. |
| 1618 | private NetworkAgentInfo getVpnForUid(int uid) { |
| 1619 | synchronized (mNetworkForNetId) { |
| 1620 | for (int i = 0; i < mNetworkForNetId.size(); i++) { |
| 1621 | final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i); |
| 1622 | if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) { |
| 1623 | return nai; |
| 1624 | } |
| 1625 | } |
| 1626 | } |
| 1627 | return null; |
| 1628 | } |
| 1629 | |
| 1630 | private Network[] getVpnUnderlyingNetworks(int uid) { |
| 1631 | if (mLockdownEnabled) return null; |
| 1632 | final NetworkAgentInfo nai = getVpnForUid(uid); |
| 1633 | if (nai != null) return nai.declaredUnderlyingNetworks; |
| 1634 | return null; |
| 1635 | } |
| 1636 | |
| 1637 | private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) { |
| 1638 | NetworkAgentInfo nai = getDefaultNetworkForUid(uid); |
| 1639 | |
| 1640 | final Network[] networks = getVpnUnderlyingNetworks(uid); |
| 1641 | if (networks != null) { |
| 1642 | // getUnderlyingNetworks() returns: |
| 1643 | // null => there was no VPN, or the VPN didn't specify anything, so we use the default. |
| 1644 | // empty array => the VPN explicitly said "no default network". |
| 1645 | // non-empty array => the VPN specified one or more default networks; we use the |
| 1646 | // first one. |
| 1647 | if (networks.length > 0) { |
| 1648 | nai = getNetworkAgentInfoForNetwork(networks[0]); |
| 1649 | } else { |
| 1650 | nai = null; |
| 1651 | } |
| 1652 | } |
| 1653 | return nai; |
| 1654 | } |
| 1655 | |
| 1656 | /** |
| 1657 | * Check if UID should be blocked from using the specified network. |
| 1658 | */ |
| 1659 | private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc, |
| 1660 | final int uid, final boolean ignoreBlocked) { |
| 1661 | // Networks aren't blocked when ignoring blocked status |
| 1662 | if (ignoreBlocked) { |
| 1663 | return false; |
| 1664 | } |
| 1665 | if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true; |
| 1666 | final long ident = Binder.clearCallingIdentity(); |
| 1667 | try { |
| 1668 | final boolean metered = nc == null ? true : nc.isMetered(); |
| 1669 | return mPolicyManager.isUidNetworkingBlocked(uid, metered); |
| 1670 | } finally { |
| 1671 | Binder.restoreCallingIdentity(ident); |
| 1672 | } |
| 1673 | } |
| 1674 | |
| 1675 | private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) { |
| 1676 | if (ni == null || !LOGD_BLOCKED_NETWORKINFO) { |
| 1677 | return; |
| 1678 | } |
| 1679 | final boolean blocked; |
| 1680 | synchronized (mBlockedAppUids) { |
| 1681 | if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) { |
| 1682 | blocked = true; |
| 1683 | } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) { |
| 1684 | blocked = false; |
| 1685 | } else { |
| 1686 | return; |
| 1687 | } |
| 1688 | } |
| 1689 | String action = blocked ? "BLOCKED" : "UNBLOCKED"; |
| 1690 | log(String.format("Returning %s NetworkInfo to uid=%d", action, uid)); |
| 1691 | mNetworkInfoBlockingLogs.log(action + " " + uid); |
| 1692 | } |
| 1693 | |
| 1694 | private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) { |
| 1695 | if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) { |
| 1696 | return; |
| 1697 | } |
| 1698 | final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED"; |
| 1699 | final int requestId = nri.getActiveRequest() != null |
| 1700 | ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId; |
| 1701 | mNetworkInfoBlockingLogs.log(String.format( |
| 1702 | "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(), |
| 1703 | Integer.toHexString(blocked))); |
| 1704 | } |
| 1705 | |
| 1706 | /** |
| 1707 | * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For |
| 1708 | * example, this may mark the network as {@link DetailedState#BLOCKED} based |
| 1709 | * on {@link #isNetworkWithCapabilitiesBlocked}. |
| 1710 | */ |
| 1711 | @NonNull |
| 1712 | private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type, |
| 1713 | @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) { |
| 1714 | final NetworkInfo filtered = new NetworkInfo(networkInfo); |
| 1715 | // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network |
| 1716 | // but only exists if an app asks about them or requests them. Ensure the requesting app |
| 1717 | // gets the type it asks for. |
| 1718 | filtered.setType(type); |
| 1719 | if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) { |
| 1720 | filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */, |
| 1721 | null /* extraInfo */); |
| 1722 | } |
| 1723 | filterForLegacyLockdown(filtered); |
| 1724 | return filtered; |
| 1725 | } |
| 1726 | |
| 1727 | private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid, |
| 1728 | boolean ignoreBlocked) { |
| 1729 | return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(), |
| 1730 | nai.networkCapabilities, uid, ignoreBlocked); |
| 1731 | } |
| 1732 | |
| 1733 | /** |
| 1734 | * Return NetworkInfo for the active (i.e., connected) network interface. |
| 1735 | * It is assumed that at most one network is active at a time. If more |
| 1736 | * than one is active, it is indeterminate which will be returned. |
| 1737 | * @return the info for the active network, or {@code null} if none is |
| 1738 | * active |
| 1739 | */ |
| 1740 | @Override |
| 1741 | public NetworkInfo getActiveNetworkInfo() { |
| 1742 | enforceAccessPermission(); |
| 1743 | final int uid = mDeps.getCallingUid(); |
| 1744 | final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid); |
| 1745 | if (nai == null) return null; |
| 1746 | final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false); |
| 1747 | maybeLogBlockedNetworkInfo(networkInfo, uid); |
| 1748 | return networkInfo; |
| 1749 | } |
| 1750 | |
| 1751 | @Override |
| 1752 | public Network getActiveNetwork() { |
| 1753 | enforceAccessPermission(); |
| 1754 | return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false); |
| 1755 | } |
| 1756 | |
| 1757 | @Override |
| 1758 | public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) { |
| 1759 | PermissionUtils.enforceNetworkStackPermission(mContext); |
| 1760 | return getActiveNetworkForUidInternal(uid, ignoreBlocked); |
| 1761 | } |
| 1762 | |
| 1763 | private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) { |
| 1764 | final NetworkAgentInfo vpnNai = getVpnForUid(uid); |
| 1765 | if (vpnNai != null) { |
| 1766 | final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid); |
| 1767 | if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) { |
| 1768 | return vpnNai.network; |
| 1769 | } |
| 1770 | } |
| 1771 | |
| 1772 | NetworkAgentInfo nai = getDefaultNetworkForUid(uid); |
| 1773 | if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, |
| 1774 | ignoreBlocked)) { |
| 1775 | return null; |
| 1776 | } |
| 1777 | return nai.network; |
| 1778 | } |
| 1779 | |
| 1780 | @Override |
| 1781 | public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) { |
| 1782 | PermissionUtils.enforceNetworkStackPermission(mContext); |
| 1783 | final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid); |
| 1784 | if (nai == null) return null; |
| 1785 | return getFilteredNetworkInfo(nai, uid, ignoreBlocked); |
| 1786 | } |
| 1787 | |
| 1788 | /** Returns a NetworkInfo object for a network that doesn't exist. */ |
| 1789 | private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) { |
| 1790 | final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */, |
| 1791 | getNetworkTypeName(networkType), "" /* subtypeName */); |
| 1792 | info.setIsAvailable(true); |
| 1793 | // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when |
| 1794 | // background data is restricted. |
| 1795 | final NetworkCapabilities nc = new NetworkCapabilities(); // Metered. |
| 1796 | final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false) |
| 1797 | ? DetailedState.BLOCKED |
| 1798 | : DetailedState.DISCONNECTED; |
| 1799 | info.setDetailedState(state, null /* reason */, null /* extraInfo */); |
| 1800 | filterForLegacyLockdown(info); |
| 1801 | return info; |
| 1802 | } |
| 1803 | |
| 1804 | private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) { |
| 1805 | if (!mLegacyTypeTracker.isTypeSupported(networkType)) { |
| 1806 | return null; |
| 1807 | } |
| 1808 | final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); |
| 1809 | if (nai == null) { |
| 1810 | return makeFakeNetworkInfo(networkType, uid); |
| 1811 | } |
| 1812 | return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid, |
| 1813 | false); |
| 1814 | } |
| 1815 | |
| 1816 | @Override |
| 1817 | public NetworkInfo getNetworkInfo(int networkType) { |
| 1818 | enforceAccessPermission(); |
| 1819 | final int uid = mDeps.getCallingUid(); |
| 1820 | if (getVpnUnderlyingNetworks(uid) != null) { |
| 1821 | // A VPN is active, so we may need to return one of its underlying networks. This |
| 1822 | // information is not available in LegacyTypeTracker, so we have to get it from |
| 1823 | // getNetworkAgentInfoForUid. |
| 1824 | final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid); |
| 1825 | if (nai == null) return null; |
| 1826 | final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false); |
| 1827 | if (networkInfo.getType() == networkType) { |
| 1828 | return networkInfo; |
| 1829 | } |
| 1830 | } |
| 1831 | return getFilteredNetworkInfoForType(networkType, uid); |
| 1832 | } |
| 1833 | |
| 1834 | @Override |
| 1835 | public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) { |
| 1836 | enforceAccessPermission(); |
| 1837 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 1838 | if (nai == null) return null; |
| 1839 | return getFilteredNetworkInfo(nai, uid, ignoreBlocked); |
| 1840 | } |
| 1841 | |
| 1842 | @Override |
| 1843 | public NetworkInfo[] getAllNetworkInfo() { |
| 1844 | enforceAccessPermission(); |
| 1845 | final ArrayList<NetworkInfo> result = new ArrayList<>(); |
| 1846 | for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE; |
| 1847 | networkType++) { |
| 1848 | NetworkInfo info = getNetworkInfo(networkType); |
| 1849 | if (info != null) { |
| 1850 | result.add(info); |
| 1851 | } |
| 1852 | } |
| 1853 | return result.toArray(new NetworkInfo[result.size()]); |
| 1854 | } |
| 1855 | |
| 1856 | @Override |
| 1857 | public Network getNetworkForType(int networkType) { |
| 1858 | enforceAccessPermission(); |
| 1859 | if (!mLegacyTypeTracker.isTypeSupported(networkType)) { |
| 1860 | return null; |
| 1861 | } |
| 1862 | final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); |
| 1863 | if (nai == null) { |
| 1864 | return null; |
| 1865 | } |
| 1866 | final int uid = mDeps.getCallingUid(); |
| 1867 | if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) { |
| 1868 | return null; |
| 1869 | } |
| 1870 | return nai.network; |
| 1871 | } |
| 1872 | |
| 1873 | @Override |
| 1874 | public Network[] getAllNetworks() { |
| 1875 | enforceAccessPermission(); |
| 1876 | synchronized (mNetworkForNetId) { |
| 1877 | final Network[] result = new Network[mNetworkForNetId.size()]; |
| 1878 | for (int i = 0; i < mNetworkForNetId.size(); i++) { |
| 1879 | result[i] = mNetworkForNetId.valueAt(i).network; |
| 1880 | } |
| 1881 | return result; |
| 1882 | } |
| 1883 | } |
| 1884 | |
| 1885 | @Override |
| 1886 | public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser( |
| 1887 | int userId, String callingPackageName, @Nullable String callingAttributionTag) { |
| 1888 | // The basic principle is: if an app's traffic could possibly go over a |
| 1889 | // network, without the app doing anything multinetwork-specific, |
| 1890 | // (hence, by "default"), then include that network's capabilities in |
| 1891 | // the array. |
| 1892 | // |
| 1893 | // In the normal case, app traffic only goes over the system's default |
| 1894 | // network connection, so that's the only network returned. |
| 1895 | // |
| 1896 | // With a VPN in force, some app traffic may go into the VPN, and thus |
| 1897 | // over whatever underlying networks the VPN specifies, while other app |
| 1898 | // traffic may go over the system default network (e.g.: a split-tunnel |
| 1899 | // VPN, or an app disallowed by the VPN), so the set of networks |
| 1900 | // returned includes the VPN's underlying networks and the system |
| 1901 | // default. |
| 1902 | enforceAccessPermission(); |
| 1903 | |
| 1904 | HashMap<Network, NetworkCapabilities> result = new HashMap<>(); |
| 1905 | |
| 1906 | for (final NetworkRequestInfo nri : mDefaultNetworkRequests) { |
| 1907 | if (!nri.isBeingSatisfied()) { |
| 1908 | continue; |
| 1909 | } |
| 1910 | final NetworkAgentInfo nai = nri.getSatisfier(); |
| 1911 | final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai); |
| 1912 | if (null != nc |
| 1913 | && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) |
| 1914 | && !result.containsKey(nai.network)) { |
| 1915 | result.put( |
| 1916 | nai.network, |
| 1917 | createWithLocationInfoSanitizedIfNecessaryWhenParceled( |
| 1918 | nc, false /* includeLocationSensitiveInfo */, |
| 1919 | getCallingPid(), mDeps.getCallingUid(), callingPackageName, |
| 1920 | callingAttributionTag)); |
| 1921 | } |
| 1922 | } |
| 1923 | |
| 1924 | // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null. |
| 1925 | final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid()); |
| 1926 | if (null != networks) { |
| 1927 | for (final Network network : networks) { |
| 1928 | final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network); |
| 1929 | if (null != nc) { |
| 1930 | result.put( |
| 1931 | network, |
| 1932 | createWithLocationInfoSanitizedIfNecessaryWhenParceled( |
| 1933 | nc, |
| 1934 | false /* includeLocationSensitiveInfo */, |
| 1935 | getCallingPid(), mDeps.getCallingUid(), callingPackageName, |
| 1936 | callingAttributionTag)); |
| 1937 | } |
| 1938 | } |
| 1939 | } |
| 1940 | |
| 1941 | NetworkCapabilities[] out = new NetworkCapabilities[result.size()]; |
| 1942 | out = result.values().toArray(out); |
| 1943 | return out; |
| 1944 | } |
| 1945 | |
| 1946 | @Override |
| 1947 | public boolean isNetworkSupported(int networkType) { |
| 1948 | enforceAccessPermission(); |
| 1949 | return mLegacyTypeTracker.isTypeSupported(networkType); |
| 1950 | } |
| 1951 | |
| 1952 | /** |
| 1953 | * Return LinkProperties for the active (i.e., connected) default |
| 1954 | * network interface for the calling uid. |
| 1955 | * @return the ip properties for the active network, or {@code null} if |
| 1956 | * none is active |
| 1957 | */ |
| 1958 | @Override |
| 1959 | public LinkProperties getActiveLinkProperties() { |
| 1960 | enforceAccessPermission(); |
| 1961 | final int uid = mDeps.getCallingUid(); |
| 1962 | NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid); |
| 1963 | if (nai == null) return null; |
| 1964 | return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties, |
| 1965 | Binder.getCallingPid(), uid); |
| 1966 | } |
| 1967 | |
| 1968 | @Override |
| 1969 | public LinkProperties getLinkPropertiesForType(int networkType) { |
| 1970 | enforceAccessPermission(); |
| 1971 | NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); |
| 1972 | final LinkProperties lp = getLinkProperties(nai); |
| 1973 | if (lp == null) return null; |
| 1974 | return linkPropertiesRestrictedForCallerPermissions( |
| 1975 | lp, Binder.getCallingPid(), mDeps.getCallingUid()); |
| 1976 | } |
| 1977 | |
| 1978 | // TODO - this should be ALL networks |
| 1979 | @Override |
| 1980 | public LinkProperties getLinkProperties(Network network) { |
| 1981 | enforceAccessPermission(); |
| 1982 | final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network)); |
| 1983 | if (lp == null) return null; |
| 1984 | return linkPropertiesRestrictedForCallerPermissions( |
| 1985 | lp, Binder.getCallingPid(), mDeps.getCallingUid()); |
| 1986 | } |
| 1987 | |
| 1988 | @Nullable |
| 1989 | private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) { |
| 1990 | if (nai == null) { |
| 1991 | return null; |
| 1992 | } |
| 1993 | synchronized (nai) { |
| 1994 | return nai.linkProperties; |
| 1995 | } |
| 1996 | } |
| 1997 | |
| 1998 | private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) { |
| 1999 | return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network)); |
| 2000 | } |
| 2001 | |
| 2002 | private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) { |
| 2003 | if (nai == null) return null; |
| 2004 | synchronized (nai) { |
| 2005 | return networkCapabilitiesRestrictedForCallerPermissions( |
| 2006 | nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid()); |
| 2007 | } |
| 2008 | } |
| 2009 | |
| 2010 | @Override |
| 2011 | public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName, |
| 2012 | @Nullable String callingAttributionTag) { |
| 2013 | mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName); |
| 2014 | enforceAccessPermission(); |
| 2015 | return createWithLocationInfoSanitizedIfNecessaryWhenParceled( |
| 2016 | getNetworkCapabilitiesInternal(network), |
| 2017 | false /* includeLocationSensitiveInfo */, |
| 2018 | getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag); |
| 2019 | } |
| 2020 | |
| 2021 | @VisibleForTesting |
| 2022 | NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions( |
| 2023 | NetworkCapabilities nc, int callerPid, int callerUid) { |
| 2024 | final NetworkCapabilities newNc = new NetworkCapabilities(nc); |
| 2025 | if (!checkSettingsPermission(callerPid, callerUid)) { |
| 2026 | newNc.setUids(null); |
| 2027 | newNc.setSSID(null); |
| 2028 | } |
| 2029 | if (newNc.getNetworkSpecifier() != null) { |
| 2030 | newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact()); |
| 2031 | } |
| 2032 | newNc.setAdministratorUids(new int[0]); |
| 2033 | if (!checkAnyPermissionOf( |
| 2034 | callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) { |
| 2035 | newNc.setSubscriptionIds(Collections.emptySet()); |
| 2036 | } |
| 2037 | |
| 2038 | return newNc; |
| 2039 | } |
| 2040 | |
| 2041 | /** |
| 2042 | * Wrapper used to cache the permission check results performed for the corresponding |
| 2043 | * app. This avoid performing multiple permission checks for different fields in |
| 2044 | * NetworkCapabilities. |
| 2045 | * Note: This wrapper does not support any sort of invalidation and thus must not be |
| 2046 | * persistent or long-lived. It may only be used for the time necessary to |
| 2047 | * compute the redactions required by one particular NetworkCallback or |
| 2048 | * synchronous call. |
| 2049 | */ |
| 2050 | private class RedactionPermissionChecker { |
| 2051 | private final int mCallingPid; |
| 2052 | private final int mCallingUid; |
| 2053 | @NonNull private final String mCallingPackageName; |
| 2054 | @Nullable private final String mCallingAttributionTag; |
| 2055 | |
| 2056 | private Boolean mHasLocationPermission = null; |
| 2057 | private Boolean mHasLocalMacAddressPermission = null; |
| 2058 | private Boolean mHasSettingsPermission = null; |
| 2059 | |
| 2060 | RedactionPermissionChecker(int callingPid, int callingUid, |
| 2061 | @NonNull String callingPackageName, @Nullable String callingAttributionTag) { |
| 2062 | mCallingPid = callingPid; |
| 2063 | mCallingUid = callingUid; |
| 2064 | mCallingPackageName = callingPackageName; |
| 2065 | mCallingAttributionTag = callingAttributionTag; |
| 2066 | } |
| 2067 | |
| 2068 | private boolean hasLocationPermissionInternal() { |
| 2069 | final long token = Binder.clearCallingIdentity(); |
| 2070 | try { |
| 2071 | return mLocationPermissionChecker.checkLocationPermission( |
| 2072 | mCallingPackageName, mCallingAttributionTag, mCallingUid, |
| 2073 | null /* message */); |
| 2074 | } finally { |
| 2075 | Binder.restoreCallingIdentity(token); |
| 2076 | } |
| 2077 | } |
| 2078 | |
| 2079 | /** |
| 2080 | * Returns whether the app holds location permission or not (might return cached result |
| 2081 | * if the permission was already checked before). |
| 2082 | */ |
| 2083 | public boolean hasLocationPermission() { |
| 2084 | if (mHasLocationPermission == null) { |
| 2085 | // If there is no cached result, perform the check now. |
| 2086 | mHasLocationPermission = hasLocationPermissionInternal(); |
| 2087 | } |
| 2088 | return mHasLocationPermission; |
| 2089 | } |
| 2090 | |
| 2091 | /** |
| 2092 | * Returns whether the app holds local mac address permission or not (might return cached |
| 2093 | * result if the permission was already checked before). |
| 2094 | */ |
| 2095 | public boolean hasLocalMacAddressPermission() { |
| 2096 | if (mHasLocalMacAddressPermission == null) { |
| 2097 | // If there is no cached result, perform the check now. |
| 2098 | mHasLocalMacAddressPermission = |
| 2099 | checkLocalMacAddressPermission(mCallingPid, mCallingUid); |
| 2100 | } |
| 2101 | return mHasLocalMacAddressPermission; |
| 2102 | } |
| 2103 | |
| 2104 | /** |
| 2105 | * Returns whether the app holds settings permission or not (might return cached |
| 2106 | * result if the permission was already checked before). |
| 2107 | */ |
| 2108 | public boolean hasSettingsPermission() { |
| 2109 | if (mHasSettingsPermission == null) { |
| 2110 | // If there is no cached result, perform the check now. |
| 2111 | mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid); |
| 2112 | } |
| 2113 | return mHasSettingsPermission; |
| 2114 | } |
| 2115 | } |
| 2116 | |
| 2117 | private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions, |
| 2118 | @NetworkCapabilities.NetCapability long redaction) { |
| 2119 | return (redactions & redaction) != 0; |
| 2120 | } |
| 2121 | |
| 2122 | /** |
| 2123 | * Use the provided |applicableRedactions| to check the receiving app's |
| 2124 | * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask |
| 2125 | * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities |
| 2126 | * before being sent to the corresponding app. |
| 2127 | */ |
| 2128 | private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions( |
| 2129 | @NetworkCapabilities.RedactionType long applicableRedactions, |
| 2130 | @NonNull RedactionPermissionChecker redactionPermissionChecker, |
| 2131 | boolean includeLocationSensitiveInfo) { |
| 2132 | long redactions = applicableRedactions; |
| 2133 | if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) { |
| 2134 | if (includeLocationSensitiveInfo |
| 2135 | && redactionPermissionChecker.hasLocationPermission()) { |
| 2136 | redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION; |
| 2137 | } |
| 2138 | } |
| 2139 | if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) { |
| 2140 | if (redactionPermissionChecker.hasLocalMacAddressPermission()) { |
| 2141 | redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS; |
| 2142 | } |
| 2143 | } |
| 2144 | if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) { |
| 2145 | if (redactionPermissionChecker.hasSettingsPermission()) { |
| 2146 | redactions &= ~REDACT_FOR_NETWORK_SETTINGS; |
| 2147 | } |
| 2148 | } |
| 2149 | return redactions; |
| 2150 | } |
| 2151 | |
| 2152 | @VisibleForTesting |
| 2153 | @Nullable |
| 2154 | NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled( |
| 2155 | @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo, |
| 2156 | int callingPid, int callingUid, @NonNull String callingPkgName, |
| 2157 | @Nullable String callingAttributionTag) { |
| 2158 | if (nc == null) { |
| 2159 | return null; |
| 2160 | } |
| 2161 | // Avoid doing location permission check if the transport info has no location sensitive |
| 2162 | // data. |
| 2163 | final RedactionPermissionChecker redactionPermissionChecker = |
| 2164 | new RedactionPermissionChecker(callingPid, callingUid, callingPkgName, |
| 2165 | callingAttributionTag); |
| 2166 | final long redactions = retrieveRequiredRedactions( |
| 2167 | nc.getApplicableRedactions(), redactionPermissionChecker, |
| 2168 | includeLocationSensitiveInfo); |
| 2169 | final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions); |
| 2170 | // Reset owner uid if not destined for the owner app. |
| 2171 | if (callingUid != nc.getOwnerUid()) { |
| 2172 | newNc.setOwnerUid(INVALID_UID); |
| 2173 | return newNc; |
| 2174 | } |
| 2175 | // Allow VPNs to see ownership of their own VPN networks - not location sensitive. |
| 2176 | if (nc.hasTransport(TRANSPORT_VPN)) { |
| 2177 | // Owner UIDs already checked above. No need to re-check. |
| 2178 | return newNc; |
| 2179 | } |
| 2180 | // If the calling does not want location sensitive data & target SDK >= S, then mask info. |
| 2181 | // Else include the owner UID iff the calling has location permission to provide backwards |
| 2182 | // compatibility for older apps. |
| 2183 | if (!includeLocationSensitiveInfo |
| 2184 | && isTargetSdkAtleast( |
| 2185 | Build.VERSION_CODES.S, callingUid, callingPkgName)) { |
| 2186 | newNc.setOwnerUid(INVALID_UID); |
| 2187 | return newNc; |
| 2188 | } |
| 2189 | // Reset owner uid if the app has no location permission. |
| 2190 | if (!redactionPermissionChecker.hasLocationPermission()) { |
| 2191 | newNc.setOwnerUid(INVALID_UID); |
| 2192 | } |
| 2193 | return newNc; |
| 2194 | } |
| 2195 | |
| 2196 | private LinkProperties linkPropertiesRestrictedForCallerPermissions( |
| 2197 | LinkProperties lp, int callerPid, int callerUid) { |
| 2198 | if (lp == null) return new LinkProperties(); |
| 2199 | |
| 2200 | // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls. |
| 2201 | final boolean needsSanitization = |
| 2202 | (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null); |
| 2203 | if (!needsSanitization) { |
| 2204 | return new LinkProperties(lp); |
| 2205 | } |
| 2206 | |
| 2207 | if (checkSettingsPermission(callerPid, callerUid)) { |
| 2208 | return new LinkProperties(lp, true /* parcelSensitiveFields */); |
| 2209 | } |
| 2210 | |
| 2211 | final LinkProperties newLp = new LinkProperties(lp); |
| 2212 | // Sensitive fields would not be parceled anyway, but sanitize for consistency before the |
| 2213 | // object gets parceled. |
| 2214 | newLp.setCaptivePortalApiUrl(null); |
| 2215 | newLp.setCaptivePortalData(null); |
| 2216 | return newLp; |
| 2217 | } |
| 2218 | |
| 2219 | private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc, |
| 2220 | int callerUid, String callerPackageName) { |
Lorenzo Colitti | 86714b1 | 2021-05-17 20:31:21 +0900 | [diff] [blame] | 2221 | // There is no need to track the effective UID of the request here. If the caller |
| 2222 | // lacks the settings permission, the effective UID is the same as the calling ID. |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 2223 | if (!checkSettingsPermission()) { |
Lorenzo Colitti | 86714b1 | 2021-05-17 20:31:21 +0900 | [diff] [blame] | 2224 | // Unprivileged apps can only pass in null or their own UID. |
| 2225 | if (nc.getUids() == null) { |
| 2226 | // If the caller passes in null, the callback will also match networks that do not |
| 2227 | // apply to its UID, similarly to what it would see if it called getAllNetworks. |
| 2228 | // In this case, redact everything in the request immediately. This ensures that the |
| 2229 | // app is not able to get any redacted information by filing an unredacted request |
| 2230 | // and observing whether the request matches something. |
| 2231 | if (nc.getNetworkSpecifier() != null) { |
| 2232 | nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact()); |
| 2233 | } |
| 2234 | } else { |
| 2235 | nc.setSingleUid(callerUid); |
| 2236 | } |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 2237 | } |
| 2238 | nc.setRequestorUidAndPackageName(callerUid, callerPackageName); |
| 2239 | nc.setAdministratorUids(new int[0]); |
| 2240 | |
| 2241 | // Clear owner UID; this can never come from an app. |
| 2242 | nc.setOwnerUid(INVALID_UID); |
| 2243 | } |
| 2244 | |
| 2245 | private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) { |
| 2246 | if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) { |
| 2247 | nc.addCapability(NET_CAPABILITY_FOREGROUND); |
| 2248 | } |
| 2249 | } |
| 2250 | |
| 2251 | @Override |
| 2252 | public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() { |
| 2253 | enforceAccessPermission(); |
| 2254 | final int callerUid = Binder.getCallingUid(); |
| 2255 | final long token = Binder.clearCallingIdentity(); |
| 2256 | try { |
| 2257 | return mPolicyManager.getRestrictBackgroundStatus(callerUid); |
| 2258 | } finally { |
| 2259 | Binder.restoreCallingIdentity(token); |
| 2260 | } |
| 2261 | } |
| 2262 | |
| 2263 | // TODO: Consider delete this function or turn it into a no-op method. |
| 2264 | @Override |
| 2265 | public NetworkState[] getAllNetworkState() { |
| 2266 | // This contains IMSI details, so make sure the caller is privileged. |
| 2267 | PermissionUtils.enforceNetworkStackPermission(mContext); |
| 2268 | |
| 2269 | final ArrayList<NetworkState> result = new ArrayList<>(); |
| 2270 | for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) { |
| 2271 | // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the |
| 2272 | // NetworkAgentInfo. |
| 2273 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork()); |
| 2274 | if (nai != null && nai.networkInfo.isConnected()) { |
| 2275 | result.add(new NetworkState(new NetworkInfo(nai.networkInfo), |
| 2276 | snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(), |
| 2277 | snapshot.getNetwork(), snapshot.getSubscriberId())); |
| 2278 | } |
| 2279 | } |
| 2280 | return result.toArray(new NetworkState[result.size()]); |
| 2281 | } |
| 2282 | |
| 2283 | @Override |
| 2284 | @NonNull |
| 2285 | public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() { |
| 2286 | // This contains IMSI details, so make sure the caller is privileged. |
junyulai | 7968fba | 2021-05-14 18:04:29 +0800 | [diff] [blame] | 2287 | enforceNetworkStackOrSettingsPermission(); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 2288 | |
| 2289 | final ArrayList<NetworkStateSnapshot> result = new ArrayList<>(); |
| 2290 | for (Network network : getAllNetworks()) { |
| 2291 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 2292 | // TODO: Consider include SUSPENDED networks, which should be considered as |
| 2293 | // temporary shortage of connectivity of a connected network. |
| 2294 | if (nai != null && nai.networkInfo.isConnected()) { |
| 2295 | // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the |
| 2296 | // NetworkCapabilities, which may contain UIDs of apps to which the |
| 2297 | // network applies. Should the UIDs be cleared so as not to leak or |
| 2298 | // interfere ? |
| 2299 | result.add(nai.getNetworkStateSnapshot()); |
| 2300 | } |
| 2301 | } |
| 2302 | return result; |
| 2303 | } |
| 2304 | |
| 2305 | @Override |
| 2306 | public boolean isActiveNetworkMetered() { |
| 2307 | enforceAccessPermission(); |
| 2308 | |
| 2309 | final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork()); |
| 2310 | if (caps != null) { |
| 2311 | return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED); |
| 2312 | } else { |
| 2313 | // Always return the most conservative value |
| 2314 | return true; |
| 2315 | } |
| 2316 | } |
| 2317 | |
| 2318 | /** |
| 2319 | * Ensures that the system cannot call a particular method. |
| 2320 | */ |
| 2321 | private boolean disallowedBecauseSystemCaller() { |
| 2322 | // TODO: start throwing a SecurityException when GnssLocationProvider stops calling |
| 2323 | // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost |
| 2324 | // for devices launched with Q and above. However, existing devices upgrading to Q and |
| 2325 | // above must continued to be supported for few more releases. |
| 2326 | if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt( |
| 2327 | "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) { |
| 2328 | log("This method exists only for app backwards compatibility" |
| 2329 | + " and must not be called by system services."); |
| 2330 | return true; |
| 2331 | } |
| 2332 | return false; |
| 2333 | } |
| 2334 | |
| 2335 | /** |
| 2336 | * Ensure that a network route exists to deliver traffic to the specified |
| 2337 | * host via the specified network interface. |
| 2338 | * @param networkType the type of the network over which traffic to the |
| 2339 | * specified host is to be routed |
| 2340 | * @param hostAddress the IP address of the host to which the route is |
| 2341 | * desired |
| 2342 | * @return {@code true} on success, {@code false} on failure |
| 2343 | */ |
| 2344 | @Override |
| 2345 | public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress, |
| 2346 | String callingPackageName, String callingAttributionTag) { |
| 2347 | if (disallowedBecauseSystemCaller()) { |
| 2348 | return false; |
| 2349 | } |
| 2350 | enforceChangePermission(callingPackageName, callingAttributionTag); |
| 2351 | if (mProtectedNetworks.contains(networkType)) { |
| 2352 | enforceConnectivityRestrictedNetworksPermission(); |
| 2353 | } |
| 2354 | |
| 2355 | InetAddress addr; |
| 2356 | try { |
| 2357 | addr = InetAddress.getByAddress(hostAddress); |
| 2358 | } catch (UnknownHostException e) { |
| 2359 | if (DBG) log("requestRouteToHostAddress got " + e.toString()); |
| 2360 | return false; |
| 2361 | } |
| 2362 | |
| 2363 | if (!ConnectivityManager.isNetworkTypeValid(networkType)) { |
| 2364 | if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType); |
| 2365 | return false; |
| 2366 | } |
| 2367 | |
| 2368 | NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); |
| 2369 | if (nai == null) { |
| 2370 | if (mLegacyTypeTracker.isTypeSupported(networkType) == false) { |
| 2371 | if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType); |
| 2372 | } else { |
| 2373 | if (DBG) log("requestRouteToHostAddress on down network: " + networkType); |
| 2374 | } |
| 2375 | return false; |
| 2376 | } |
| 2377 | |
| 2378 | DetailedState netState; |
| 2379 | synchronized (nai) { |
| 2380 | netState = nai.networkInfo.getDetailedState(); |
| 2381 | } |
| 2382 | |
| 2383 | if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) { |
| 2384 | if (VDBG) { |
| 2385 | log("requestRouteToHostAddress on down network " |
| 2386 | + "(" + networkType + ") - dropped" |
| 2387 | + " netState=" + netState); |
| 2388 | } |
| 2389 | return false; |
| 2390 | } |
| 2391 | |
| 2392 | final int uid = mDeps.getCallingUid(); |
| 2393 | final long token = Binder.clearCallingIdentity(); |
| 2394 | try { |
| 2395 | LinkProperties lp; |
| 2396 | int netId; |
| 2397 | synchronized (nai) { |
| 2398 | lp = nai.linkProperties; |
| 2399 | netId = nai.network.getNetId(); |
| 2400 | } |
| 2401 | boolean ok = addLegacyRouteToHost(lp, addr, netId, uid); |
| 2402 | if (DBG) { |
| 2403 | log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok); |
| 2404 | } |
| 2405 | return ok; |
| 2406 | } finally { |
| 2407 | Binder.restoreCallingIdentity(token); |
| 2408 | } |
| 2409 | } |
| 2410 | |
| 2411 | private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) { |
| 2412 | RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr); |
| 2413 | if (bestRoute == null) { |
| 2414 | bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName()); |
| 2415 | } else { |
| 2416 | String iface = bestRoute.getInterface(); |
| 2417 | if (bestRoute.getGateway().equals(addr)) { |
| 2418 | // if there is no better route, add the implied hostroute for our gateway |
| 2419 | bestRoute = RouteInfo.makeHostRoute(addr, iface); |
| 2420 | } else { |
| 2421 | // if we will connect to this through another route, add a direct route |
| 2422 | // to it's gateway |
| 2423 | bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface); |
| 2424 | } |
| 2425 | } |
| 2426 | if (DBG) log("Adding legacy route " + bestRoute + |
| 2427 | " for UID/PID " + uid + "/" + Binder.getCallingPid()); |
| 2428 | |
| 2429 | final String dst = bestRoute.getDestinationLinkAddress().toString(); |
| 2430 | final String nextHop = bestRoute.hasGateway() |
| 2431 | ? bestRoute.getGateway().getHostAddress() : ""; |
| 2432 | try { |
| 2433 | mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid); |
| 2434 | } catch (RemoteException | ServiceSpecificException e) { |
| 2435 | if (DBG) loge("Exception trying to add a route: " + e); |
| 2436 | return false; |
| 2437 | } |
| 2438 | return true; |
| 2439 | } |
| 2440 | |
| 2441 | class DnsResolverUnsolicitedEventCallback extends |
| 2442 | IDnsResolverUnsolicitedEventListener.Stub { |
| 2443 | @Override |
| 2444 | public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) { |
| 2445 | try { |
| 2446 | mHandler.sendMessage(mHandler.obtainMessage( |
| 2447 | EVENT_PRIVATE_DNS_VALIDATION_UPDATE, |
| 2448 | new PrivateDnsValidationUpdate(event.netId, |
| 2449 | InetAddresses.parseNumericAddress(event.ipAddress), |
| 2450 | event.hostname, event.validation))); |
| 2451 | } catch (IllegalArgumentException e) { |
| 2452 | loge("Error parsing ip address in validation event"); |
| 2453 | } |
| 2454 | } |
| 2455 | |
| 2456 | @Override |
| 2457 | public void onDnsHealthEvent(final DnsHealthEventParcel event) { |
| 2458 | NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId); |
| 2459 | // Netd event only allow registrants from system. Each NetworkMonitor thread is under |
| 2460 | // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd |
| 2461 | // event callback for certain nai. e.g. cellular. Register here to pass to |
| 2462 | // NetworkMonitor instead. |
| 2463 | // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one |
| 2464 | // callback from each caller type. Need to re-factor NetdEventListenerService to allow |
| 2465 | // multiple NetworkMonitor registrants. |
| 2466 | if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) { |
| 2467 | nai.networkMonitor().notifyDnsResponse(event.healthResult); |
| 2468 | } |
| 2469 | } |
| 2470 | |
| 2471 | @Override |
| 2472 | public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) { |
| 2473 | mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation, |
| 2474 | event.prefixAddress, event.prefixLength)); |
| 2475 | } |
| 2476 | |
| 2477 | @Override |
| 2478 | public int getInterfaceVersion() { |
| 2479 | return this.VERSION; |
| 2480 | } |
| 2481 | |
| 2482 | @Override |
| 2483 | public String getInterfaceHash() { |
| 2484 | return this.HASH; |
| 2485 | } |
| 2486 | } |
| 2487 | |
| 2488 | @VisibleForTesting |
| 2489 | protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback = |
| 2490 | new DnsResolverUnsolicitedEventCallback(); |
| 2491 | |
| 2492 | private void registerDnsResolverUnsolicitedEventListener() { |
| 2493 | try { |
| 2494 | mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback); |
| 2495 | } catch (Exception e) { |
| 2496 | loge("Error registering DnsResolver unsolicited event callback: " + e); |
| 2497 | } |
| 2498 | } |
| 2499 | |
| 2500 | private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() { |
| 2501 | @Override |
| 2502 | public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) { |
| 2503 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED, |
| 2504 | uid, blockedReasons)); |
| 2505 | } |
| 2506 | }; |
| 2507 | |
| 2508 | private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) { |
| 2509 | maybeNotifyNetworkBlockedForNewState(uid, blockedReasons); |
| 2510 | setUidBlockedReasons(uid, blockedReasons); |
| 2511 | } |
| 2512 | |
| 2513 | private boolean checkAnyPermissionOf(String... permissions) { |
| 2514 | for (String permission : permissions) { |
| 2515 | if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) { |
| 2516 | return true; |
| 2517 | } |
| 2518 | } |
| 2519 | return false; |
| 2520 | } |
| 2521 | |
| 2522 | private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) { |
| 2523 | for (String permission : permissions) { |
| 2524 | if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) { |
| 2525 | return true; |
| 2526 | } |
| 2527 | } |
| 2528 | return false; |
| 2529 | } |
| 2530 | |
| 2531 | private void enforceAnyPermissionOf(String... permissions) { |
| 2532 | if (!checkAnyPermissionOf(permissions)) { |
| 2533 | throw new SecurityException("Requires one of the following permissions: " |
| 2534 | + String.join(", ", permissions) + "."); |
| 2535 | } |
| 2536 | } |
| 2537 | |
| 2538 | private void enforceInternetPermission() { |
| 2539 | mContext.enforceCallingOrSelfPermission( |
| 2540 | android.Manifest.permission.INTERNET, |
| 2541 | "ConnectivityService"); |
| 2542 | } |
| 2543 | |
| 2544 | private void enforceAccessPermission() { |
| 2545 | mContext.enforceCallingOrSelfPermission( |
| 2546 | android.Manifest.permission.ACCESS_NETWORK_STATE, |
| 2547 | "ConnectivityService"); |
| 2548 | } |
| 2549 | |
| 2550 | /** |
| 2551 | * Performs a strict and comprehensive check of whether a calling package is allowed to |
| 2552 | * change the state of network, as the condition differs for pre-M, M+, and |
| 2553 | * privileged/preinstalled apps. The caller is expected to have either the |
| 2554 | * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these |
| 2555 | * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and |
| 2556 | * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal |
| 2557 | * permission and cannot be revoked. See http://b/23597341 |
| 2558 | * |
| 2559 | * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation |
| 2560 | * of this app will be updated to the current time. |
| 2561 | */ |
| 2562 | private void enforceChangePermission(String callingPkg, String callingAttributionTag) { |
| 2563 | if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE) |
| 2564 | == PackageManager.PERMISSION_GRANTED) { |
| 2565 | return; |
| 2566 | } |
| 2567 | |
| 2568 | if (callingPkg == null) { |
| 2569 | throw new SecurityException("Calling package name is null."); |
| 2570 | } |
| 2571 | |
| 2572 | final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class); |
| 2573 | final int uid = mDeps.getCallingUid(); |
| 2574 | final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid, |
| 2575 | callingPkg, callingAttributionTag, null /* message */); |
| 2576 | |
| 2577 | if (mode == AppOpsManager.MODE_ALLOWED) { |
| 2578 | return; |
| 2579 | } |
| 2580 | |
| 2581 | if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission( |
| 2582 | android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) { |
| 2583 | return; |
| 2584 | } |
| 2585 | |
| 2586 | throw new SecurityException(callingPkg + " was not granted either of these permissions:" |
| 2587 | + android.Manifest.permission.CHANGE_NETWORK_STATE + "," |
| 2588 | + android.Manifest.permission.WRITE_SETTINGS + "."); |
| 2589 | } |
| 2590 | |
| 2591 | private void enforceSettingsPermission() { |
| 2592 | enforceAnyPermissionOf( |
| 2593 | android.Manifest.permission.NETWORK_SETTINGS, |
| 2594 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK); |
| 2595 | } |
| 2596 | |
| 2597 | private void enforceNetworkFactoryPermission() { |
| 2598 | enforceAnyPermissionOf( |
| 2599 | android.Manifest.permission.NETWORK_FACTORY, |
| 2600 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK); |
| 2601 | } |
| 2602 | |
| 2603 | private void enforceNetworkFactoryOrSettingsPermission() { |
| 2604 | enforceAnyPermissionOf( |
| 2605 | android.Manifest.permission.NETWORK_SETTINGS, |
| 2606 | android.Manifest.permission.NETWORK_FACTORY, |
| 2607 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK); |
| 2608 | } |
| 2609 | |
| 2610 | private void enforceNetworkFactoryOrTestNetworksPermission() { |
| 2611 | enforceAnyPermissionOf( |
| 2612 | android.Manifest.permission.MANAGE_TEST_NETWORKS, |
| 2613 | android.Manifest.permission.NETWORK_FACTORY, |
| 2614 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK); |
| 2615 | } |
| 2616 | |
| 2617 | private boolean checkSettingsPermission() { |
| 2618 | return checkAnyPermissionOf( |
| 2619 | android.Manifest.permission.NETWORK_SETTINGS, |
| 2620 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK); |
| 2621 | } |
| 2622 | |
| 2623 | private boolean checkSettingsPermission(int pid, int uid) { |
| 2624 | return PERMISSION_GRANTED == mContext.checkPermission( |
| 2625 | android.Manifest.permission.NETWORK_SETTINGS, pid, uid) |
| 2626 | || PERMISSION_GRANTED == mContext.checkPermission( |
| 2627 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid); |
| 2628 | } |
| 2629 | |
| 2630 | private void enforceNetworkStackOrSettingsPermission() { |
| 2631 | enforceAnyPermissionOf( |
| 2632 | android.Manifest.permission.NETWORK_SETTINGS, |
| 2633 | android.Manifest.permission.NETWORK_STACK, |
| 2634 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK); |
| 2635 | } |
| 2636 | |
| 2637 | private void enforceNetworkStackSettingsOrSetup() { |
| 2638 | enforceAnyPermissionOf( |
| 2639 | android.Manifest.permission.NETWORK_SETTINGS, |
| 2640 | android.Manifest.permission.NETWORK_SETUP_WIZARD, |
| 2641 | android.Manifest.permission.NETWORK_STACK, |
| 2642 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK); |
| 2643 | } |
| 2644 | |
| 2645 | private void enforceAirplaneModePermission() { |
| 2646 | enforceAnyPermissionOf( |
| 2647 | android.Manifest.permission.NETWORK_AIRPLANE_MODE, |
| 2648 | android.Manifest.permission.NETWORK_SETTINGS, |
| 2649 | android.Manifest.permission.NETWORK_SETUP_WIZARD, |
| 2650 | android.Manifest.permission.NETWORK_STACK, |
| 2651 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK); |
| 2652 | } |
| 2653 | |
| 2654 | private void enforceOemNetworkPreferencesPermission() { |
| 2655 | mContext.enforceCallingOrSelfPermission( |
| 2656 | android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE, |
| 2657 | "ConnectivityService"); |
| 2658 | } |
| 2659 | |
James Mattis | b7ca034 | 2021-06-16 01:30:05 +0000 | [diff] [blame] | 2660 | private void enforceManageTestNetworksPermission() { |
| 2661 | mContext.enforceCallingOrSelfPermission( |
| 2662 | android.Manifest.permission.MANAGE_TEST_NETWORKS, |
| 2663 | "ConnectivityService"); |
| 2664 | } |
| 2665 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 2666 | private boolean checkNetworkStackPermission() { |
| 2667 | return checkAnyPermissionOf( |
| 2668 | android.Manifest.permission.NETWORK_STACK, |
| 2669 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK); |
| 2670 | } |
| 2671 | |
| 2672 | private boolean checkNetworkStackPermission(int pid, int uid) { |
| 2673 | return checkAnyPermissionOf(pid, uid, |
| 2674 | android.Manifest.permission.NETWORK_STACK, |
| 2675 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK); |
| 2676 | } |
| 2677 | |
| 2678 | private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) { |
| 2679 | return checkAnyPermissionOf(pid, uid, |
| 2680 | android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP, |
| 2681 | NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, |
| 2682 | android.Manifest.permission.NETWORK_SETTINGS); |
| 2683 | } |
| 2684 | |
| 2685 | private void enforceConnectivityRestrictedNetworksPermission() { |
| 2686 | try { |
| 2687 | mContext.enforceCallingOrSelfPermission( |
| 2688 | android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS, |
| 2689 | "ConnectivityService"); |
| 2690 | return; |
| 2691 | } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ } |
| 2692 | // TODO: Remove this fallback check after all apps have declared |
| 2693 | // CONNECTIVITY_USE_RESTRICTED_NETWORKS. |
| 2694 | mContext.enforceCallingOrSelfPermission( |
| 2695 | android.Manifest.permission.CONNECTIVITY_INTERNAL, |
| 2696 | "ConnectivityService"); |
| 2697 | } |
| 2698 | |
| 2699 | private void enforceKeepalivePermission() { |
| 2700 | mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService"); |
| 2701 | } |
| 2702 | |
| 2703 | private boolean checkLocalMacAddressPermission(int pid, int uid) { |
| 2704 | return PERMISSION_GRANTED == mContext.checkPermission( |
| 2705 | Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid); |
| 2706 | } |
| 2707 | |
| 2708 | private void sendConnectedBroadcast(NetworkInfo info) { |
| 2709 | sendGeneralBroadcast(info, CONNECTIVITY_ACTION); |
| 2710 | } |
| 2711 | |
| 2712 | private void sendInetConditionBroadcast(NetworkInfo info) { |
| 2713 | sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION); |
| 2714 | } |
| 2715 | |
| 2716 | private Intent makeGeneralIntent(NetworkInfo info, String bcastType) { |
| 2717 | Intent intent = new Intent(bcastType); |
| 2718 | intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info)); |
| 2719 | intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); |
| 2720 | if (info.isFailover()) { |
| 2721 | intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); |
| 2722 | info.setFailover(false); |
| 2723 | } |
| 2724 | if (info.getReason() != null) { |
| 2725 | intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); |
| 2726 | } |
| 2727 | if (info.getExtraInfo() != null) { |
| 2728 | intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, |
| 2729 | info.getExtraInfo()); |
| 2730 | } |
| 2731 | intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished); |
| 2732 | return intent; |
| 2733 | } |
| 2734 | |
| 2735 | private void sendGeneralBroadcast(NetworkInfo info, String bcastType) { |
| 2736 | sendStickyBroadcast(makeGeneralIntent(info, bcastType)); |
| 2737 | } |
| 2738 | |
| 2739 | private void sendStickyBroadcast(Intent intent) { |
| 2740 | synchronized (this) { |
| 2741 | if (!mSystemReady |
| 2742 | && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { |
| 2743 | mInitialBroadcast = new Intent(intent); |
| 2744 | } |
| 2745 | intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); |
| 2746 | if (VDBG) { |
| 2747 | log("sendStickyBroadcast: action=" + intent.getAction()); |
| 2748 | } |
| 2749 | |
| 2750 | Bundle options = null; |
| 2751 | final long ident = Binder.clearCallingIdentity(); |
| 2752 | if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { |
| 2753 | final NetworkInfo ni = intent.getParcelableExtra( |
| 2754 | ConnectivityManager.EXTRA_NETWORK_INFO); |
| 2755 | final BroadcastOptions opts = BroadcastOptions.makeBasic(); |
| 2756 | opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M); |
| 2757 | options = opts.toBundle(); |
| 2758 | intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS); |
| 2759 | } |
| 2760 | try { |
| 2761 | mUserAllContext.sendStickyBroadcast(intent, options); |
| 2762 | } finally { |
| 2763 | Binder.restoreCallingIdentity(ident); |
| 2764 | } |
| 2765 | } |
| 2766 | } |
| 2767 | |
| 2768 | /** |
| 2769 | * Called by SystemServer through ConnectivityManager when the system is ready. |
| 2770 | */ |
| 2771 | @Override |
| 2772 | public void systemReady() { |
| 2773 | if (mDeps.getCallingUid() != Process.SYSTEM_UID) { |
| 2774 | throw new SecurityException("Calling Uid is not system uid."); |
| 2775 | } |
| 2776 | systemReadyInternal(); |
| 2777 | } |
| 2778 | |
| 2779 | /** |
| 2780 | * Called when ConnectivityService can initialize remaining components. |
| 2781 | */ |
| 2782 | @VisibleForTesting |
| 2783 | public void systemReadyInternal() { |
| 2784 | // Since mApps in PermissionMonitor needs to be populated first to ensure that |
| 2785 | // listening network request which is sent by MultipathPolicyTracker won't be added |
| 2786 | // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must |
| 2787 | // be called after PermissionMonitor#startMonitoring(). |
| 2788 | // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the |
| 2789 | // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady() |
| 2790 | // to ensure the tracking will be initialized correctly. |
| 2791 | mPermissionMonitor.startMonitoring(); |
| 2792 | mProxyTracker.loadGlobalProxy(); |
| 2793 | registerDnsResolverUnsolicitedEventListener(); |
| 2794 | |
| 2795 | synchronized (this) { |
| 2796 | mSystemReady = true; |
| 2797 | if (mInitialBroadcast != null) { |
| 2798 | mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL); |
| 2799 | mInitialBroadcast = null; |
| 2800 | } |
| 2801 | } |
| 2802 | |
| 2803 | // Create network requests for always-on networks. |
| 2804 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS)); |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 2805 | |
| 2806 | // Update mobile data preference if necessary. |
| 2807 | // Note that empty uid list can be skip here only because no uid rules applied before system |
| 2808 | // ready. Normally, the empty uid list means to clear the uids rules on netd. |
| 2809 | if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) { |
| 2810 | updateMobileDataPreferredUids(); |
| 2811 | } |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 2812 | } |
| 2813 | |
| 2814 | /** |
| 2815 | * Start listening for default data network activity state changes. |
| 2816 | */ |
| 2817 | @Override |
| 2818 | public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) { |
| 2819 | mNetworkActivityTracker.registerNetworkActivityListener(l); |
| 2820 | } |
| 2821 | |
| 2822 | /** |
| 2823 | * Stop listening for default data network activity state changes. |
| 2824 | */ |
| 2825 | @Override |
| 2826 | public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) { |
| 2827 | mNetworkActivityTracker.unregisterNetworkActivityListener(l); |
| 2828 | } |
| 2829 | |
| 2830 | /** |
| 2831 | * Check whether the default network radio is currently active. |
| 2832 | */ |
| 2833 | @Override |
| 2834 | public boolean isDefaultNetworkActive() { |
| 2835 | return mNetworkActivityTracker.isDefaultNetworkActive(); |
| 2836 | } |
| 2837 | |
| 2838 | /** |
| 2839 | * Reads the network specific MTU size from resources. |
| 2840 | * and set it on it's iface. |
| 2841 | */ |
| 2842 | private void updateMtu(LinkProperties newLp, LinkProperties oldLp) { |
| 2843 | final String iface = newLp.getInterfaceName(); |
| 2844 | final int mtu = newLp.getMtu(); |
| 2845 | if (oldLp == null && mtu == 0) { |
| 2846 | // Silently ignore unset MTU value. |
| 2847 | return; |
| 2848 | } |
| 2849 | if (oldLp != null && newLp.isIdenticalMtu(oldLp)) { |
| 2850 | if (VDBG) log("identical MTU - not setting"); |
| 2851 | return; |
| 2852 | } |
| 2853 | if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) { |
| 2854 | if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface); |
| 2855 | return; |
| 2856 | } |
| 2857 | |
| 2858 | // Cannot set MTU without interface name |
| 2859 | if (TextUtils.isEmpty(iface)) { |
| 2860 | loge("Setting MTU size with null iface."); |
| 2861 | return; |
| 2862 | } |
| 2863 | |
| 2864 | try { |
| 2865 | if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu); |
| 2866 | mNetd.interfaceSetMtu(iface, mtu); |
| 2867 | } catch (RemoteException | ServiceSpecificException e) { |
| 2868 | loge("exception in interfaceSetMtu()" + e); |
| 2869 | } |
| 2870 | } |
| 2871 | |
| 2872 | @VisibleForTesting |
| 2873 | protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208"; |
| 2874 | |
| 2875 | private void updateTcpBufferSizes(String tcpBufferSizes) { |
| 2876 | String[] values = null; |
| 2877 | if (tcpBufferSizes != null) { |
| 2878 | values = tcpBufferSizes.split(","); |
| 2879 | } |
| 2880 | |
| 2881 | if (values == null || values.length != 6) { |
| 2882 | if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults"); |
| 2883 | tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES; |
| 2884 | values = tcpBufferSizes.split(","); |
| 2885 | } |
| 2886 | |
| 2887 | if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return; |
| 2888 | |
| 2889 | try { |
| 2890 | if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes); |
| 2891 | |
| 2892 | String rmemValues = String.join(" ", values[0], values[1], values[2]); |
| 2893 | String wmemValues = String.join(" ", values[3], values[4], values[5]); |
| 2894 | mNetd.setTcpRWmemorySize(rmemValues, wmemValues); |
| 2895 | mCurrentTcpBufferSizes = tcpBufferSizes; |
| 2896 | } catch (RemoteException | ServiceSpecificException e) { |
| 2897 | loge("Can't set TCP buffer sizes:" + e); |
| 2898 | } |
| 2899 | } |
| 2900 | |
| 2901 | @Override |
| 2902 | public int getRestoreDefaultNetworkDelay(int networkType) { |
| 2903 | String restoreDefaultNetworkDelayStr = mSystemProperties.get( |
| 2904 | NETWORK_RESTORE_DELAY_PROP_NAME); |
| 2905 | if(restoreDefaultNetworkDelayStr != null && |
| 2906 | restoreDefaultNetworkDelayStr.length() != 0) { |
| 2907 | try { |
| 2908 | return Integer.parseInt(restoreDefaultNetworkDelayStr); |
| 2909 | } catch (NumberFormatException e) { |
| 2910 | } |
| 2911 | } |
| 2912 | // if the system property isn't set, use the value for the apn type |
| 2913 | int ret = RESTORE_DEFAULT_NETWORK_DELAY; |
| 2914 | |
| 2915 | if (mLegacyTypeTracker.isTypeSupported(networkType)) { |
| 2916 | ret = mLegacyTypeTracker.getRestoreTimerForType(networkType); |
| 2917 | } |
| 2918 | return ret; |
| 2919 | } |
| 2920 | |
| 2921 | private void dumpNetworkDiagnostics(IndentingPrintWriter pw) { |
| 2922 | final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>(); |
| 2923 | final long DIAG_TIME_MS = 5000; |
| 2924 | for (NetworkAgentInfo nai : networksSortedById()) { |
| 2925 | PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network); |
| 2926 | // Start gathering diagnostic information. |
| 2927 | netDiags.add(new NetworkDiagnostics( |
| 2928 | nai.network, |
| 2929 | new LinkProperties(nai.linkProperties), // Must be a copy. |
| 2930 | privateDnsCfg, |
| 2931 | DIAG_TIME_MS)); |
| 2932 | } |
| 2933 | |
| 2934 | for (NetworkDiagnostics netDiag : netDiags) { |
| 2935 | pw.println(); |
| 2936 | netDiag.waitForMeasurements(); |
| 2937 | netDiag.dump(pw); |
| 2938 | } |
| 2939 | } |
| 2940 | |
| 2941 | @Override |
| 2942 | protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer, |
| 2943 | @Nullable String[] args) { |
| 2944 | if (!checkDumpPermission(mContext, TAG, writer)) return; |
| 2945 | |
| 2946 | mPriorityDumper.dump(fd, writer, args); |
| 2947 | } |
| 2948 | |
| 2949 | private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) { |
| 2950 | if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) |
| 2951 | != PackageManager.PERMISSION_GRANTED) { |
| 2952 | pw.println("Permission Denial: can't dump " + tag + " from from pid=" |
| 2953 | + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid() |
| 2954 | + " due to missing android.permission.DUMP permission"); |
| 2955 | return false; |
| 2956 | } else { |
| 2957 | return true; |
| 2958 | } |
| 2959 | } |
| 2960 | |
| 2961 | private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) { |
| 2962 | final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); |
| 2963 | |
| 2964 | if (CollectionUtils.contains(args, DIAG_ARG)) { |
| 2965 | dumpNetworkDiagnostics(pw); |
| 2966 | return; |
| 2967 | } else if (CollectionUtils.contains(args, NETWORK_ARG)) { |
| 2968 | dumpNetworks(pw); |
| 2969 | return; |
| 2970 | } else if (CollectionUtils.contains(args, REQUEST_ARG)) { |
| 2971 | dumpNetworkRequests(pw); |
| 2972 | return; |
| 2973 | } |
| 2974 | |
| 2975 | pw.print("NetworkProviders for:"); |
| 2976 | for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) { |
| 2977 | pw.print(" " + npi.name); |
| 2978 | } |
| 2979 | pw.println(); |
| 2980 | pw.println(); |
| 2981 | |
| 2982 | final NetworkAgentInfo defaultNai = getDefaultNetwork(); |
| 2983 | pw.print("Active default network: "); |
| 2984 | if (defaultNai == null) { |
| 2985 | pw.println("none"); |
| 2986 | } else { |
| 2987 | pw.println(defaultNai.network.getNetId()); |
| 2988 | } |
| 2989 | pw.println(); |
| 2990 | |
| 2991 | pw.print("Current per-app default networks: "); |
| 2992 | pw.increaseIndent(); |
| 2993 | dumpPerAppNetworkPreferences(pw); |
| 2994 | pw.decreaseIndent(); |
| 2995 | pw.println(); |
| 2996 | |
| 2997 | pw.println("Current Networks:"); |
| 2998 | pw.increaseIndent(); |
| 2999 | dumpNetworks(pw); |
| 3000 | pw.decreaseIndent(); |
| 3001 | pw.println(); |
| 3002 | |
| 3003 | pw.println("Status for known UIDs:"); |
| 3004 | pw.increaseIndent(); |
| 3005 | final int size = mUidBlockedReasons.size(); |
| 3006 | for (int i = 0; i < size; i++) { |
| 3007 | // Don't crash if the array is modified while dumping in bugreports. |
| 3008 | try { |
| 3009 | final int uid = mUidBlockedReasons.keyAt(i); |
| 3010 | final int blockedReasons = mUidBlockedReasons.valueAt(i); |
| 3011 | pw.println("UID=" + uid + " blockedReasons=" |
| 3012 | + Integer.toHexString(blockedReasons)); |
| 3013 | } catch (ArrayIndexOutOfBoundsException e) { |
| 3014 | pw.println(" ArrayIndexOutOfBoundsException"); |
| 3015 | } catch (ConcurrentModificationException e) { |
| 3016 | pw.println(" ConcurrentModificationException"); |
| 3017 | } |
| 3018 | } |
| 3019 | pw.println(); |
| 3020 | pw.decreaseIndent(); |
| 3021 | |
| 3022 | pw.println("Network Requests:"); |
| 3023 | pw.increaseIndent(); |
| 3024 | dumpNetworkRequests(pw); |
| 3025 | pw.decreaseIndent(); |
| 3026 | pw.println(); |
| 3027 | |
| 3028 | mLegacyTypeTracker.dump(pw); |
| 3029 | |
| 3030 | pw.println(); |
| 3031 | mKeepaliveTracker.dump(pw); |
| 3032 | |
| 3033 | pw.println(); |
| 3034 | dumpAvoidBadWifiSettings(pw); |
| 3035 | |
| 3036 | pw.println(); |
| 3037 | |
| 3038 | if (!CollectionUtils.contains(args, SHORT_ARG)) { |
| 3039 | pw.println(); |
| 3040 | pw.println("mNetworkRequestInfoLogs (most recent first):"); |
| 3041 | pw.increaseIndent(); |
| 3042 | mNetworkRequestInfoLogs.reverseDump(pw); |
| 3043 | pw.decreaseIndent(); |
| 3044 | |
| 3045 | pw.println(); |
| 3046 | pw.println("mNetworkInfoBlockingLogs (most recent first):"); |
| 3047 | pw.increaseIndent(); |
| 3048 | mNetworkInfoBlockingLogs.reverseDump(pw); |
| 3049 | pw.decreaseIndent(); |
| 3050 | |
| 3051 | pw.println(); |
| 3052 | pw.println("NetTransition WakeLock activity (most recent first):"); |
| 3053 | pw.increaseIndent(); |
| 3054 | pw.println("total acquisitions: " + mTotalWakelockAcquisitions); |
| 3055 | pw.println("total releases: " + mTotalWakelockReleases); |
| 3056 | pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s"); |
| 3057 | pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s"); |
| 3058 | if (mTotalWakelockAcquisitions > mTotalWakelockReleases) { |
| 3059 | long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp; |
| 3060 | pw.println("currently holding WakeLock for: " + (duration / 1000) + "s"); |
| 3061 | } |
| 3062 | mWakelockLogs.reverseDump(pw); |
| 3063 | |
| 3064 | pw.println(); |
| 3065 | pw.println("bandwidth update requests (by uid):"); |
| 3066 | pw.increaseIndent(); |
| 3067 | synchronized (mBandwidthRequests) { |
| 3068 | for (int i = 0; i < mBandwidthRequests.size(); i++) { |
| 3069 | pw.println("[" + mBandwidthRequests.keyAt(i) |
| 3070 | + "]: " + mBandwidthRequests.valueAt(i)); |
| 3071 | } |
| 3072 | } |
| 3073 | pw.decreaseIndent(); |
| 3074 | pw.decreaseIndent(); |
| 3075 | |
| 3076 | pw.println(); |
| 3077 | pw.println("mOemNetworkPreferencesLogs (most recent first):"); |
| 3078 | pw.increaseIndent(); |
| 3079 | mOemNetworkPreferencesLogs.reverseDump(pw); |
| 3080 | pw.decreaseIndent(); |
| 3081 | } |
| 3082 | |
| 3083 | pw.println(); |
| 3084 | |
| 3085 | pw.println(); |
| 3086 | pw.println("Permission Monitor:"); |
| 3087 | pw.increaseIndent(); |
| 3088 | mPermissionMonitor.dump(pw); |
| 3089 | pw.decreaseIndent(); |
| 3090 | |
| 3091 | pw.println(); |
| 3092 | pw.println("Legacy network activity:"); |
| 3093 | pw.increaseIndent(); |
| 3094 | mNetworkActivityTracker.dump(pw); |
| 3095 | pw.decreaseIndent(); |
| 3096 | } |
| 3097 | |
| 3098 | private void dumpNetworks(IndentingPrintWriter pw) { |
| 3099 | for (NetworkAgentInfo nai : networksSortedById()) { |
| 3100 | pw.println(nai.toString()); |
| 3101 | pw.increaseIndent(); |
| 3102 | pw.println(String.format( |
| 3103 | "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d", |
| 3104 | nai.numForegroundNetworkRequests(), |
| 3105 | nai.numNetworkRequests() - nai.numRequestNetworkRequests(), |
| 3106 | nai.numBackgroundNetworkRequests(), |
| 3107 | nai.numNetworkRequests())); |
| 3108 | pw.increaseIndent(); |
| 3109 | for (int i = 0; i < nai.numNetworkRequests(); i++) { |
| 3110 | pw.println(nai.requestAt(i).toString()); |
| 3111 | } |
| 3112 | pw.decreaseIndent(); |
| 3113 | pw.println("Inactivity Timers:"); |
| 3114 | pw.increaseIndent(); |
| 3115 | nai.dumpInactivityTimers(pw); |
| 3116 | pw.decreaseIndent(); |
| 3117 | pw.decreaseIndent(); |
| 3118 | } |
| 3119 | } |
| 3120 | |
| 3121 | private void dumpPerAppNetworkPreferences(IndentingPrintWriter pw) { |
| 3122 | pw.println("Per-App Network Preference:"); |
| 3123 | pw.increaseIndent(); |
| 3124 | if (0 == mOemNetworkPreferences.getNetworkPreferences().size()) { |
| 3125 | pw.println("none"); |
| 3126 | } else { |
| 3127 | pw.println(mOemNetworkPreferences.toString()); |
| 3128 | } |
| 3129 | pw.decreaseIndent(); |
| 3130 | |
| 3131 | for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) { |
| 3132 | if (mDefaultRequest == defaultRequest) { |
| 3133 | continue; |
| 3134 | } |
| 3135 | |
| 3136 | final boolean isActive = null != defaultRequest.getSatisfier(); |
| 3137 | pw.println("Is per-app network active:"); |
| 3138 | pw.increaseIndent(); |
| 3139 | pw.println(isActive); |
| 3140 | if (isActive) { |
| 3141 | pw.println("Active network: " + defaultRequest.getSatisfier().network.netId); |
| 3142 | } |
| 3143 | pw.println("Tracked UIDs:"); |
| 3144 | pw.increaseIndent(); |
| 3145 | if (0 == defaultRequest.mRequests.size()) { |
| 3146 | pw.println("none, this should never occur."); |
| 3147 | } else { |
| 3148 | pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges()); |
| 3149 | } |
| 3150 | pw.decreaseIndent(); |
| 3151 | pw.decreaseIndent(); |
| 3152 | } |
| 3153 | } |
| 3154 | |
| 3155 | private void dumpNetworkRequests(IndentingPrintWriter pw) { |
| 3156 | for (NetworkRequestInfo nri : requestsSortedById()) { |
| 3157 | pw.println(nri.toString()); |
| 3158 | } |
| 3159 | } |
| 3160 | |
| 3161 | /** |
| 3162 | * Return an array of all current NetworkAgentInfos sorted by network id. |
| 3163 | */ |
| 3164 | private NetworkAgentInfo[] networksSortedById() { |
| 3165 | NetworkAgentInfo[] networks = new NetworkAgentInfo[0]; |
| 3166 | networks = mNetworkAgentInfos.toArray(networks); |
| 3167 | Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId())); |
| 3168 | return networks; |
| 3169 | } |
| 3170 | |
| 3171 | /** |
| 3172 | * Return an array of all current NetworkRequest sorted by request id. |
| 3173 | */ |
| 3174 | @VisibleForTesting |
| 3175 | NetworkRequestInfo[] requestsSortedById() { |
| 3176 | NetworkRequestInfo[] requests = new NetworkRequestInfo[0]; |
| 3177 | requests = getNrisFromGlobalRequests().toArray(requests); |
| 3178 | // Sort the array based off the NRI containing the min requestId in its requests. |
| 3179 | Arrays.sort(requests, |
| 3180 | Comparator.comparingInt(nri -> Collections.min(nri.mRequests, |
| 3181 | Comparator.comparingInt(req -> req.requestId)).requestId |
| 3182 | ) |
| 3183 | ); |
| 3184 | return requests; |
| 3185 | } |
| 3186 | |
| 3187 | private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) { |
| 3188 | final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network); |
| 3189 | if (officialNai != null && officialNai.equals(nai)) return true; |
| 3190 | if (officialNai != null || VDBG) { |
| 3191 | loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai + |
| 3192 | " - " + nai); |
| 3193 | } |
| 3194 | return false; |
| 3195 | } |
| 3196 | |
| 3197 | // must be stateless - things change under us. |
| 3198 | private class NetworkStateTrackerHandler extends Handler { |
| 3199 | public NetworkStateTrackerHandler(Looper looper) { |
| 3200 | super(looper); |
| 3201 | } |
| 3202 | |
| 3203 | private void maybeHandleNetworkAgentMessage(Message msg) { |
| 3204 | final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj; |
| 3205 | final NetworkAgentInfo nai = arg.first; |
| 3206 | if (!mNetworkAgentInfos.contains(nai)) { |
| 3207 | if (VDBG) { |
| 3208 | log(String.format("%s from unknown NetworkAgent", eventName(msg.what))); |
| 3209 | } |
| 3210 | return; |
| 3211 | } |
| 3212 | |
| 3213 | switch (msg.what) { |
| 3214 | case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: { |
| 3215 | NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second; |
| 3216 | if (networkCapabilities.hasConnectivityManagedCapability()) { |
| 3217 | Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability."); |
| 3218 | } |
| 3219 | if (networkCapabilities.hasTransport(TRANSPORT_TEST)) { |
| 3220 | // Make sure the original object is not mutated. NetworkAgent normally |
| 3221 | // makes a copy of the capabilities when sending the message through |
| 3222 | // the Messenger, but if this ever changes, not making a defensive copy |
| 3223 | // here will give attack vectors to clients using this code path. |
| 3224 | networkCapabilities = new NetworkCapabilities(networkCapabilities); |
| 3225 | networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid); |
| 3226 | } |
| 3227 | processCapabilitiesFromAgent(nai, networkCapabilities); |
| 3228 | updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities); |
| 3229 | break; |
| 3230 | } |
| 3231 | case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: { |
| 3232 | LinkProperties newLp = (LinkProperties) arg.second; |
| 3233 | processLinkPropertiesFromAgent(nai, newLp); |
| 3234 | handleUpdateLinkProperties(nai, newLp); |
| 3235 | break; |
| 3236 | } |
| 3237 | case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: { |
| 3238 | NetworkInfo info = (NetworkInfo) arg.second; |
| 3239 | updateNetworkInfo(nai, info); |
| 3240 | break; |
| 3241 | } |
| 3242 | case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: { |
| 3243 | updateNetworkScore(nai, (NetworkScore) arg.second); |
| 3244 | break; |
| 3245 | } |
| 3246 | case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: { |
| 3247 | if (nai.everConnected) { |
| 3248 | loge("ERROR: cannot call explicitlySelected on already-connected network"); |
| 3249 | // Note that if the NAI had been connected, this would affect the |
| 3250 | // score, and therefore would require re-mixing the score and performing |
| 3251 | // a rematch. |
| 3252 | } |
| 3253 | nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1); |
| 3254 | nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2); |
| 3255 | // Mark the network as temporarily accepting partial connectivity so that it |
| 3256 | // will be validated (and possibly become default) even if it only provides |
| 3257 | // partial internet access. Note that if user connects to partial connectivity |
| 3258 | // and choose "don't ask again", then wifi disconnected by some reasons(maybe |
| 3259 | // out of wifi coverage) and if the same wifi is available again, the device |
| 3260 | // will auto connect to this wifi even though the wifi has "no internet". |
| 3261 | // TODO: Evaluate using a separate setting in IpMemoryStore. |
| 3262 | nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2); |
| 3263 | break; |
| 3264 | } |
| 3265 | case NetworkAgent.EVENT_SOCKET_KEEPALIVE: { |
| 3266 | mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2); |
| 3267 | break; |
| 3268 | } |
| 3269 | case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: { |
| 3270 | // TODO: prevent loops, e.g., if a network declares itself as underlying. |
| 3271 | if (!nai.supportsUnderlyingNetworks()) { |
| 3272 | Log.wtf(TAG, "Non-virtual networks cannot have underlying networks"); |
| 3273 | break; |
| 3274 | } |
| 3275 | |
| 3276 | final List<Network> underlying = (List<Network>) arg.second; |
| 3277 | |
| 3278 | if (isLegacyLockdownNai(nai) |
| 3279 | && (underlying == null || underlying.size() != 1)) { |
| 3280 | Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString() |
| 3281 | + " must have exactly one underlying network: " + underlying); |
| 3282 | } |
| 3283 | |
| 3284 | final Network[] oldUnderlying = nai.declaredUnderlyingNetworks; |
| 3285 | nai.declaredUnderlyingNetworks = (underlying != null) |
| 3286 | ? underlying.toArray(new Network[0]) : null; |
| 3287 | |
| 3288 | if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) { |
| 3289 | if (DBG) { |
| 3290 | log(nai.toShortString() + " changed underlying networks to " |
| 3291 | + Arrays.toString(nai.declaredUnderlyingNetworks)); |
| 3292 | } |
| 3293 | updateCapabilitiesForNetwork(nai); |
| 3294 | notifyIfacesChangedForNetworkStats(); |
| 3295 | } |
| 3296 | break; |
| 3297 | } |
| 3298 | case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: { |
| 3299 | if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) { |
| 3300 | nai.teardownDelayMs = msg.arg1; |
| 3301 | } else { |
| 3302 | logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1); |
| 3303 | } |
| 3304 | break; |
| 3305 | } |
| 3306 | case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: { |
| 3307 | nai.setLingerDuration((int) arg.second); |
| 3308 | break; |
| 3309 | } |
| 3310 | } |
| 3311 | } |
| 3312 | |
| 3313 | private boolean maybeHandleNetworkMonitorMessage(Message msg) { |
| 3314 | switch (msg.what) { |
| 3315 | default: |
| 3316 | return false; |
| 3317 | case EVENT_PROBE_STATUS_CHANGED: { |
| 3318 | final Integer netId = (Integer) msg.obj; |
| 3319 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId); |
| 3320 | if (nai == null) { |
| 3321 | break; |
| 3322 | } |
| 3323 | final boolean probePrivateDnsCompleted = |
| 3324 | ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0); |
| 3325 | final boolean privateDnsBroken = |
| 3326 | ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0); |
| 3327 | if (probePrivateDnsCompleted) { |
| 3328 | if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) { |
| 3329 | nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken); |
| 3330 | updateCapabilitiesForNetwork(nai); |
| 3331 | } |
| 3332 | // Only show the notification when the private DNS is broken and the |
| 3333 | // PRIVATE_DNS_BROKEN notification hasn't shown since last valid. |
| 3334 | if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) { |
| 3335 | showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN); |
| 3336 | } |
| 3337 | nai.networkAgentConfig.hasShownBroken = privateDnsBroken; |
| 3338 | } else if (nai.networkCapabilities.isPrivateDnsBroken()) { |
| 3339 | // If probePrivateDnsCompleted is false but nai.networkCapabilities says |
| 3340 | // private DNS is broken, it means this network is being reevaluated. |
| 3341 | // Either probing private DNS is not necessary any more or it hasn't been |
| 3342 | // done yet. In either case, the networkCapabilities should be updated to |
| 3343 | // reflect the new status. |
| 3344 | nai.networkCapabilities.setPrivateDnsBroken(false); |
| 3345 | updateCapabilitiesForNetwork(nai); |
| 3346 | nai.networkAgentConfig.hasShownBroken = false; |
| 3347 | } |
| 3348 | break; |
| 3349 | } |
| 3350 | case EVENT_NETWORK_TESTED: { |
| 3351 | final NetworkTestedResults results = (NetworkTestedResults) msg.obj; |
| 3352 | |
| 3353 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId); |
| 3354 | if (nai == null) break; |
| 3355 | |
| 3356 | handleNetworkTested(nai, results.mTestResult, |
| 3357 | (results.mRedirectUrl == null) ? "" : results.mRedirectUrl); |
| 3358 | break; |
| 3359 | } |
| 3360 | case EVENT_PROVISIONING_NOTIFICATION: { |
| 3361 | final int netId = msg.arg2; |
| 3362 | final boolean visible = toBool(msg.arg1); |
| 3363 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId); |
| 3364 | // If captive portal status has changed, update capabilities or disconnect. |
| 3365 | if (nai != null && (visible != nai.lastCaptivePortalDetected)) { |
| 3366 | nai.lastCaptivePortalDetected = visible; |
| 3367 | nai.everCaptivePortalDetected |= visible; |
| 3368 | if (nai.lastCaptivePortalDetected && |
| 3369 | ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID |
| 3370 | == getCaptivePortalMode()) { |
| 3371 | if (DBG) log("Avoiding captive portal network: " + nai.toShortString()); |
| 3372 | nai.onPreventAutomaticReconnect(); |
| 3373 | teardownUnneededNetwork(nai); |
| 3374 | break; |
| 3375 | } |
| 3376 | updateCapabilitiesForNetwork(nai); |
| 3377 | } |
| 3378 | if (!visible) { |
| 3379 | // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other |
| 3380 | // notifications belong to the same network may be cleared unexpectedly. |
| 3381 | mNotifier.clearNotification(netId, NotificationType.SIGN_IN); |
| 3382 | mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH); |
| 3383 | } else { |
| 3384 | if (nai == null) { |
| 3385 | loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor"); |
| 3386 | break; |
| 3387 | } |
| 3388 | if (!nai.networkAgentConfig.provisioningNotificationDisabled) { |
| 3389 | mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null, |
| 3390 | (PendingIntent) msg.obj, |
| 3391 | nai.networkAgentConfig.explicitlySelected); |
| 3392 | } |
| 3393 | } |
| 3394 | break; |
| 3395 | } |
| 3396 | case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: { |
| 3397 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2); |
| 3398 | if (nai == null) break; |
| 3399 | |
| 3400 | updatePrivateDns(nai, (PrivateDnsConfig) msg.obj); |
| 3401 | break; |
| 3402 | } |
| 3403 | case EVENT_CAPPORT_DATA_CHANGED: { |
| 3404 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2); |
| 3405 | if (nai == null) break; |
| 3406 | handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj); |
| 3407 | break; |
| 3408 | } |
| 3409 | } |
| 3410 | return true; |
| 3411 | } |
| 3412 | |
| 3413 | private void handleNetworkTested( |
| 3414 | @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) { |
| 3415 | final boolean wasPartial = nai.partialConnectivity; |
| 3416 | nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0); |
| 3417 | final boolean partialConnectivityChanged = |
| 3418 | (wasPartial != nai.partialConnectivity); |
| 3419 | |
| 3420 | final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0); |
| 3421 | final boolean wasValidated = nai.lastValidated; |
| 3422 | final boolean wasDefault = isDefaultNetwork(nai); |
| 3423 | |
| 3424 | if (DBG) { |
| 3425 | final String logMsg = !TextUtils.isEmpty(redirectUrl) |
| 3426 | ? " with redirect to " + redirectUrl |
| 3427 | : ""; |
| 3428 | log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg); |
| 3429 | } |
| 3430 | if (valid != nai.lastValidated) { |
| 3431 | final int oldScore = nai.getCurrentScore(); |
| 3432 | nai.lastValidated = valid; |
| 3433 | nai.everValidated |= valid; |
| 3434 | updateCapabilities(oldScore, nai, nai.networkCapabilities); |
| 3435 | if (valid) { |
| 3436 | handleFreshlyValidatedNetwork(nai); |
| 3437 | // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and |
| 3438 | // LOST_INTERNET notifications if network becomes valid. |
| 3439 | mNotifier.clearNotification(nai.network.getNetId(), |
| 3440 | NotificationType.NO_INTERNET); |
| 3441 | mNotifier.clearNotification(nai.network.getNetId(), |
| 3442 | NotificationType.LOST_INTERNET); |
| 3443 | mNotifier.clearNotification(nai.network.getNetId(), |
| 3444 | NotificationType.PARTIAL_CONNECTIVITY); |
| 3445 | mNotifier.clearNotification(nai.network.getNetId(), |
| 3446 | NotificationType.PRIVATE_DNS_BROKEN); |
| 3447 | // If network becomes valid, the hasShownBroken should be reset for |
| 3448 | // that network so that the notification will be fired when the private |
| 3449 | // DNS is broken again. |
| 3450 | nai.networkAgentConfig.hasShownBroken = false; |
| 3451 | } |
| 3452 | } else if (partialConnectivityChanged) { |
| 3453 | updateCapabilitiesForNetwork(nai); |
| 3454 | } |
| 3455 | updateInetCondition(nai); |
| 3456 | // Let the NetworkAgent know the state of its network |
| 3457 | // TODO: Evaluate to update partial connectivity to status to NetworkAgent. |
| 3458 | nai.onValidationStatusChanged( |
| 3459 | valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK, |
| 3460 | redirectUrl); |
| 3461 | |
| 3462 | // If NetworkMonitor detects partial connectivity before |
| 3463 | // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification |
| 3464 | // immediately. Re-notify partial connectivity silently if no internet |
| 3465 | // notification already there. |
| 3466 | if (!wasPartial && nai.partialConnectivity) { |
| 3467 | // Remove delayed message if there is a pending message. |
| 3468 | mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network); |
| 3469 | handlePromptUnvalidated(nai.network); |
| 3470 | } |
| 3471 | |
| 3472 | if (wasValidated && !nai.lastValidated) { |
| 3473 | handleNetworkUnvalidated(nai); |
| 3474 | } |
| 3475 | } |
| 3476 | |
| 3477 | private int getCaptivePortalMode() { |
| 3478 | return Settings.Global.getInt(mContext.getContentResolver(), |
| 3479 | ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE, |
| 3480 | ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT); |
| 3481 | } |
| 3482 | |
| 3483 | private boolean maybeHandleNetworkAgentInfoMessage(Message msg) { |
| 3484 | switch (msg.what) { |
| 3485 | default: |
| 3486 | return false; |
| 3487 | case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: { |
| 3488 | NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj; |
| 3489 | if (nai != null && isLiveNetworkAgent(nai, msg.what)) { |
| 3490 | handleLingerComplete(nai); |
| 3491 | } |
| 3492 | break; |
| 3493 | } |
| 3494 | case NetworkAgentInfo.EVENT_AGENT_REGISTERED: { |
| 3495 | handleNetworkAgentRegistered(msg); |
| 3496 | break; |
| 3497 | } |
| 3498 | case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: { |
| 3499 | handleNetworkAgentDisconnected(msg); |
| 3500 | break; |
| 3501 | } |
| 3502 | } |
| 3503 | return true; |
| 3504 | } |
| 3505 | |
| 3506 | @Override |
| 3507 | public void handleMessage(Message msg) { |
| 3508 | if (!maybeHandleNetworkMonitorMessage(msg) |
| 3509 | && !maybeHandleNetworkAgentInfoMessage(msg)) { |
| 3510 | maybeHandleNetworkAgentMessage(msg); |
| 3511 | } |
| 3512 | } |
| 3513 | } |
| 3514 | |
| 3515 | private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub { |
| 3516 | private final int mNetId; |
| 3517 | private final AutodestructReference<NetworkAgentInfo> mNai; |
| 3518 | |
| 3519 | private NetworkMonitorCallbacks(NetworkAgentInfo nai) { |
| 3520 | mNetId = nai.network.getNetId(); |
| 3521 | mNai = new AutodestructReference<>(nai); |
| 3522 | } |
| 3523 | |
| 3524 | @Override |
| 3525 | public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) { |
| 3526 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, |
| 3527 | new Pair<>(mNai.getAndDestroy(), networkMonitor))); |
| 3528 | } |
| 3529 | |
| 3530 | @Override |
| 3531 | public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) { |
| 3532 | // Legacy version of notifyNetworkTestedWithExtras. |
| 3533 | // Would only be called if the system has a NetworkStack module older than the |
| 3534 | // framework, which does not happen in practice. |
| 3535 | Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken"); |
| 3536 | } |
| 3537 | |
| 3538 | @Override |
| 3539 | public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) { |
| 3540 | // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use |
| 3541 | // the same looper so messages will be processed in sequence. |
| 3542 | final Message msg = mTrackerHandler.obtainMessage( |
| 3543 | EVENT_NETWORK_TESTED, |
| 3544 | new NetworkTestedResults( |
| 3545 | mNetId, p.result, p.timestampMillis, p.redirectUrl)); |
| 3546 | mTrackerHandler.sendMessage(msg); |
| 3547 | |
| 3548 | // Invoke ConnectivityReport generation for this Network test event. |
| 3549 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId); |
| 3550 | if (nai == null) return; |
| 3551 | |
| 3552 | final PersistableBundle extras = new PersistableBundle(); |
| 3553 | extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result); |
| 3554 | extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded); |
| 3555 | extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted); |
| 3556 | |
| 3557 | ConnectivityReportEvent reportEvent = |
| 3558 | new ConnectivityReportEvent(p.timestampMillis, nai, extras); |
| 3559 | final Message m = mConnectivityDiagnosticsHandler.obtainMessage( |
| 3560 | ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent); |
| 3561 | mConnectivityDiagnosticsHandler.sendMessage(m); |
| 3562 | } |
| 3563 | |
| 3564 | @Override |
| 3565 | public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) { |
| 3566 | mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage( |
| 3567 | EVENT_PRIVATE_DNS_CONFIG_RESOLVED, |
| 3568 | 0, mNetId, PrivateDnsConfig.fromParcel(config))); |
| 3569 | } |
| 3570 | |
| 3571 | @Override |
| 3572 | public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) { |
| 3573 | mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage( |
| 3574 | EVENT_PROBE_STATUS_CHANGED, |
| 3575 | probesCompleted, probesSucceeded, new Integer(mNetId))); |
| 3576 | } |
| 3577 | |
| 3578 | @Override |
| 3579 | public void notifyCaptivePortalDataChanged(CaptivePortalData data) { |
| 3580 | mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage( |
| 3581 | EVENT_CAPPORT_DATA_CHANGED, |
| 3582 | 0, mNetId, data)); |
| 3583 | } |
| 3584 | |
| 3585 | @Override |
| 3586 | public void showProvisioningNotification(String action, String packageName) { |
| 3587 | final Intent intent = new Intent(action); |
| 3588 | intent.setPackage(packageName); |
| 3589 | |
| 3590 | final PendingIntent pendingIntent; |
| 3591 | // Only the system server can register notifications with package "android" |
| 3592 | final long token = Binder.clearCallingIdentity(); |
| 3593 | try { |
| 3594 | pendingIntent = PendingIntent.getBroadcast( |
| 3595 | mContext, |
| 3596 | 0 /* requestCode */, |
| 3597 | intent, |
| 3598 | PendingIntent.FLAG_IMMUTABLE); |
| 3599 | } finally { |
| 3600 | Binder.restoreCallingIdentity(token); |
| 3601 | } |
| 3602 | mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage( |
| 3603 | EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW, |
| 3604 | mNetId, pendingIntent)); |
| 3605 | } |
| 3606 | |
| 3607 | @Override |
| 3608 | public void hideProvisioningNotification() { |
| 3609 | mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage( |
| 3610 | EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId)); |
| 3611 | } |
| 3612 | |
| 3613 | @Override |
| 3614 | public void notifyDataStallSuspected(DataStallReportParcelable p) { |
| 3615 | ConnectivityService.this.notifyDataStallSuspected(p, mNetId); |
| 3616 | } |
| 3617 | |
| 3618 | @Override |
| 3619 | public int getInterfaceVersion() { |
| 3620 | return this.VERSION; |
| 3621 | } |
| 3622 | |
| 3623 | @Override |
| 3624 | public String getInterfaceHash() { |
| 3625 | return this.HASH; |
| 3626 | } |
| 3627 | } |
| 3628 | |
| 3629 | private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) { |
| 3630 | log("Data stall detected with methods: " + p.detectionMethod); |
| 3631 | |
| 3632 | final PersistableBundle extras = new PersistableBundle(); |
| 3633 | int detectionMethod = 0; |
| 3634 | if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) { |
| 3635 | extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts); |
| 3636 | detectionMethod |= DETECTION_METHOD_DNS_EVENTS; |
| 3637 | } |
| 3638 | if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) { |
| 3639 | extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate); |
| 3640 | extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS, |
| 3641 | p.tcpMetricsCollectionPeriodMillis); |
| 3642 | detectionMethod |= DETECTION_METHOD_TCP_METRICS; |
| 3643 | } |
| 3644 | |
| 3645 | final Message msg = mConnectivityDiagnosticsHandler.obtainMessage( |
| 3646 | ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId, |
| 3647 | new Pair<>(p.timestampMillis, extras)); |
| 3648 | |
| 3649 | // NetworkStateTrackerHandler currently doesn't take any actions based on data |
| 3650 | // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid |
| 3651 | // the cost of going through two handlers. |
| 3652 | mConnectivityDiagnosticsHandler.sendMessage(msg); |
| 3653 | } |
| 3654 | |
| 3655 | private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) { |
| 3656 | return (p.detectionMethod & detectionMethod) != 0; |
| 3657 | } |
| 3658 | |
| 3659 | private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) { |
| 3660 | return isPrivateDnsValidationRequired(nai.networkCapabilities); |
| 3661 | } |
| 3662 | |
| 3663 | private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) { |
| 3664 | if (nai == null) return; |
| 3665 | // If the Private DNS mode is opportunistic, reprogram the DNS servers |
| 3666 | // in order to restart a validation pass from within netd. |
| 3667 | final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig(); |
| 3668 | if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) { |
| 3669 | updateDnses(nai.linkProperties, null, nai.network.getNetId()); |
| 3670 | } |
| 3671 | } |
| 3672 | |
| 3673 | private void handlePrivateDnsSettingsChanged() { |
| 3674 | final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig(); |
| 3675 | |
| 3676 | for (NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 3677 | handlePerNetworkPrivateDnsConfig(nai, cfg); |
| 3678 | if (networkRequiresPrivateDnsValidation(nai)) { |
| 3679 | handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties)); |
| 3680 | } |
| 3681 | } |
| 3682 | } |
| 3683 | |
| 3684 | private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) { |
| 3685 | // Private DNS only ever applies to networks that might provide |
| 3686 | // Internet access and therefore also require validation. |
| 3687 | if (!networkRequiresPrivateDnsValidation(nai)) return; |
| 3688 | |
| 3689 | // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or |
| 3690 | // schedule DNS resolutions. If a DNS resolution is required the |
| 3691 | // result will be sent back to us. |
| 3692 | nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel()); |
| 3693 | |
| 3694 | // With Private DNS bypass support, we can proceed to update the |
| 3695 | // Private DNS config immediately, even if we're in strict mode |
| 3696 | // and have not yet resolved the provider name into a set of IPs. |
| 3697 | updatePrivateDns(nai, cfg); |
| 3698 | } |
| 3699 | |
| 3700 | private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) { |
| 3701 | mDnsManager.updatePrivateDns(nai.network, newCfg); |
| 3702 | updateDnses(nai.linkProperties, null, nai.network.getNetId()); |
| 3703 | } |
| 3704 | |
| 3705 | private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) { |
| 3706 | NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId); |
| 3707 | if (nai == null) { |
| 3708 | return; |
| 3709 | } |
| 3710 | mDnsManager.updatePrivateDnsValidation(update); |
| 3711 | handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties)); |
| 3712 | } |
| 3713 | |
| 3714 | private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress, |
| 3715 | int prefixLength) { |
| 3716 | NetworkAgentInfo nai = mNetworkForNetId.get(netId); |
| 3717 | if (nai == null) return; |
| 3718 | |
| 3719 | log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d", |
| 3720 | netId, operation, prefixAddress, prefixLength)); |
| 3721 | |
| 3722 | IpPrefix prefix = null; |
| 3723 | if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) { |
| 3724 | try { |
| 3725 | prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress), |
| 3726 | prefixLength); |
| 3727 | } catch (IllegalArgumentException e) { |
| 3728 | loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength); |
| 3729 | return; |
| 3730 | } |
| 3731 | } |
| 3732 | |
| 3733 | nai.clatd.setNat64PrefixFromDns(prefix); |
| 3734 | handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties)); |
| 3735 | } |
| 3736 | |
| 3737 | private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai, |
| 3738 | @Nullable final CaptivePortalData data) { |
| 3739 | nai.capportApiData = data; |
| 3740 | // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo |
| 3741 | handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties)); |
| 3742 | } |
| 3743 | |
| 3744 | /** |
| 3745 | * Updates the inactivity state from the network requests inside the NAI. |
| 3746 | * @param nai the agent info to update |
| 3747 | * @param now the timestamp of the event causing this update |
| 3748 | * @return whether the network was inactive as a result of this update |
| 3749 | */ |
| 3750 | private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) { |
| 3751 | // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm. |
| 3752 | // 2. If the network was inactive and there are now requests, unset inactive. |
| 3753 | // 3. If this network is unneeded (which implies it is not lingering), and there is at least |
| 3754 | // one lingered request, set inactive. |
| 3755 | nai.updateInactivityTimer(); |
| 3756 | if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) { |
| 3757 | if (DBG) log("Unsetting inactive " + nai.toShortString()); |
| 3758 | nai.unsetInactive(); |
| 3759 | logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER); |
| 3760 | } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) { |
| 3761 | if (DBG) { |
| 3762 | final int lingerTime = (int) (nai.getInactivityExpiry() - now); |
| 3763 | log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms"); |
| 3764 | } |
| 3765 | nai.setInactive(); |
| 3766 | logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER); |
| 3767 | return true; |
| 3768 | } |
| 3769 | return false; |
| 3770 | } |
| 3771 | |
| 3772 | private void handleNetworkAgentRegistered(Message msg) { |
| 3773 | final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj; |
| 3774 | if (!mNetworkAgentInfos.contains(nai)) { |
| 3775 | return; |
| 3776 | } |
| 3777 | |
| 3778 | if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) { |
| 3779 | if (VDBG) log("NetworkAgent registered"); |
| 3780 | } else { |
| 3781 | loge("Error connecting NetworkAgent"); |
| 3782 | mNetworkAgentInfos.remove(nai); |
| 3783 | if (nai != null) { |
| 3784 | final boolean wasDefault = isDefaultNetwork(nai); |
| 3785 | synchronized (mNetworkForNetId) { |
| 3786 | mNetworkForNetId.remove(nai.network.getNetId()); |
| 3787 | } |
| 3788 | mNetIdManager.releaseNetId(nai.network.getNetId()); |
| 3789 | // Just in case. |
| 3790 | mLegacyTypeTracker.remove(nai, wasDefault); |
| 3791 | } |
| 3792 | } |
| 3793 | } |
| 3794 | |
| 3795 | private void handleNetworkAgentDisconnected(Message msg) { |
| 3796 | NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj; |
| 3797 | if (mNetworkAgentInfos.contains(nai)) { |
| 3798 | disconnectAndDestroyNetwork(nai); |
| 3799 | } |
| 3800 | } |
| 3801 | |
| 3802 | // Destroys a network, remove references to it from the internal state managed by |
| 3803 | // ConnectivityService, free its interfaces and clean up. |
| 3804 | // Must be called on the Handler thread. |
| 3805 | private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) { |
| 3806 | ensureRunningOnConnectivityServiceThread(); |
| 3807 | if (DBG) { |
| 3808 | log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests()); |
| 3809 | } |
| 3810 | // Clear all notifications of this network. |
| 3811 | mNotifier.clearNotification(nai.network.getNetId()); |
| 3812 | // A network agent has disconnected. |
| 3813 | // TODO - if we move the logic to the network agent (have them disconnect |
| 3814 | // because they lost all their requests or because their score isn't good) |
| 3815 | // then they would disconnect organically, report their new state and then |
| 3816 | // disconnect the channel. |
| 3817 | if (nai.networkInfo.isConnected()) { |
| 3818 | nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, |
| 3819 | null, null); |
| 3820 | } |
| 3821 | final boolean wasDefault = isDefaultNetwork(nai); |
| 3822 | if (wasDefault) { |
| 3823 | mDefaultInetConditionPublished = 0; |
| 3824 | } |
| 3825 | notifyIfacesChangedForNetworkStats(); |
| 3826 | // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied |
| 3827 | // by other networks that are already connected. Perhaps that can be done by |
| 3828 | // sending all CALLBACK_LOST messages (for requests, not listens) at the end |
| 3829 | // of rematchAllNetworksAndRequests |
| 3830 | notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST); |
| 3831 | mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK); |
| 3832 | |
| 3833 | mQosCallbackTracker.handleNetworkReleased(nai.network); |
| 3834 | for (String iface : nai.linkProperties.getAllInterfaceNames()) { |
| 3835 | // Disable wakeup packet monitoring for each interface. |
| 3836 | wakeupModifyInterface(iface, nai.networkCapabilities, false); |
| 3837 | } |
| 3838 | nai.networkMonitor().notifyNetworkDisconnected(); |
| 3839 | mNetworkAgentInfos.remove(nai); |
| 3840 | nai.clatd.update(); |
| 3841 | synchronized (mNetworkForNetId) { |
| 3842 | // Remove the NetworkAgent, but don't mark the netId as |
| 3843 | // available until we've told netd to delete it below. |
| 3844 | mNetworkForNetId.remove(nai.network.getNetId()); |
| 3845 | } |
| 3846 | propagateUnderlyingNetworkCapabilities(nai.network); |
| 3847 | // Remove all previously satisfied requests. |
| 3848 | for (int i = 0; i < nai.numNetworkRequests(); i++) { |
| 3849 | final NetworkRequest request = nai.requestAt(i); |
| 3850 | final NetworkRequestInfo nri = mNetworkRequests.get(request); |
| 3851 | final NetworkAgentInfo currentNetwork = nri.getSatisfier(); |
| 3852 | if (currentNetwork != null |
| 3853 | && currentNetwork.network.getNetId() == nai.network.getNetId()) { |
| 3854 | // uid rules for this network will be removed in destroyNativeNetwork(nai). |
| 3855 | // TODO : setting the satisfier is in fact the job of the rematch. Teach the |
| 3856 | // rematch not to keep disconnected agents instead of setting it here ; this |
| 3857 | // will also allow removing updating the offers below. |
| 3858 | nri.setSatisfier(null, null); |
| 3859 | for (final NetworkOfferInfo noi : mNetworkOffers) { |
| 3860 | informOffer(nri, noi.offer, mNetworkRanker); |
| 3861 | } |
| 3862 | |
| 3863 | if (mDefaultRequest == nri) { |
| 3864 | // TODO : make battery stats aware that since 2013 multiple interfaces may be |
| 3865 | // active at the same time. For now keep calling this with the default |
| 3866 | // network, because while incorrect this is the closest to the old (also |
| 3867 | // incorrect) behavior. |
| 3868 | mNetworkActivityTracker.updateDataActivityTracking( |
| 3869 | null /* newNetwork */, nai); |
| 3870 | ensureNetworkTransitionWakelock(nai.toShortString()); |
| 3871 | } |
| 3872 | } |
| 3873 | } |
| 3874 | nai.clearInactivityState(); |
| 3875 | // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after. |
| 3876 | // Currently, deleting it breaks tests that check for the default network disconnecting. |
| 3877 | // Find out why, fix the rematch code, and delete this. |
| 3878 | mLegacyTypeTracker.remove(nai, wasDefault); |
| 3879 | rematchAllNetworksAndRequests(); |
| 3880 | mLingerMonitor.noteDisconnect(nai); |
| 3881 | |
| 3882 | // Immediate teardown. |
| 3883 | if (nai.teardownDelayMs == 0) { |
| 3884 | destroyNetwork(nai); |
| 3885 | return; |
| 3886 | } |
| 3887 | |
| 3888 | // Delayed teardown. |
| 3889 | try { |
| 3890 | mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM); |
| 3891 | } catch (RemoteException e) { |
| 3892 | Log.d(TAG, "Error marking network restricted during teardown: " + e); |
| 3893 | } |
| 3894 | mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs); |
| 3895 | } |
| 3896 | |
| 3897 | private void destroyNetwork(NetworkAgentInfo nai) { |
| 3898 | if (nai.created) { |
| 3899 | // Tell netd to clean up the configuration for this network |
| 3900 | // (routing rules, DNS, etc). |
| 3901 | // This may be slow as it requires a lot of netd shelling out to ip and |
| 3902 | // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it |
| 3903 | // after we've rematched networks with requests (which might change the default |
| 3904 | // network or service a new request from an app), so network traffic isn't interrupted |
| 3905 | // for an unnecessarily long time. |
| 3906 | destroyNativeNetwork(nai); |
| 3907 | mDnsManager.removeNetwork(nai.network); |
| 3908 | } |
| 3909 | mNetIdManager.releaseNetId(nai.network.getNetId()); |
| 3910 | nai.onNetworkDestroyed(); |
| 3911 | } |
| 3912 | |
| 3913 | private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) { |
| 3914 | try { |
| 3915 | // This should never fail. Specifying an already in use NetID will cause failure. |
| 3916 | final NativeNetworkConfig config; |
| 3917 | if (nai.isVPN()) { |
| 3918 | if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) { |
| 3919 | Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString()); |
| 3920 | return false; |
| 3921 | } |
| 3922 | config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL, |
| 3923 | INetd.PERMISSION_NONE, |
| 3924 | (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass), |
| 3925 | getVpnType(nai)); |
| 3926 | } else { |
| 3927 | config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL, |
| 3928 | getNetworkPermission(nai.networkCapabilities), /*secure=*/ false, |
| 3929 | VpnManager.TYPE_VPN_NONE); |
| 3930 | } |
| 3931 | mNetd.networkCreate(config); |
| 3932 | mDnsResolver.createNetworkCache(nai.network.getNetId()); |
| 3933 | mDnsManager.updateTransportsForNetwork(nai.network.getNetId(), |
| 3934 | nai.networkCapabilities.getTransportTypes()); |
| 3935 | return true; |
| 3936 | } catch (RemoteException | ServiceSpecificException e) { |
| 3937 | loge("Error creating network " + nai.toShortString() + ": " + e.getMessage()); |
| 3938 | return false; |
| 3939 | } |
| 3940 | } |
| 3941 | |
| 3942 | private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) { |
| 3943 | try { |
| 3944 | mNetd.networkDestroy(nai.network.getNetId()); |
| 3945 | } catch (RemoteException | ServiceSpecificException e) { |
| 3946 | loge("Exception destroying network(networkDestroy): " + e); |
| 3947 | } |
| 3948 | try { |
| 3949 | mDnsResolver.destroyNetworkCache(nai.network.getNetId()); |
| 3950 | } catch (RemoteException | ServiceSpecificException e) { |
| 3951 | loge("Exception destroying network: " + e); |
| 3952 | } |
| 3953 | } |
| 3954 | |
| 3955 | // If this method proves to be too slow then we can maintain a separate |
| 3956 | // pendingIntent => NetworkRequestInfo map. |
| 3957 | // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo. |
| 3958 | private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) { |
| 3959 | for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) { |
| 3960 | PendingIntent existingPendingIntent = entry.getValue().mPendingIntent; |
| 3961 | if (existingPendingIntent != null && |
Remi NGUYEN VAN | ff55aeb | 2021-06-16 11:37:53 +0000 | [diff] [blame] | 3962 | mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) { |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 3963 | return entry.getValue(); |
| 3964 | } |
| 3965 | } |
| 3966 | return null; |
| 3967 | } |
| 3968 | |
| 3969 | private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) { |
| 3970 | final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj); |
| 3971 | // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests. |
| 3972 | ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent"); |
| 3973 | final NetworkRequestInfo existingRequest = |
| 3974 | findExistingNetworkRequestInfo(nri.mPendingIntent); |
| 3975 | if (existingRequest != null) { // remove the existing request. |
| 3976 | if (DBG) { |
| 3977 | log("Replacing " + existingRequest.mRequests.get(0) + " with " |
| 3978 | + nri.mRequests.get(0) + " because their intents matched."); |
| 3979 | } |
| 3980 | handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(), |
| 3981 | /* callOnUnavailable */ false); |
| 3982 | } |
| 3983 | handleRegisterNetworkRequest(nri); |
| 3984 | } |
| 3985 | |
| 3986 | private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) { |
| 3987 | handleRegisterNetworkRequests(Collections.singleton(nri)); |
| 3988 | } |
| 3989 | |
| 3990 | private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) { |
| 3991 | ensureRunningOnConnectivityServiceThread(); |
| 3992 | for (final NetworkRequestInfo nri : nris) { |
| 3993 | mNetworkRequestInfoLogs.log("REGISTER " + nri); |
| 3994 | for (final NetworkRequest req : nri.mRequests) { |
| 3995 | mNetworkRequests.put(req, nri); |
| 3996 | // TODO: Consider update signal strength for other types. |
| 3997 | if (req.isListen()) { |
| 3998 | for (final NetworkAgentInfo network : mNetworkAgentInfos) { |
| 3999 | if (req.networkCapabilities.hasSignalStrength() |
| 4000 | && network.satisfiesImmutableCapabilitiesOf(req)) { |
| 4001 | updateSignalStrengthThresholds(network, "REGISTER", req); |
| 4002 | } |
| 4003 | } |
| 4004 | } |
| 4005 | } |
| 4006 | // If this NRI has a satisfier already, it is replacing an older request that |
| 4007 | // has been removed. Track it. |
| 4008 | final NetworkRequest activeRequest = nri.getActiveRequest(); |
| 4009 | if (null != activeRequest) { |
| 4010 | // If there is an active request, then for sure there is a satisfier. |
| 4011 | nri.getSatisfier().addRequest(activeRequest); |
| 4012 | } |
| 4013 | } |
| 4014 | |
| 4015 | rematchAllNetworksAndRequests(); |
| 4016 | |
| 4017 | // Requests that have not been matched to a network will not have been sent to the |
| 4018 | // providers, because the old satisfier and the new satisfier are the same (null in this |
| 4019 | // case). Send these requests to the providers. |
| 4020 | for (final NetworkRequestInfo nri : nris) { |
| 4021 | for (final NetworkOfferInfo noi : mNetworkOffers) { |
| 4022 | informOffer(nri, noi.offer, mNetworkRanker); |
| 4023 | } |
| 4024 | } |
| 4025 | } |
| 4026 | |
| 4027 | private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent, |
| 4028 | final int callingUid) { |
| 4029 | final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent); |
| 4030 | if (nri != null) { |
| 4031 | // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests. |
| 4032 | ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent"); |
| 4033 | handleReleaseNetworkRequest( |
| 4034 | nri.mRequests.get(0), |
| 4035 | callingUid, |
| 4036 | /* callOnUnavailable */ false); |
| 4037 | } |
| 4038 | } |
| 4039 | |
| 4040 | // Determines whether the network is the best (or could become the best, if it validated), for |
| 4041 | // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends |
| 4042 | // on the value of reason: |
| 4043 | // |
| 4044 | // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason, |
| 4045 | // then it should be torn down. |
| 4046 | // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason, |
| 4047 | // then it should be lingered. |
| 4048 | private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) { |
| 4049 | ensureRunningOnConnectivityServiceThread(); |
| 4050 | |
| 4051 | if (!nai.everConnected || nai.isVPN() || nai.isInactive() |
| 4052 | || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) { |
| 4053 | return false; |
| 4054 | } |
| 4055 | |
| 4056 | final int numRequests; |
| 4057 | switch (reason) { |
| 4058 | case TEARDOWN: |
| 4059 | numRequests = nai.numRequestNetworkRequests(); |
| 4060 | break; |
| 4061 | case LINGER: |
| 4062 | numRequests = nai.numForegroundNetworkRequests(); |
| 4063 | break; |
| 4064 | default: |
| 4065 | Log.wtf(TAG, "Invalid reason. Cannot happen."); |
| 4066 | return true; |
| 4067 | } |
| 4068 | |
| 4069 | if (numRequests > 0) return false; |
| 4070 | |
| 4071 | for (NetworkRequestInfo nri : mNetworkRequests.values()) { |
| 4072 | if (reason == UnneededFor.LINGER |
| 4073 | && !nri.isMultilayerRequest() |
| 4074 | && nri.mRequests.get(0).isBackgroundRequest()) { |
| 4075 | // Background requests don't affect lingering. |
| 4076 | continue; |
| 4077 | } |
| 4078 | |
| 4079 | if (isNetworkPotentialSatisfier(nai, nri)) { |
| 4080 | return false; |
| 4081 | } |
| 4082 | } |
| 4083 | return true; |
| 4084 | } |
| 4085 | |
| 4086 | private boolean isNetworkPotentialSatisfier( |
| 4087 | @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) { |
| 4088 | // listen requests won't keep up a network satisfying it. If this is not a multilayer |
| 4089 | // request, return immediately. For multilayer requests, check to see if any of the |
| 4090 | // multilayer requests may have a potential satisfier. |
| 4091 | if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen() |
| 4092 | || nri.mRequests.get(0).isListenForBest())) { |
| 4093 | return false; |
| 4094 | } |
| 4095 | for (final NetworkRequest req : nri.mRequests) { |
| 4096 | // This multilayer listen request is satisfied therefore no further requests need to be |
| 4097 | // evaluated deeming this network not a potential satisfier. |
| 4098 | if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) { |
| 4099 | return false; |
| 4100 | } |
| 4101 | // As non-multilayer listen requests have already returned, the below would only happen |
| 4102 | // for a multilayer request therefore continue to the next request if available. |
| 4103 | if (req.isListen() || req.isListenForBest()) { |
| 4104 | continue; |
| 4105 | } |
| 4106 | // If this Network is already the highest scoring Network for a request, or if |
| 4107 | // there is hope for it to become one if it validated, then it is needed. |
| 4108 | if (candidate.satisfies(req)) { |
| 4109 | // As soon as a network is found that satisfies a request, return. Specifically for |
| 4110 | // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request |
| 4111 | // is important so as to not evaluate lower priority requests further in |
| 4112 | // nri.mRequests. |
| 4113 | final NetworkAgentInfo champion = req.equals(nri.getActiveRequest()) |
| 4114 | ? nri.getSatisfier() : null; |
| 4115 | // Note that this catches two important cases: |
| 4116 | // 1. Unvalidated cellular will not be reaped when unvalidated WiFi |
| 4117 | // is currently satisfying the request. This is desirable when |
| 4118 | // cellular ends up validating but WiFi does not. |
| 4119 | // 2. Unvalidated WiFi will not be reaped when validated cellular |
| 4120 | // is currently satisfying the request. This is desirable when |
| 4121 | // WiFi ends up validating and out scoring cellular. |
| 4122 | return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable()); |
| 4123 | } |
| 4124 | } |
| 4125 | |
| 4126 | return false; |
| 4127 | } |
| 4128 | |
| 4129 | private NetworkRequestInfo getNriForAppRequest( |
| 4130 | NetworkRequest request, int callingUid, String requestedOperation) { |
| 4131 | // Looking up the app passed param request in mRequests isn't possible since it may return |
| 4132 | // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to |
| 4133 | // do the lookup since that will also find per-app default managed requests. |
| 4134 | // Additionally, this lookup needs to be relatively fast (hence the lookup optimization) |
| 4135 | // to avoid potential race conditions when validating a package->uid mapping when sending |
| 4136 | // the callback on the very low-chance that an application shuts down prior to the callback |
| 4137 | // being sent. |
| 4138 | final NetworkRequestInfo nri = mNetworkRequests.get(request) != null |
| 4139 | ? mNetworkRequests.get(request) : getNriForAppRequest(request); |
| 4140 | |
| 4141 | if (nri != null) { |
| 4142 | if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) { |
| 4143 | log(String.format("UID %d attempted to %s for unowned request %s", |
| 4144 | callingUid, requestedOperation, nri)); |
| 4145 | return null; |
| 4146 | } |
| 4147 | } |
| 4148 | |
| 4149 | return nri; |
| 4150 | } |
| 4151 | |
| 4152 | private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri, |
| 4153 | final String callingMethod) { |
| 4154 | if (nri.isMultilayerRequest()) { |
| 4155 | throw new IllegalStateException( |
| 4156 | callingMethod + " does not support multilayer requests."); |
| 4157 | } |
| 4158 | } |
| 4159 | |
| 4160 | private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) { |
| 4161 | ensureRunningOnConnectivityServiceThread(); |
| 4162 | // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a |
| 4163 | // single NetworkRequest and thus does not apply to multilayer requests. |
| 4164 | ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest"); |
| 4165 | if (mNetworkRequests.get(nri.mRequests.get(0)) == null) { |
| 4166 | return; |
| 4167 | } |
| 4168 | if (nri.isBeingSatisfied()) { |
| 4169 | return; |
| 4170 | } |
| 4171 | if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) { |
| 4172 | log("releasing " + nri.mRequests.get(0) + " (timeout)"); |
| 4173 | } |
| 4174 | handleRemoveNetworkRequest(nri); |
| 4175 | callCallbackForRequest( |
| 4176 | nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0); |
| 4177 | } |
| 4178 | |
| 4179 | private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request, |
| 4180 | final int callingUid, |
| 4181 | final boolean callOnUnavailable) { |
| 4182 | final NetworkRequestInfo nri = |
| 4183 | getNriForAppRequest(request, callingUid, "release NetworkRequest"); |
| 4184 | if (nri == null) { |
| 4185 | return; |
| 4186 | } |
| 4187 | if (VDBG || (DBG && request.isRequest())) { |
| 4188 | log("releasing " + request + " (release request)"); |
| 4189 | } |
| 4190 | handleRemoveNetworkRequest(nri); |
| 4191 | if (callOnUnavailable) { |
| 4192 | callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0); |
| 4193 | } |
| 4194 | } |
| 4195 | |
| 4196 | private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) { |
| 4197 | ensureRunningOnConnectivityServiceThread(); |
| 4198 | nri.unlinkDeathRecipient(); |
| 4199 | for (final NetworkRequest req : nri.mRequests) { |
| 4200 | mNetworkRequests.remove(req); |
| 4201 | if (req.isListen()) { |
| 4202 | removeListenRequestFromNetworks(req); |
| 4203 | } |
| 4204 | } |
| 4205 | if (mDefaultNetworkRequests.remove(nri)) { |
| 4206 | // If this request was one of the defaults, then the UID rules need to be updated |
| 4207 | // WARNING : if the app(s) for which this network request is the default are doing |
| 4208 | // traffic, this will kill their connected sockets, even if an equivalent request |
| 4209 | // is going to be reinstated right away ; unconnected traffic will go on the default |
| 4210 | // until the new default is set, which will happen very soon. |
| 4211 | // TODO : The only way out of this is to diff old defaults and new defaults, and only |
| 4212 | // remove ranges for those requests that won't have a replacement |
| 4213 | final NetworkAgentInfo satisfier = nri.getSatisfier(); |
| 4214 | if (null != satisfier) { |
| 4215 | try { |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 4216 | // TODO: Passing default network priority to netd. |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 4217 | mNetd.networkRemoveUidRanges(satisfier.network.getNetId(), |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 4218 | toUidRangeStableParcels(nri.getUids()) |
| 4219 | /* nri.getDefaultNetworkPriority() */); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 4220 | } catch (RemoteException e) { |
| 4221 | loge("Exception setting network preference default network", e); |
| 4222 | } |
| 4223 | } |
| 4224 | } |
| 4225 | nri.decrementRequestCount(); |
| 4226 | mNetworkRequestInfoLogs.log("RELEASE " + nri); |
| 4227 | |
| 4228 | if (null != nri.getActiveRequest()) { |
| 4229 | if (!nri.getActiveRequest().isListen()) { |
| 4230 | removeSatisfiedNetworkRequestFromNetwork(nri); |
| 4231 | } else { |
| 4232 | nri.setSatisfier(null, null); |
| 4233 | } |
| 4234 | } |
| 4235 | |
| 4236 | // For all outstanding offers, cancel any of the layers of this NRI that used to be |
| 4237 | // needed for this offer. |
| 4238 | for (final NetworkOfferInfo noi : mNetworkOffers) { |
| 4239 | for (final NetworkRequest req : nri.mRequests) { |
| 4240 | if (req.isRequest() && noi.offer.neededFor(req)) { |
| 4241 | noi.offer.onNetworkUnneeded(req); |
| 4242 | } |
| 4243 | } |
| 4244 | } |
| 4245 | } |
| 4246 | |
| 4247 | private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) { |
| 4248 | for (final NetworkRequestInfo nri : nris) { |
| 4249 | if (mDefaultRequest == nri) { |
| 4250 | // Make sure we never remove the default request. |
| 4251 | continue; |
| 4252 | } |
| 4253 | handleRemoveNetworkRequest(nri); |
| 4254 | } |
| 4255 | } |
| 4256 | |
| 4257 | private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) { |
| 4258 | // listens don't have a singular affected Network. Check all networks to see |
| 4259 | // if this listen request applies and remove it. |
| 4260 | for (final NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 4261 | nai.removeRequest(req.requestId); |
| 4262 | if (req.networkCapabilities.hasSignalStrength() |
| 4263 | && nai.satisfiesImmutableCapabilitiesOf(req)) { |
| 4264 | updateSignalStrengthThresholds(nai, "RELEASE", req); |
| 4265 | } |
| 4266 | } |
| 4267 | } |
| 4268 | |
| 4269 | /** |
| 4270 | * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and |
| 4271 | * manage the necessary upkeep (linger, teardown networks, etc.) when doing so. |
| 4272 | * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo |
| 4273 | */ |
| 4274 | private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) { |
| 4275 | boolean wasKept = false; |
| 4276 | final NetworkAgentInfo nai = nri.getSatisfier(); |
| 4277 | if (nai != null) { |
| 4278 | final int requestLegacyType = nri.getActiveRequest().legacyType; |
| 4279 | final boolean wasBackgroundNetwork = nai.isBackgroundNetwork(); |
| 4280 | nai.removeRequest(nri.getActiveRequest().requestId); |
| 4281 | if (VDBG || DDBG) { |
| 4282 | log(" Removing from current network " + nai.toShortString() |
| 4283 | + ", leaving " + nai.numNetworkRequests() + " requests."); |
| 4284 | } |
| 4285 | // If there are still lingered requests on this network, don't tear it down, |
| 4286 | // but resume lingering instead. |
| 4287 | final long now = SystemClock.elapsedRealtime(); |
| 4288 | if (updateInactivityState(nai, now)) { |
| 4289 | notifyNetworkLosing(nai, now); |
| 4290 | } |
| 4291 | if (unneeded(nai, UnneededFor.TEARDOWN)) { |
| 4292 | if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting"); |
| 4293 | teardownUnneededNetwork(nai); |
| 4294 | } else { |
| 4295 | wasKept = true; |
| 4296 | } |
| 4297 | nri.setSatisfier(null, null); |
| 4298 | if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) { |
| 4299 | // Went from foreground to background. |
| 4300 | updateCapabilitiesForNetwork(nai); |
| 4301 | } |
| 4302 | |
| 4303 | // Maintain the illusion. When this request arrived, we might have pretended |
| 4304 | // that a network connected to serve it, even though the network was already |
| 4305 | // connected. Now that this request has gone away, we might have to pretend |
| 4306 | // that the network disconnected. LegacyTypeTracker will generate that |
| 4307 | // phantom disconnect for this type. |
| 4308 | if (requestLegacyType != TYPE_NONE) { |
| 4309 | boolean doRemove = true; |
| 4310 | if (wasKept) { |
| 4311 | // check if any of the remaining requests for this network are for the |
| 4312 | // same legacy type - if so, don't remove the nai |
| 4313 | for (int i = 0; i < nai.numNetworkRequests(); i++) { |
| 4314 | NetworkRequest otherRequest = nai.requestAt(i); |
| 4315 | if (otherRequest.legacyType == requestLegacyType |
| 4316 | && otherRequest.isRequest()) { |
| 4317 | if (DBG) log(" still have other legacy request - leaving"); |
| 4318 | doRemove = false; |
| 4319 | } |
| 4320 | } |
| 4321 | } |
| 4322 | |
| 4323 | if (doRemove) { |
| 4324 | mLegacyTypeTracker.remove(requestLegacyType, nai, false); |
| 4325 | } |
| 4326 | } |
| 4327 | } |
| 4328 | } |
| 4329 | |
| 4330 | private PerUidCounter getRequestCounter(NetworkRequestInfo nri) { |
| 4331 | return checkAnyPermissionOf( |
| 4332 | nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK) |
| 4333 | ? mSystemNetworkRequestCounter : mNetworkRequestCounter; |
| 4334 | } |
| 4335 | |
| 4336 | @Override |
| 4337 | public void setAcceptUnvalidated(Network network, boolean accept, boolean always) { |
| 4338 | enforceNetworkStackSettingsOrSetup(); |
| 4339 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED, |
| 4340 | encodeBool(accept), encodeBool(always), network)); |
| 4341 | } |
| 4342 | |
| 4343 | @Override |
| 4344 | public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) { |
| 4345 | enforceNetworkStackSettingsOrSetup(); |
| 4346 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY, |
| 4347 | encodeBool(accept), encodeBool(always), network)); |
| 4348 | } |
| 4349 | |
| 4350 | @Override |
| 4351 | public void setAvoidUnvalidated(Network network) { |
| 4352 | enforceNetworkStackSettingsOrSetup(); |
| 4353 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network)); |
| 4354 | } |
| 4355 | |
Chiachang Wang | fad30e3 | 2021-06-23 02:08:44 +0000 | [diff] [blame] | 4356 | @Override |
| 4357 | public void setTestAllowBadWifiUntil(long timeMs) { |
| 4358 | enforceSettingsPermission(); |
| 4359 | if (!Build.isDebuggable()) { |
| 4360 | throw new IllegalStateException("Does not support in non-debuggable build"); |
| 4361 | } |
| 4362 | |
| 4363 | if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) { |
| 4364 | throw new IllegalArgumentException("It should not exceed " |
| 4365 | + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now"); |
| 4366 | } |
| 4367 | |
| 4368 | mHandler.sendMessage( |
| 4369 | mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs)); |
| 4370 | } |
| 4371 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 4372 | private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) { |
| 4373 | if (DBG) log("handleSetAcceptUnvalidated network=" + network + |
| 4374 | " accept=" + accept + " always=" + always); |
| 4375 | |
| 4376 | NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 4377 | if (nai == null) { |
| 4378 | // Nothing to do. |
| 4379 | return; |
| 4380 | } |
| 4381 | |
| 4382 | if (nai.everValidated) { |
| 4383 | // The network validated while the dialog box was up. Take no action. |
| 4384 | return; |
| 4385 | } |
| 4386 | |
| 4387 | if (!nai.networkAgentConfig.explicitlySelected) { |
| 4388 | Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network"); |
| 4389 | } |
| 4390 | |
| 4391 | if (accept != nai.networkAgentConfig.acceptUnvalidated) { |
| 4392 | nai.networkAgentConfig.acceptUnvalidated = accept; |
| 4393 | // If network becomes partial connectivity and user already accepted to use this |
| 4394 | // network, we should respect the user's option and don't need to popup the |
| 4395 | // PARTIAL_CONNECTIVITY notification to user again. |
| 4396 | nai.networkAgentConfig.acceptPartialConnectivity = accept; |
| 4397 | nai.updateScoreForNetworkAgentUpdate(); |
| 4398 | rematchAllNetworksAndRequests(); |
| 4399 | } |
| 4400 | |
| 4401 | if (always) { |
| 4402 | nai.onSaveAcceptUnvalidated(accept); |
| 4403 | } |
| 4404 | |
| 4405 | if (!accept) { |
| 4406 | // Tell the NetworkAgent to not automatically reconnect to the network. |
| 4407 | nai.onPreventAutomaticReconnect(); |
| 4408 | // Teardown the network. |
| 4409 | teardownUnneededNetwork(nai); |
| 4410 | } |
| 4411 | |
| 4412 | } |
| 4413 | |
| 4414 | private void handleSetAcceptPartialConnectivity(Network network, boolean accept, |
| 4415 | boolean always) { |
| 4416 | if (DBG) { |
| 4417 | log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept |
| 4418 | + " always=" + always); |
| 4419 | } |
| 4420 | |
| 4421 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 4422 | if (nai == null) { |
| 4423 | // Nothing to do. |
| 4424 | return; |
| 4425 | } |
| 4426 | |
| 4427 | if (nai.lastValidated) { |
| 4428 | // The network validated while the dialog box was up. Take no action. |
| 4429 | return; |
| 4430 | } |
| 4431 | |
| 4432 | if (accept != nai.networkAgentConfig.acceptPartialConnectivity) { |
| 4433 | nai.networkAgentConfig.acceptPartialConnectivity = accept; |
| 4434 | } |
| 4435 | |
| 4436 | // TODO: Use the current design or save the user choice into IpMemoryStore. |
| 4437 | if (always) { |
| 4438 | nai.onSaveAcceptUnvalidated(accept); |
| 4439 | } |
| 4440 | |
| 4441 | if (!accept) { |
| 4442 | // Tell the NetworkAgent to not automatically reconnect to the network. |
| 4443 | nai.onPreventAutomaticReconnect(); |
| 4444 | // Tear down the network. |
| 4445 | teardownUnneededNetwork(nai); |
| 4446 | } else { |
| 4447 | // Inform NetworkMonitor that partial connectivity is acceptable. This will likely |
| 4448 | // result in a partial connectivity result which will be processed by |
| 4449 | // maybeHandleNetworkMonitorMessage. |
| 4450 | // |
| 4451 | // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored |
| 4452 | // per network. Therefore, NetworkMonitor may still do https probe. |
| 4453 | nai.networkMonitor().setAcceptPartialConnectivity(); |
| 4454 | } |
| 4455 | } |
| 4456 | |
| 4457 | private void handleSetAvoidUnvalidated(Network network) { |
| 4458 | NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 4459 | if (nai == null || nai.lastValidated) { |
| 4460 | // Nothing to do. The network either disconnected or revalidated. |
| 4461 | return; |
| 4462 | } |
| 4463 | if (!nai.avoidUnvalidated) { |
| 4464 | nai.avoidUnvalidated = true; |
| 4465 | nai.updateScoreForNetworkAgentUpdate(); |
| 4466 | rematchAllNetworksAndRequests(); |
| 4467 | } |
| 4468 | } |
| 4469 | |
| 4470 | private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) { |
| 4471 | if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network); |
| 4472 | mHandler.sendMessageDelayed( |
| 4473 | mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network), |
| 4474 | PROMPT_UNVALIDATED_DELAY_MS); |
| 4475 | } |
| 4476 | |
| 4477 | @Override |
| 4478 | public void startCaptivePortalApp(Network network) { |
| 4479 | enforceNetworkStackOrSettingsPermission(); |
| 4480 | mHandler.post(() -> { |
| 4481 | NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 4482 | if (nai == null) return; |
| 4483 | if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return; |
| 4484 | nai.networkMonitor().launchCaptivePortalApp(); |
| 4485 | }); |
| 4486 | } |
| 4487 | |
| 4488 | /** |
| 4489 | * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this |
| 4490 | * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself. |
| 4491 | * @param network Network on which the captive portal was detected. |
| 4492 | * @param appExtras Bundle to use as intent extras for the captive portal application. |
| 4493 | * Must be treated as opaque to avoid preventing the captive portal app to |
| 4494 | * update its arguments. |
| 4495 | */ |
| 4496 | @Override |
| 4497 | public void startCaptivePortalAppInternal(Network network, Bundle appExtras) { |
| 4498 | mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, |
| 4499 | "ConnectivityService"); |
| 4500 | |
| 4501 | final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN); |
| 4502 | appIntent.putExtras(appExtras); |
| 4503 | appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL, |
| 4504 | new CaptivePortal(new CaptivePortalImpl(network).asBinder())); |
| 4505 | appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); |
| 4506 | |
| 4507 | final long token = Binder.clearCallingIdentity(); |
| 4508 | try { |
| 4509 | mContext.startActivityAsUser(appIntent, UserHandle.CURRENT); |
| 4510 | } finally { |
| 4511 | Binder.restoreCallingIdentity(token); |
| 4512 | } |
| 4513 | } |
| 4514 | |
| 4515 | private class CaptivePortalImpl extends ICaptivePortal.Stub { |
| 4516 | private final Network mNetwork; |
| 4517 | |
| 4518 | private CaptivePortalImpl(Network network) { |
| 4519 | mNetwork = network; |
| 4520 | } |
| 4521 | |
| 4522 | @Override |
| 4523 | public void appResponse(final int response) { |
| 4524 | if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) { |
| 4525 | enforceSettingsPermission(); |
| 4526 | } |
| 4527 | |
| 4528 | final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork); |
| 4529 | if (nm == null) return; |
| 4530 | nm.notifyCaptivePortalAppFinished(response); |
| 4531 | } |
| 4532 | |
| 4533 | @Override |
| 4534 | public void appRequest(final int request) { |
| 4535 | final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork); |
| 4536 | if (nm == null) return; |
| 4537 | |
| 4538 | if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) { |
| 4539 | checkNetworkStackPermission(); |
| 4540 | nm.forceReevaluation(mDeps.getCallingUid()); |
| 4541 | } |
| 4542 | } |
| 4543 | |
| 4544 | @Nullable |
| 4545 | private NetworkMonitorManager getNetworkMonitorManager(final Network network) { |
| 4546 | // getNetworkAgentInfoForNetwork is thread-safe |
| 4547 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 4548 | if (nai == null) return null; |
| 4549 | |
| 4550 | // nai.networkMonitor() is thread-safe |
| 4551 | return nai.networkMonitor(); |
| 4552 | } |
| 4553 | } |
| 4554 | |
| 4555 | public boolean avoidBadWifi() { |
| 4556 | return mMultinetworkPolicyTracker.getAvoidBadWifi(); |
| 4557 | } |
| 4558 | |
| 4559 | /** |
| 4560 | * Return whether the device should maintain continuous, working connectivity by switching away |
| 4561 | * from WiFi networks having no connectivity. |
| 4562 | * @see MultinetworkPolicyTracker#getAvoidBadWifi() |
| 4563 | */ |
| 4564 | public boolean shouldAvoidBadWifi() { |
| 4565 | if (!checkNetworkStackPermission()) { |
| 4566 | throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission"); |
| 4567 | } |
| 4568 | return avoidBadWifi(); |
| 4569 | } |
| 4570 | |
| 4571 | private void updateAvoidBadWifi() { |
| 4572 | for (final NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 4573 | nai.updateScoreForNetworkAgentUpdate(); |
| 4574 | } |
| 4575 | rematchAllNetworksAndRequests(); |
| 4576 | } |
| 4577 | |
| 4578 | // TODO: Evaluate whether this is of interest to other consumers of |
| 4579 | // MultinetworkPolicyTracker and worth moving out of here. |
| 4580 | private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) { |
| 4581 | final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi(); |
| 4582 | if (!configRestrict) { |
| 4583 | pw.println("Bad Wi-Fi avoidance: unrestricted"); |
| 4584 | return; |
| 4585 | } |
| 4586 | |
| 4587 | pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi()); |
| 4588 | pw.increaseIndent(); |
| 4589 | pw.println("Config restrict: " + configRestrict); |
| 4590 | |
| 4591 | final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting(); |
| 4592 | String description; |
| 4593 | // Can't use a switch statement because strings are legal case labels, but null is not. |
| 4594 | if ("0".equals(value)) { |
| 4595 | description = "get stuck"; |
| 4596 | } else if (value == null) { |
| 4597 | description = "prompt"; |
| 4598 | } else if ("1".equals(value)) { |
| 4599 | description = "avoid"; |
| 4600 | } else { |
| 4601 | description = value + " (?)"; |
| 4602 | } |
| 4603 | pw.println("User setting: " + description); |
| 4604 | pw.println("Network overrides:"); |
| 4605 | pw.increaseIndent(); |
| 4606 | for (NetworkAgentInfo nai : networksSortedById()) { |
| 4607 | if (nai.avoidUnvalidated) { |
| 4608 | pw.println(nai.toShortString()); |
| 4609 | } |
| 4610 | } |
| 4611 | pw.decreaseIndent(); |
| 4612 | pw.decreaseIndent(); |
| 4613 | } |
| 4614 | |
| 4615 | // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to |
| 4616 | // unify the method. |
| 4617 | private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) { |
| 4618 | final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS); |
| 4619 | final ComponentName settingsComponent = settingsIntent.resolveActivity(pm); |
| 4620 | return settingsComponent != null |
| 4621 | ? settingsComponent.getPackageName() : "com.android.settings"; |
| 4622 | } |
| 4623 | |
| 4624 | private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) { |
| 4625 | final String action; |
| 4626 | final boolean highPriority; |
| 4627 | switch (type) { |
| 4628 | case NO_INTERNET: |
| 4629 | action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED; |
| 4630 | // High priority because it is only displayed for explicitly selected networks. |
| 4631 | highPriority = true; |
| 4632 | break; |
| 4633 | case PRIVATE_DNS_BROKEN: |
| 4634 | action = Settings.ACTION_WIRELESS_SETTINGS; |
| 4635 | // High priority because we should let user know why there is no internet. |
| 4636 | highPriority = true; |
| 4637 | break; |
| 4638 | case LOST_INTERNET: |
| 4639 | action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION; |
| 4640 | // High priority because it could help the user avoid unexpected data usage. |
| 4641 | highPriority = true; |
| 4642 | break; |
| 4643 | case PARTIAL_CONNECTIVITY: |
| 4644 | action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY; |
| 4645 | // Don't bother the user with a high-priority notification if the network was not |
| 4646 | // explicitly selected by the user. |
| 4647 | highPriority = nai.networkAgentConfig.explicitlySelected; |
| 4648 | break; |
| 4649 | default: |
| 4650 | Log.wtf(TAG, "Unknown notification type " + type); |
| 4651 | return; |
| 4652 | } |
| 4653 | |
| 4654 | Intent intent = new Intent(action); |
| 4655 | if (type != NotificationType.PRIVATE_DNS_BROKEN) { |
| 4656 | intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network); |
| 4657 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); |
| 4658 | // Some OEMs have their own Settings package. Thus, need to get the current using |
| 4659 | // Settings package name instead of just use default name "com.android.settings". |
| 4660 | final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager()); |
| 4661 | intent.setClassName(settingsPkgName, |
| 4662 | settingsPkgName + ".wifi.WifiNoInternetDialog"); |
| 4663 | } |
| 4664 | |
| 4665 | PendingIntent pendingIntent = PendingIntent.getActivity( |
| 4666 | mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */), |
| 4667 | 0 /* requestCode */, |
| 4668 | intent, |
| 4669 | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE); |
| 4670 | |
| 4671 | mNotifier.showNotification( |
| 4672 | nai.network.getNetId(), type, nai, null, pendingIntent, highPriority); |
| 4673 | } |
| 4674 | |
| 4675 | private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) { |
| 4676 | // Don't prompt if the network is validated, and don't prompt on captive portals |
| 4677 | // because we're already prompting the user to sign in. |
| 4678 | if (nai.everValidated || nai.everCaptivePortalDetected) { |
| 4679 | return false; |
| 4680 | } |
| 4681 | |
| 4682 | // If a network has partial connectivity, always prompt unless the user has already accepted |
| 4683 | // partial connectivity and selected don't ask again. This ensures that if the device |
| 4684 | // automatically connects to a network that has partial Internet access, the user will |
| 4685 | // always be able to use it, either because they've already chosen "don't ask again" or |
| 4686 | // because we have prompt them. |
| 4687 | if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) { |
| 4688 | return true; |
| 4689 | } |
| 4690 | |
| 4691 | // If a network has no Internet access, only prompt if the network was explicitly selected |
| 4692 | // and if the user has not already told us to use the network regardless of whether it |
| 4693 | // validated or not. |
| 4694 | if (nai.networkAgentConfig.explicitlySelected |
| 4695 | && !nai.networkAgentConfig.acceptUnvalidated) { |
| 4696 | return true; |
| 4697 | } |
| 4698 | |
| 4699 | return false; |
| 4700 | } |
| 4701 | |
| 4702 | private void handlePromptUnvalidated(Network network) { |
| 4703 | if (VDBG || DDBG) log("handlePromptUnvalidated " + network); |
| 4704 | NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 4705 | |
| 4706 | if (nai == null || !shouldPromptUnvalidated(nai)) { |
| 4707 | return; |
| 4708 | } |
| 4709 | |
| 4710 | // Stop automatically reconnecting to this network in the future. Automatically connecting |
| 4711 | // to a network that provides no or limited connectivity is not useful, because the user |
| 4712 | // cannot use that network except through the notification shown by this method, and the |
| 4713 | // notification is only shown if the network is explicitly selected by the user. |
| 4714 | nai.onPreventAutomaticReconnect(); |
| 4715 | |
| 4716 | // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when |
| 4717 | // NetworkMonitor detects the network is partial connectivity. Need to change the design to |
| 4718 | // popup the notification immediately when the network is partial connectivity. |
| 4719 | if (nai.partialConnectivity) { |
| 4720 | showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY); |
| 4721 | } else { |
| 4722 | showNetworkNotification(nai, NotificationType.NO_INTERNET); |
| 4723 | } |
| 4724 | } |
| 4725 | |
| 4726 | private void handleNetworkUnvalidated(NetworkAgentInfo nai) { |
| 4727 | NetworkCapabilities nc = nai.networkCapabilities; |
| 4728 | if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc); |
| 4729 | |
| 4730 | if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { |
| 4731 | return; |
| 4732 | } |
| 4733 | |
| 4734 | if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) { |
| 4735 | showNetworkNotification(nai, NotificationType.LOST_INTERNET); |
| 4736 | } |
| 4737 | } |
| 4738 | |
| 4739 | @Override |
| 4740 | public int getMultipathPreference(Network network) { |
| 4741 | enforceAccessPermission(); |
| 4742 | |
| 4743 | NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 4744 | if (nai != null && nai.networkCapabilities |
| 4745 | .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) { |
| 4746 | return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED; |
| 4747 | } |
| 4748 | |
| 4749 | final NetworkPolicyManager netPolicyManager = |
| 4750 | mContext.getSystemService(NetworkPolicyManager.class); |
| 4751 | |
| 4752 | final long token = Binder.clearCallingIdentity(); |
| 4753 | final int networkPreference; |
| 4754 | try { |
| 4755 | networkPreference = netPolicyManager.getMultipathPreference(network); |
| 4756 | } finally { |
| 4757 | Binder.restoreCallingIdentity(token); |
| 4758 | } |
| 4759 | if (networkPreference != 0) { |
| 4760 | return networkPreference; |
| 4761 | } |
| 4762 | return mMultinetworkPolicyTracker.getMeteredMultipathPreference(); |
| 4763 | } |
| 4764 | |
| 4765 | @Override |
| 4766 | public NetworkRequest getDefaultRequest() { |
| 4767 | return mDefaultRequest.mRequests.get(0); |
| 4768 | } |
| 4769 | |
| 4770 | private class InternalHandler extends Handler { |
| 4771 | public InternalHandler(Looper looper) { |
| 4772 | super(looper); |
| 4773 | } |
| 4774 | |
| 4775 | @Override |
| 4776 | public void handleMessage(Message msg) { |
| 4777 | switch (msg.what) { |
| 4778 | case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK: |
| 4779 | case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: { |
| 4780 | handleReleaseNetworkTransitionWakelock(msg.what); |
| 4781 | break; |
| 4782 | } |
| 4783 | case EVENT_APPLY_GLOBAL_HTTP_PROXY: { |
| 4784 | mProxyTracker.loadDeprecatedGlobalHttpProxy(); |
| 4785 | break; |
| 4786 | } |
| 4787 | case EVENT_PROXY_HAS_CHANGED: { |
| 4788 | final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj; |
| 4789 | handleApplyDefaultProxy(arg.second); |
| 4790 | break; |
| 4791 | } |
| 4792 | case EVENT_REGISTER_NETWORK_PROVIDER: { |
| 4793 | handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj); |
| 4794 | break; |
| 4795 | } |
| 4796 | case EVENT_UNREGISTER_NETWORK_PROVIDER: { |
| 4797 | handleUnregisterNetworkProvider((Messenger) msg.obj); |
| 4798 | break; |
| 4799 | } |
| 4800 | case EVENT_REGISTER_NETWORK_OFFER: { |
| 4801 | handleRegisterNetworkOffer((NetworkOffer) msg.obj); |
| 4802 | break; |
| 4803 | } |
| 4804 | case EVENT_UNREGISTER_NETWORK_OFFER: { |
| 4805 | final NetworkOfferInfo offer = |
| 4806 | findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj); |
| 4807 | if (null != offer) { |
| 4808 | handleUnregisterNetworkOffer(offer); |
| 4809 | } |
| 4810 | break; |
| 4811 | } |
| 4812 | case EVENT_REGISTER_NETWORK_AGENT: { |
| 4813 | final Pair<NetworkAgentInfo, INetworkMonitor> arg = |
| 4814 | (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj; |
| 4815 | handleRegisterNetworkAgent(arg.first, arg.second); |
| 4816 | break; |
| 4817 | } |
| 4818 | case EVENT_REGISTER_NETWORK_REQUEST: |
| 4819 | case EVENT_REGISTER_NETWORK_LISTENER: { |
| 4820 | handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj); |
| 4821 | break; |
| 4822 | } |
| 4823 | case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: |
| 4824 | case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: { |
| 4825 | handleRegisterNetworkRequestWithIntent(msg); |
| 4826 | break; |
| 4827 | } |
| 4828 | case EVENT_TIMEOUT_NETWORK_REQUEST: { |
| 4829 | NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj; |
| 4830 | handleTimedOutNetworkRequest(nri); |
| 4831 | break; |
| 4832 | } |
| 4833 | case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: { |
| 4834 | handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1); |
| 4835 | break; |
| 4836 | } |
| 4837 | case EVENT_RELEASE_NETWORK_REQUEST: { |
| 4838 | handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1, |
| 4839 | /* callOnUnavailable */ false); |
| 4840 | break; |
| 4841 | } |
| 4842 | case EVENT_SET_ACCEPT_UNVALIDATED: { |
| 4843 | Network network = (Network) msg.obj; |
| 4844 | handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2)); |
| 4845 | break; |
| 4846 | } |
| 4847 | case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: { |
| 4848 | Network network = (Network) msg.obj; |
| 4849 | handleSetAcceptPartialConnectivity(network, toBool(msg.arg1), |
| 4850 | toBool(msg.arg2)); |
| 4851 | break; |
| 4852 | } |
| 4853 | case EVENT_SET_AVOID_UNVALIDATED: { |
| 4854 | handleSetAvoidUnvalidated((Network) msg.obj); |
| 4855 | break; |
| 4856 | } |
| 4857 | case EVENT_PROMPT_UNVALIDATED: { |
| 4858 | handlePromptUnvalidated((Network) msg.obj); |
| 4859 | break; |
| 4860 | } |
| 4861 | case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: { |
| 4862 | handleConfigureAlwaysOnNetworks(); |
| 4863 | break; |
| 4864 | } |
| 4865 | // Sent by KeepaliveTracker to process an app request on the state machine thread. |
| 4866 | case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: { |
| 4867 | mKeepaliveTracker.handleStartKeepalive(msg); |
| 4868 | break; |
| 4869 | } |
| 4870 | // Sent by KeepaliveTracker to process an app request on the state machine thread. |
| 4871 | case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: { |
| 4872 | NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj); |
| 4873 | int slot = msg.arg1; |
| 4874 | int reason = msg.arg2; |
| 4875 | mKeepaliveTracker.handleStopKeepalive(nai, slot, reason); |
| 4876 | break; |
| 4877 | } |
| 4878 | case EVENT_REVALIDATE_NETWORK: { |
| 4879 | handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2)); |
| 4880 | break; |
| 4881 | } |
| 4882 | case EVENT_PRIVATE_DNS_SETTINGS_CHANGED: |
| 4883 | handlePrivateDnsSettingsChanged(); |
| 4884 | break; |
| 4885 | case EVENT_PRIVATE_DNS_VALIDATION_UPDATE: |
| 4886 | handlePrivateDnsValidationUpdate( |
| 4887 | (PrivateDnsValidationUpdate) msg.obj); |
| 4888 | break; |
| 4889 | case EVENT_UID_BLOCKED_REASON_CHANGED: |
| 4890 | handleUidBlockedReasonChanged(msg.arg1, msg.arg2); |
| 4891 | break; |
| 4892 | case EVENT_SET_REQUIRE_VPN_FOR_UIDS: |
| 4893 | handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj); |
| 4894 | break; |
| 4895 | case EVENT_SET_OEM_NETWORK_PREFERENCE: { |
| 4896 | final Pair<OemNetworkPreferences, IOnCompleteListener> arg = |
| 4897 | (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj; |
| 4898 | handleSetOemNetworkPreference(arg.first, arg.second); |
| 4899 | break; |
| 4900 | } |
| 4901 | case EVENT_SET_PROFILE_NETWORK_PREFERENCE: { |
| 4902 | final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg = |
| 4903 | (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>) |
| 4904 | msg.obj; |
| 4905 | handleSetProfileNetworkPreference(arg.first, arg.second); |
| 4906 | break; |
| 4907 | } |
| 4908 | case EVENT_REPORT_NETWORK_ACTIVITY: |
| 4909 | mNetworkActivityTracker.handleReportNetworkActivity(); |
| 4910 | break; |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 4911 | case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED: |
| 4912 | handleMobileDataPreferredUidsChanged(); |
| 4913 | break; |
Chiachang Wang | fad30e3 | 2021-06-23 02:08:44 +0000 | [diff] [blame] | 4914 | case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL: |
| 4915 | final long timeMs = ((Long) msg.obj).longValue(); |
| 4916 | mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs); |
| 4917 | break; |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 4918 | } |
| 4919 | } |
| 4920 | } |
| 4921 | |
| 4922 | @Override |
| 4923 | @Deprecated |
| 4924 | public int getLastTetherError(String iface) { |
| 4925 | final TetheringManager tm = (TetheringManager) mContext.getSystemService( |
| 4926 | Context.TETHERING_SERVICE); |
| 4927 | return tm.getLastTetherError(iface); |
| 4928 | } |
| 4929 | |
| 4930 | @Override |
| 4931 | @Deprecated |
| 4932 | public String[] getTetherableIfaces() { |
| 4933 | final TetheringManager tm = (TetheringManager) mContext.getSystemService( |
| 4934 | Context.TETHERING_SERVICE); |
| 4935 | return tm.getTetherableIfaces(); |
| 4936 | } |
| 4937 | |
| 4938 | @Override |
| 4939 | @Deprecated |
| 4940 | public String[] getTetheredIfaces() { |
| 4941 | final TetheringManager tm = (TetheringManager) mContext.getSystemService( |
| 4942 | Context.TETHERING_SERVICE); |
| 4943 | return tm.getTetheredIfaces(); |
| 4944 | } |
| 4945 | |
| 4946 | |
| 4947 | @Override |
| 4948 | @Deprecated |
| 4949 | public String[] getTetheringErroredIfaces() { |
| 4950 | final TetheringManager tm = (TetheringManager) mContext.getSystemService( |
| 4951 | Context.TETHERING_SERVICE); |
| 4952 | |
| 4953 | return tm.getTetheringErroredIfaces(); |
| 4954 | } |
| 4955 | |
| 4956 | @Override |
| 4957 | @Deprecated |
| 4958 | public String[] getTetherableUsbRegexs() { |
| 4959 | final TetheringManager tm = (TetheringManager) mContext.getSystemService( |
| 4960 | Context.TETHERING_SERVICE); |
| 4961 | |
| 4962 | return tm.getTetherableUsbRegexs(); |
| 4963 | } |
| 4964 | |
| 4965 | @Override |
| 4966 | @Deprecated |
| 4967 | public String[] getTetherableWifiRegexs() { |
| 4968 | final TetheringManager tm = (TetheringManager) mContext.getSystemService( |
| 4969 | Context.TETHERING_SERVICE); |
| 4970 | return tm.getTetherableWifiRegexs(); |
| 4971 | } |
| 4972 | |
| 4973 | // Called when we lose the default network and have no replacement yet. |
| 4974 | // This will automatically be cleared after X seconds or a new default network |
| 4975 | // becomes CONNECTED, whichever happens first. The timer is started by the |
| 4976 | // first caller and not restarted by subsequent callers. |
| 4977 | private void ensureNetworkTransitionWakelock(String forWhom) { |
| 4978 | synchronized (this) { |
| 4979 | if (mNetTransitionWakeLock.isHeld()) { |
| 4980 | return; |
| 4981 | } |
| 4982 | mNetTransitionWakeLock.acquire(); |
| 4983 | mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime(); |
| 4984 | mTotalWakelockAcquisitions++; |
| 4985 | } |
| 4986 | mWakelockLogs.log("ACQUIRE for " + forWhom); |
| 4987 | Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK); |
| 4988 | final int lockTimeout = mResources.get().getInteger( |
| 4989 | R.integer.config_networkTransitionTimeout); |
| 4990 | mHandler.sendMessageDelayed(msg, lockTimeout); |
| 4991 | } |
| 4992 | |
| 4993 | // Called when we gain a new default network to release the network transition wakelock in a |
| 4994 | // second, to allow a grace period for apps to reconnect over the new network. Pending expiry |
| 4995 | // message is cancelled. |
| 4996 | private void scheduleReleaseNetworkTransitionWakelock() { |
| 4997 | synchronized (this) { |
| 4998 | if (!mNetTransitionWakeLock.isHeld()) { |
| 4999 | return; // expiry message released the lock first. |
| 5000 | } |
| 5001 | } |
| 5002 | // Cancel self timeout on wakelock hold. |
| 5003 | mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK); |
| 5004 | Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK); |
| 5005 | mHandler.sendMessageDelayed(msg, 1000); |
| 5006 | } |
| 5007 | |
| 5008 | // Called when either message of ensureNetworkTransitionWakelock or |
| 5009 | // scheduleReleaseNetworkTransitionWakelock is processed. |
| 5010 | private void handleReleaseNetworkTransitionWakelock(int eventId) { |
| 5011 | String event = eventName(eventId); |
| 5012 | synchronized (this) { |
| 5013 | if (!mNetTransitionWakeLock.isHeld()) { |
| 5014 | mWakelockLogs.log(String.format("RELEASE: already released (%s)", event)); |
| 5015 | Log.w(TAG, "expected Net Transition WakeLock to be held"); |
| 5016 | return; |
| 5017 | } |
| 5018 | mNetTransitionWakeLock.release(); |
| 5019 | long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp; |
| 5020 | mTotalWakelockDurationMs += lockDuration; |
| 5021 | mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration); |
| 5022 | mTotalWakelockReleases++; |
| 5023 | } |
| 5024 | mWakelockLogs.log(String.format("RELEASE (%s)", event)); |
| 5025 | } |
| 5026 | |
| 5027 | // 100 percent is full good, 0 is full bad. |
| 5028 | @Override |
| 5029 | public void reportInetCondition(int networkType, int percentage) { |
| 5030 | NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); |
| 5031 | if (nai == null) return; |
| 5032 | reportNetworkConnectivity(nai.network, percentage > 50); |
| 5033 | } |
| 5034 | |
| 5035 | @Override |
| 5036 | public void reportNetworkConnectivity(Network network, boolean hasConnectivity) { |
| 5037 | enforceAccessPermission(); |
| 5038 | enforceInternetPermission(); |
| 5039 | final int uid = mDeps.getCallingUid(); |
| 5040 | final int connectivityInfo = encodeBool(hasConnectivity); |
| 5041 | |
| 5042 | // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This |
| 5043 | // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity |
| 5044 | // does not match the known connectivity of the network - this causes NetworkMonitor to |
| 5045 | // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event. |
| 5046 | final NetworkAgentInfo nai; |
| 5047 | if (network == null) { |
| 5048 | nai = getDefaultNetwork(); |
| 5049 | } else { |
| 5050 | nai = getNetworkAgentInfoForNetwork(network); |
| 5051 | } |
| 5052 | if (nai != null) { |
| 5053 | mConnectivityDiagnosticsHandler.sendMessage( |
| 5054 | mConnectivityDiagnosticsHandler.obtainMessage( |
| 5055 | ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED, |
| 5056 | connectivityInfo, 0, nai)); |
| 5057 | } |
| 5058 | |
| 5059 | mHandler.sendMessage( |
| 5060 | mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network)); |
| 5061 | } |
| 5062 | |
| 5063 | private void handleReportNetworkConnectivity( |
| 5064 | Network network, int uid, boolean hasConnectivity) { |
| 5065 | final NetworkAgentInfo nai; |
| 5066 | if (network == null) { |
| 5067 | nai = getDefaultNetwork(); |
| 5068 | } else { |
| 5069 | nai = getNetworkAgentInfoForNetwork(network); |
| 5070 | } |
| 5071 | if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING || |
| 5072 | nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) { |
| 5073 | return; |
| 5074 | } |
| 5075 | // Revalidate if the app report does not match our current validated state. |
| 5076 | if (hasConnectivity == nai.lastValidated) { |
| 5077 | return; |
| 5078 | } |
| 5079 | if (DBG) { |
| 5080 | int netid = nai.network.getNetId(); |
| 5081 | log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid); |
| 5082 | } |
| 5083 | // Validating a network that has not yet connected could result in a call to |
| 5084 | // rematchNetworkAndRequests() which is not meant to work on such networks. |
| 5085 | if (!nai.everConnected) { |
| 5086 | return; |
| 5087 | } |
| 5088 | final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai); |
| 5089 | if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) { |
| 5090 | return; |
| 5091 | } |
| 5092 | nai.networkMonitor().forceReevaluation(uid); |
| 5093 | } |
| 5094 | |
| 5095 | // TODO: call into netd. |
| 5096 | private boolean queryUserAccess(int uid, Network network) { |
| 5097 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 5098 | if (nai == null) return false; |
| 5099 | |
| 5100 | // Any UID can use its default network. |
| 5101 | if (nai == getDefaultNetworkForUid(uid)) return true; |
| 5102 | |
| 5103 | // Privileged apps can use any network. |
| 5104 | if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) { |
| 5105 | return true; |
| 5106 | } |
| 5107 | |
| 5108 | // An unprivileged UID can use a VPN iff the VPN applies to it. |
| 5109 | if (nai.isVPN()) { |
| 5110 | return nai.networkCapabilities.appliesToUid(uid); |
| 5111 | } |
| 5112 | |
| 5113 | // An unprivileged UID can bypass the VPN that applies to it only if it can protect its |
| 5114 | // sockets, i.e., if it is the owner. |
| 5115 | final NetworkAgentInfo vpn = getVpnForUid(uid); |
| 5116 | if (vpn != null && !vpn.networkAgentConfig.allowBypass |
| 5117 | && uid != vpn.networkCapabilities.getOwnerUid()) { |
| 5118 | return false; |
| 5119 | } |
| 5120 | |
| 5121 | // The UID's permission must be at least sufficient for the network. Since the restricted |
| 5122 | // permission was already checked above, that just leaves background networks. |
| 5123 | if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) { |
| 5124 | return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid); |
| 5125 | } |
| 5126 | |
| 5127 | // Unrestricted network. Anyone gets to use it. |
| 5128 | return true; |
| 5129 | } |
| 5130 | |
| 5131 | /** |
| 5132 | * Returns information about the proxy a certain network is using. If given a null network, it |
| 5133 | * it will return the proxy for the bound network for the caller app or the default proxy if |
| 5134 | * none. |
| 5135 | * |
| 5136 | * @param network the network we want to get the proxy information for. |
| 5137 | * @return Proxy information if a network has a proxy configured, or otherwise null. |
| 5138 | */ |
| 5139 | @Override |
| 5140 | public ProxyInfo getProxyForNetwork(Network network) { |
| 5141 | final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy(); |
| 5142 | if (globalProxy != null) return globalProxy; |
| 5143 | if (network == null) { |
| 5144 | // Get the network associated with the calling UID. |
| 5145 | final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(), |
| 5146 | true); |
| 5147 | if (activeNetwork == null) { |
| 5148 | return null; |
| 5149 | } |
| 5150 | return getLinkPropertiesProxyInfo(activeNetwork); |
| 5151 | } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) { |
| 5152 | // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which |
| 5153 | // caller may not have. |
| 5154 | return getLinkPropertiesProxyInfo(network); |
| 5155 | } |
| 5156 | // No proxy info available if the calling UID does not have network access. |
| 5157 | return null; |
| 5158 | } |
| 5159 | |
| 5160 | |
| 5161 | private ProxyInfo getLinkPropertiesProxyInfo(Network network) { |
| 5162 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 5163 | if (nai == null) return null; |
| 5164 | synchronized (nai) { |
| 5165 | final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy(); |
| 5166 | return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy); |
| 5167 | } |
| 5168 | } |
| 5169 | |
| 5170 | @Override |
| 5171 | public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) { |
| 5172 | PermissionUtils.enforceNetworkStackPermission(mContext); |
| 5173 | mProxyTracker.setGlobalProxy(proxyProperties); |
| 5174 | } |
| 5175 | |
| 5176 | @Override |
| 5177 | @Nullable |
| 5178 | public ProxyInfo getGlobalProxy() { |
| 5179 | return mProxyTracker.getGlobalProxy(); |
| 5180 | } |
| 5181 | |
| 5182 | private void handleApplyDefaultProxy(ProxyInfo proxy) { |
| 5183 | if (proxy != null && TextUtils.isEmpty(proxy.getHost()) |
| 5184 | && Uri.EMPTY.equals(proxy.getPacFileUrl())) { |
| 5185 | proxy = null; |
| 5186 | } |
| 5187 | mProxyTracker.setDefaultProxy(proxy); |
| 5188 | } |
| 5189 | |
| 5190 | // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called |
| 5191 | // when any network changes proxy. |
| 5192 | // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a |
| 5193 | // multi-network world where an app might be bound to a non-default network. |
| 5194 | private void updateProxy(LinkProperties newLp, LinkProperties oldLp) { |
| 5195 | ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy(); |
| 5196 | ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy(); |
| 5197 | |
| 5198 | if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) { |
| 5199 | mProxyTracker.sendProxyBroadcast(); |
| 5200 | } |
| 5201 | } |
| 5202 | |
| 5203 | private static class SettingsObserver extends ContentObserver { |
| 5204 | final private HashMap<Uri, Integer> mUriEventMap; |
| 5205 | final private Context mContext; |
| 5206 | final private Handler mHandler; |
| 5207 | |
| 5208 | SettingsObserver(Context context, Handler handler) { |
| 5209 | super(null); |
| 5210 | mUriEventMap = new HashMap<>(); |
| 5211 | mContext = context; |
| 5212 | mHandler = handler; |
| 5213 | } |
| 5214 | |
| 5215 | void observe(Uri uri, int what) { |
| 5216 | mUriEventMap.put(uri, what); |
| 5217 | final ContentResolver resolver = mContext.getContentResolver(); |
| 5218 | resolver.registerContentObserver(uri, false, this); |
| 5219 | } |
| 5220 | |
| 5221 | @Override |
| 5222 | public void onChange(boolean selfChange) { |
| 5223 | Log.wtf(TAG, "Should never be reached."); |
| 5224 | } |
| 5225 | |
| 5226 | @Override |
| 5227 | public void onChange(boolean selfChange, Uri uri) { |
| 5228 | final Integer what = mUriEventMap.get(uri); |
| 5229 | if (what != null) { |
| 5230 | mHandler.obtainMessage(what).sendToTarget(); |
| 5231 | } else { |
| 5232 | loge("No matching event to send for URI=" + uri); |
| 5233 | } |
| 5234 | } |
| 5235 | } |
| 5236 | |
| 5237 | private static void log(String s) { |
| 5238 | Log.d(TAG, s); |
| 5239 | } |
| 5240 | |
| 5241 | private static void logw(String s) { |
| 5242 | Log.w(TAG, s); |
| 5243 | } |
| 5244 | |
| 5245 | private static void logwtf(String s) { |
| 5246 | Log.wtf(TAG, s); |
| 5247 | } |
| 5248 | |
| 5249 | private static void logwtf(String s, Throwable t) { |
| 5250 | Log.wtf(TAG, s, t); |
| 5251 | } |
| 5252 | |
| 5253 | private static void loge(String s) { |
| 5254 | Log.e(TAG, s); |
| 5255 | } |
| 5256 | |
| 5257 | private static void loge(String s, Throwable t) { |
| 5258 | Log.e(TAG, s, t); |
| 5259 | } |
| 5260 | |
| 5261 | /** |
| 5262 | * Return the information of all ongoing VPNs. |
| 5263 | * |
| 5264 | * <p>This method is used to update NetworkStatsService. |
| 5265 | * |
| 5266 | * <p>Must be called on the handler thread. |
| 5267 | */ |
| 5268 | private UnderlyingNetworkInfo[] getAllVpnInfo() { |
| 5269 | ensureRunningOnConnectivityServiceThread(); |
| 5270 | if (mLockdownEnabled) { |
| 5271 | return new UnderlyingNetworkInfo[0]; |
| 5272 | } |
| 5273 | List<UnderlyingNetworkInfo> infoList = new ArrayList<>(); |
| 5274 | for (NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 5275 | UnderlyingNetworkInfo info = createVpnInfo(nai); |
| 5276 | if (info != null) { |
| 5277 | infoList.add(info); |
| 5278 | } |
| 5279 | } |
| 5280 | return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]); |
| 5281 | } |
| 5282 | |
| 5283 | /** |
| 5284 | * @return VPN information for accounting, or null if we can't retrieve all required |
| 5285 | * information, e.g underlying ifaces. |
| 5286 | */ |
| 5287 | private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) { |
| 5288 | if (!nai.isVPN()) return null; |
| 5289 | |
| 5290 | Network[] underlyingNetworks = nai.declaredUnderlyingNetworks; |
| 5291 | // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret |
| 5292 | // the underlyingNetworks list. |
| 5293 | if (underlyingNetworks == null) { |
| 5294 | final NetworkAgentInfo defaultNai = getDefaultNetworkForUid( |
| 5295 | nai.networkCapabilities.getOwnerUid()); |
| 5296 | if (defaultNai != null) { |
| 5297 | underlyingNetworks = new Network[] { defaultNai.network }; |
| 5298 | } |
| 5299 | } |
| 5300 | |
| 5301 | if (CollectionUtils.isEmpty(underlyingNetworks)) return null; |
| 5302 | |
| 5303 | List<String> interfaces = new ArrayList<>(); |
| 5304 | for (Network network : underlyingNetworks) { |
| 5305 | NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network); |
| 5306 | if (underlyingNai == null) continue; |
| 5307 | LinkProperties lp = underlyingNai.linkProperties; |
| 5308 | for (String iface : lp.getAllInterfaceNames()) { |
| 5309 | if (!TextUtils.isEmpty(iface)) { |
| 5310 | interfaces.add(iface); |
| 5311 | } |
| 5312 | } |
| 5313 | } |
| 5314 | |
| 5315 | if (interfaces.isEmpty()) return null; |
| 5316 | |
| 5317 | // Must be non-null or NetworkStatsService will crash. |
| 5318 | // Cannot happen in production code because Vpn only registers the NetworkAgent after the |
| 5319 | // tun or ipsec interface is created. |
| 5320 | // TODO: Remove this check. |
| 5321 | if (nai.linkProperties.getInterfaceName() == null) return null; |
| 5322 | |
| 5323 | return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(), |
| 5324 | nai.linkProperties.getInterfaceName(), interfaces); |
| 5325 | } |
| 5326 | |
| 5327 | // TODO This needs to be the default network that applies to the NAI. |
| 5328 | private Network[] underlyingNetworksOrDefault(final int ownerUid, |
| 5329 | Network[] underlyingNetworks) { |
| 5330 | final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid)); |
| 5331 | if (underlyingNetworks == null && defaultNetwork != null) { |
| 5332 | // null underlying networks means to track the default. |
| 5333 | underlyingNetworks = new Network[] { defaultNetwork }; |
| 5334 | } |
| 5335 | return underlyingNetworks; |
| 5336 | } |
| 5337 | |
| 5338 | // Returns true iff |network| is an underlying network of |nai|. |
| 5339 | private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) { |
| 5340 | // TODO: support more than one level of underlying networks, either via a fixed-depth search |
| 5341 | // (e.g., 2 levels of underlying networks), or via loop detection, or.... |
| 5342 | if (!nai.supportsUnderlyingNetworks()) return false; |
| 5343 | final Network[] underlying = underlyingNetworksOrDefault( |
| 5344 | nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks); |
| 5345 | return CollectionUtils.contains(underlying, network); |
| 5346 | } |
| 5347 | |
| 5348 | /** |
| 5349 | * Recompute the capabilities for any networks that had a specific network as underlying. |
| 5350 | * |
| 5351 | * When underlying networks change, such networks may have to update capabilities to reflect |
| 5352 | * things like the metered bit, their transports, and so on. The capabilities are calculated |
| 5353 | * immediately. This method runs on the ConnectivityService thread. |
| 5354 | */ |
| 5355 | private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) { |
| 5356 | ensureRunningOnConnectivityServiceThread(); |
| 5357 | for (NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 5358 | if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) { |
| 5359 | updateCapabilitiesForNetwork(nai); |
| 5360 | } |
| 5361 | } |
| 5362 | } |
| 5363 | |
| 5364 | private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) { |
| 5365 | // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies |
| 5366 | // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when |
| 5367 | // a VPN is not up. |
| 5368 | final NetworkAgentInfo vpnNai = getVpnForUid(uid); |
| 5369 | if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false; |
| 5370 | for (UidRange range : blockedUidRanges) { |
| 5371 | if (range.contains(uid)) return true; |
| 5372 | } |
| 5373 | return false; |
| 5374 | } |
| 5375 | |
| 5376 | @Override |
| 5377 | public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) { |
| 5378 | enforceNetworkStackOrSettingsPermission(); |
| 5379 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS, |
| 5380 | encodeBool(requireVpn), 0 /* arg2 */, ranges)); |
| 5381 | } |
| 5382 | |
| 5383 | private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) { |
| 5384 | if (DBG) { |
| 5385 | Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: " |
| 5386 | + Arrays.toString(ranges)); |
| 5387 | } |
| 5388 | // Cannot use a Set since the list of UID ranges might contain duplicates. |
| 5389 | final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges); |
| 5390 | for (int i = 0; i < ranges.length; i++) { |
| 5391 | if (requireVpn) { |
| 5392 | newVpnBlockedUidRanges.add(ranges[i]); |
| 5393 | } else { |
| 5394 | newVpnBlockedUidRanges.remove(ranges[i]); |
| 5395 | } |
| 5396 | } |
| 5397 | |
| 5398 | try { |
| 5399 | mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges)); |
| 5400 | } catch (RemoteException | ServiceSpecificException e) { |
| 5401 | Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", " |
| 5402 | + Arrays.toString(ranges) + "): netd command failed: " + e); |
| 5403 | } |
| 5404 | |
| 5405 | for (final NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 5406 | final boolean curMetered = nai.networkCapabilities.isMetered(); |
| 5407 | maybeNotifyNetworkBlocked(nai, curMetered, curMetered, |
| 5408 | mVpnBlockedUidRanges, newVpnBlockedUidRanges); |
| 5409 | } |
| 5410 | |
| 5411 | mVpnBlockedUidRanges = newVpnBlockedUidRanges; |
| 5412 | } |
| 5413 | |
| 5414 | @Override |
| 5415 | public void setLegacyLockdownVpnEnabled(boolean enabled) { |
| 5416 | enforceNetworkStackOrSettingsPermission(); |
| 5417 | mHandler.post(() -> mLockdownEnabled = enabled); |
| 5418 | } |
| 5419 | |
| 5420 | private boolean isLegacyLockdownNai(NetworkAgentInfo nai) { |
| 5421 | return mLockdownEnabled |
| 5422 | && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY |
| 5423 | && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID); |
| 5424 | } |
| 5425 | |
| 5426 | private NetworkAgentInfo getLegacyLockdownNai() { |
| 5427 | if (!mLockdownEnabled) { |
| 5428 | return null; |
| 5429 | } |
| 5430 | // The legacy lockdown VPN always only applies to userId 0. |
| 5431 | final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID); |
| 5432 | if (nai == null || !isLegacyLockdownNai(nai)) return null; |
| 5433 | |
| 5434 | // The legacy lockdown VPN must always have exactly one underlying network. |
| 5435 | // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in |
| 5436 | // a local variable. There is no need to make a copy because its contents cannot change. |
| 5437 | final Network[] underlying = nai.declaredUnderlyingNetworks; |
| 5438 | if (underlying == null || underlying.length != 1) { |
| 5439 | return null; |
| 5440 | } |
| 5441 | |
| 5442 | // The legacy lockdown VPN always uses the default network. |
| 5443 | // If the VPN's underlying network is no longer the current default network, it means that |
| 5444 | // the default network has just switched, and the VPN is about to disconnect. |
| 5445 | // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten |
| 5446 | // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED. |
| 5447 | final NetworkAgentInfo defaultNetwork = getDefaultNetwork(); |
| 5448 | if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) { |
| 5449 | return null; |
| 5450 | } |
| 5451 | |
| 5452 | return nai; |
| 5453 | }; |
| 5454 | |
| 5455 | // TODO: move all callers to filterForLegacyLockdown and delete this method. |
| 5456 | // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of |
| 5457 | // just a DetailedState object. |
| 5458 | private DetailedState getLegacyLockdownState(DetailedState origState) { |
| 5459 | if (origState != DetailedState.CONNECTED) { |
| 5460 | return origState; |
| 5461 | } |
| 5462 | return (mLockdownEnabled && getLegacyLockdownNai() == null) |
| 5463 | ? DetailedState.CONNECTING |
| 5464 | : DetailedState.CONNECTED; |
| 5465 | } |
| 5466 | |
| 5467 | private void filterForLegacyLockdown(NetworkInfo ni) { |
| 5468 | if (!mLockdownEnabled || !ni.isConnected()) return; |
| 5469 | // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the |
| 5470 | // state of its VPN. This is to ensure that when an underlying network connects, apps will |
| 5471 | // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN |
| 5472 | // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying |
| 5473 | // network, this time with a state of CONNECTED. |
| 5474 | // |
| 5475 | // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access |
| 5476 | // to the internal state of the Vpn object, always replace the state with CONNECTING. This |
| 5477 | // is not too far off the truth, since an always-on VPN, when not connected, is always |
| 5478 | // trying to reconnect. |
| 5479 | if (getLegacyLockdownNai() == null) { |
| 5480 | ni.setDetailedState(DetailedState.CONNECTING, "", null); |
| 5481 | } |
| 5482 | } |
| 5483 | |
| 5484 | @Override |
| 5485 | public void setProvisioningNotificationVisible(boolean visible, int networkType, |
| 5486 | String action) { |
| 5487 | enforceSettingsPermission(); |
| 5488 | if (!ConnectivityManager.isNetworkTypeValid(networkType)) { |
| 5489 | return; |
| 5490 | } |
| 5491 | final long ident = Binder.clearCallingIdentity(); |
| 5492 | try { |
| 5493 | // Concatenate the range of types onto the range of NetIDs. |
| 5494 | int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE); |
| 5495 | mNotifier.setProvNotificationVisible(visible, id, action); |
| 5496 | } finally { |
| 5497 | Binder.restoreCallingIdentity(ident); |
| 5498 | } |
| 5499 | } |
| 5500 | |
| 5501 | @Override |
| 5502 | public void setAirplaneMode(boolean enable) { |
| 5503 | enforceAirplaneModePermission(); |
| 5504 | final long ident = Binder.clearCallingIdentity(); |
| 5505 | try { |
| 5506 | final ContentResolver cr = mContext.getContentResolver(); |
| 5507 | Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable)); |
| 5508 | Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); |
| 5509 | intent.putExtra("state", enable); |
| 5510 | mContext.sendBroadcastAsUser(intent, UserHandle.ALL); |
| 5511 | } finally { |
| 5512 | Binder.restoreCallingIdentity(ident); |
| 5513 | } |
| 5514 | } |
| 5515 | |
| 5516 | private void onUserAdded(@NonNull final UserHandle user) { |
| 5517 | mPermissionMonitor.onUserAdded(user); |
| 5518 | if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) { |
| 5519 | handleSetOemNetworkPreference(mOemNetworkPreferences, null); |
| 5520 | } |
| 5521 | } |
| 5522 | |
| 5523 | private void onUserRemoved(@NonNull final UserHandle user) { |
| 5524 | mPermissionMonitor.onUserRemoved(user); |
| 5525 | // If there was a network preference for this user, remove it. |
| 5526 | handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null), |
| 5527 | null /* listener */); |
| 5528 | if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) { |
| 5529 | handleSetOemNetworkPreference(mOemNetworkPreferences, null); |
| 5530 | } |
| 5531 | } |
| 5532 | |
| 5533 | private void onPackageChanged(@NonNull final String packageName) { |
| 5534 | // This is necessary in case a package is added or removed, but also when it's replaced to |
| 5535 | // run as a new UID by its manifest rules. Also, if a separate package shares the same UID |
| 5536 | // as one in the preferences, then it should follow the same routing as that other package, |
| 5537 | // which means updating the rules is never to be needed in this case (whether it joins or |
| 5538 | // leaves a UID with a preference). |
| 5539 | if (isMappedInOemNetworkPreference(packageName)) { |
| 5540 | handleSetOemNetworkPreference(mOemNetworkPreferences, null); |
| 5541 | } |
| 5542 | } |
| 5543 | |
| 5544 | private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() { |
| 5545 | @Override |
| 5546 | public void onReceive(Context context, Intent intent) { |
| 5547 | ensureRunningOnConnectivityServiceThread(); |
| 5548 | final String action = intent.getAction(); |
| 5549 | final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER); |
| 5550 | |
| 5551 | // User should be filled for below intents, check the existence. |
| 5552 | if (user == null) { |
| 5553 | Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER"); |
| 5554 | return; |
| 5555 | } |
| 5556 | |
| 5557 | if (Intent.ACTION_USER_ADDED.equals(action)) { |
| 5558 | onUserAdded(user); |
| 5559 | } else if (Intent.ACTION_USER_REMOVED.equals(action)) { |
| 5560 | onUserRemoved(user); |
| 5561 | } else { |
| 5562 | Log.wtf(TAG, "received unexpected intent: " + action); |
| 5563 | } |
| 5564 | } |
| 5565 | }; |
| 5566 | |
| 5567 | private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() { |
| 5568 | @Override |
| 5569 | public void onReceive(Context context, Intent intent) { |
| 5570 | ensureRunningOnConnectivityServiceThread(); |
| 5571 | switch (intent.getAction()) { |
| 5572 | case Intent.ACTION_PACKAGE_ADDED: |
| 5573 | case Intent.ACTION_PACKAGE_REMOVED: |
| 5574 | case Intent.ACTION_PACKAGE_REPLACED: |
| 5575 | onPackageChanged(intent.getData().getSchemeSpecificPart()); |
| 5576 | break; |
| 5577 | default: |
| 5578 | Log.wtf(TAG, "received unexpected intent: " + intent.getAction()); |
| 5579 | } |
| 5580 | } |
| 5581 | }; |
| 5582 | |
| 5583 | private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>(); |
| 5584 | private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>(); |
| 5585 | |
| 5586 | private static class NetworkProviderInfo { |
| 5587 | public final String name; |
| 5588 | public final Messenger messenger; |
| 5589 | private final IBinder.DeathRecipient mDeathRecipient; |
| 5590 | public final int providerId; |
| 5591 | |
| 5592 | NetworkProviderInfo(String name, Messenger messenger, int providerId, |
| 5593 | @NonNull IBinder.DeathRecipient deathRecipient) { |
| 5594 | this.name = name; |
| 5595 | this.messenger = messenger; |
| 5596 | this.providerId = providerId; |
| 5597 | mDeathRecipient = deathRecipient; |
| 5598 | |
| 5599 | if (mDeathRecipient == null) { |
| 5600 | throw new AssertionError("Must pass a deathRecipient"); |
| 5601 | } |
| 5602 | } |
| 5603 | |
| 5604 | void connect(Context context, Handler handler) { |
| 5605 | try { |
| 5606 | messenger.getBinder().linkToDeath(mDeathRecipient, 0); |
| 5607 | } catch (RemoteException e) { |
| 5608 | mDeathRecipient.binderDied(); |
| 5609 | } |
| 5610 | } |
| 5611 | } |
| 5612 | |
| 5613 | private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) { |
| 5614 | for (int i = 0; i < requests.size(); i++) { |
| 5615 | ensureNetworkRequestHasType(requests.get(i)); |
| 5616 | } |
| 5617 | } |
| 5618 | |
| 5619 | private void ensureNetworkRequestHasType(NetworkRequest request) { |
| 5620 | if (request.type == NetworkRequest.Type.NONE) { |
| 5621 | throw new IllegalArgumentException( |
| 5622 | "All NetworkRequests in ConnectivityService must have a type"); |
| 5623 | } |
| 5624 | } |
| 5625 | |
| 5626 | /** |
| 5627 | * Tracks info about the requester. |
| 5628 | * Also used to notice when the calling process dies so as to self-expire |
| 5629 | */ |
| 5630 | @VisibleForTesting |
| 5631 | protected class NetworkRequestInfo implements IBinder.DeathRecipient { |
| 5632 | // The requests to be satisfied in priority order. Non-multilayer requests will only have a |
| 5633 | // single NetworkRequest in mRequests. |
| 5634 | final List<NetworkRequest> mRequests; |
| 5635 | |
| 5636 | // mSatisfier and mActiveRequest rely on one another therefore set them together. |
| 5637 | void setSatisfier( |
| 5638 | @Nullable final NetworkAgentInfo satisfier, |
| 5639 | @Nullable final NetworkRequest activeRequest) { |
| 5640 | mSatisfier = satisfier; |
| 5641 | mActiveRequest = activeRequest; |
| 5642 | } |
| 5643 | |
| 5644 | // The network currently satisfying this NRI. Only one request in an NRI can have a |
| 5645 | // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier. |
| 5646 | @Nullable |
| 5647 | private NetworkAgentInfo mSatisfier; |
| 5648 | NetworkAgentInfo getSatisfier() { |
| 5649 | return mSatisfier; |
| 5650 | } |
| 5651 | |
| 5652 | // The request in mRequests assigned to a network agent. This is null if none of the |
| 5653 | // requests in mRequests can be satisfied. This member has the constraint of only being |
| 5654 | // accessible on the handler thread. |
| 5655 | @Nullable |
| 5656 | private NetworkRequest mActiveRequest; |
| 5657 | NetworkRequest getActiveRequest() { |
| 5658 | return mActiveRequest; |
| 5659 | } |
| 5660 | |
| 5661 | final PendingIntent mPendingIntent; |
| 5662 | boolean mPendingIntentSent; |
| 5663 | @Nullable |
| 5664 | final Messenger mMessenger; |
| 5665 | |
| 5666 | // Information about the caller that caused this object to be created. |
| 5667 | @Nullable |
| 5668 | private final IBinder mBinder; |
| 5669 | final int mPid; |
| 5670 | final int mUid; |
| 5671 | final @NetworkCallback.Flag int mCallbackFlags; |
| 5672 | @Nullable |
| 5673 | final String mCallingAttributionTag; |
| 5674 | |
| 5675 | // Counter keeping track of this NRI. |
| 5676 | final PerUidCounter mPerUidCounter; |
| 5677 | |
| 5678 | // Effective UID of this request. This is different from mUid when a privileged process |
| 5679 | // files a request on behalf of another UID. This UID is used to determine blocked status, |
| 5680 | // UID matching, and so on. mUid above is used for permission checks and to enforce the |
| 5681 | // maximum limit of registered callbacks per UID. |
| 5682 | final int mAsUid; |
| 5683 | |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 5684 | // Default network priority of this request. |
| 5685 | private final int mDefaultNetworkPriority; |
| 5686 | |
| 5687 | int getDefaultNetworkPriority() { |
| 5688 | return mDefaultNetworkPriority; |
| 5689 | } |
| 5690 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 5691 | // In order to preserve the mapping of NetworkRequest-to-callback when apps register |
| 5692 | // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be |
| 5693 | // maintained for keying off of. This is only a concern when the original nri |
| 5694 | // mNetworkRequests changes which happens currently for apps that register callbacks to |
| 5695 | // track the default network. In those cases, the nri is updated to have mNetworkRequests |
| 5696 | // that match the per-app default nri that currently tracks the calling app's uid so that |
| 5697 | // callbacks are fired at the appropriate time. When the callbacks fire, |
| 5698 | // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When |
| 5699 | // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue. |
| 5700 | // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects. |
| 5701 | @NonNull |
| 5702 | private final NetworkRequest mNetworkRequestForCallback; |
| 5703 | NetworkRequest getNetworkRequestForCallback() { |
| 5704 | return mNetworkRequestForCallback; |
| 5705 | } |
| 5706 | |
| 5707 | /** |
| 5708 | * Get the list of UIDs this nri applies to. |
| 5709 | */ |
| 5710 | @NonNull |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 5711 | Set<UidRange> getUids() { |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 5712 | // networkCapabilities.getUids() returns a defensive copy. |
| 5713 | // multilayer requests will all have the same uids so return the first one. |
| 5714 | final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges(); |
| 5715 | return (null == uids) ? new ArraySet<>() : uids; |
| 5716 | } |
| 5717 | |
| 5718 | NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, |
| 5719 | @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) { |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 5720 | this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag, |
| 5721 | DEFAULT_NETWORK_PRIORITY_NONE); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 5722 | } |
| 5723 | |
| 5724 | NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r, |
| 5725 | @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi, |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 5726 | @Nullable String callingAttributionTag, final int defaultNetworkPriority) { |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 5727 | ensureAllNetworkRequestsHaveType(r); |
| 5728 | mRequests = initializeRequests(r); |
| 5729 | mNetworkRequestForCallback = requestForCallback; |
| 5730 | mPendingIntent = pi; |
| 5731 | mMessenger = null; |
| 5732 | mBinder = null; |
| 5733 | mPid = getCallingPid(); |
| 5734 | mUid = mDeps.getCallingUid(); |
| 5735 | mAsUid = asUid; |
| 5736 | mPerUidCounter = getRequestCounter(this); |
| 5737 | mPerUidCounter.incrementCountOrThrow(mUid); |
| 5738 | /** |
| 5739 | * Location sensitive data not included in pending intent. Only included in |
| 5740 | * {@link NetworkCallback}. |
| 5741 | */ |
| 5742 | mCallbackFlags = NetworkCallback.FLAG_NONE; |
| 5743 | mCallingAttributionTag = callingAttributionTag; |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 5744 | mDefaultNetworkPriority = defaultNetworkPriority; |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 5745 | } |
| 5746 | |
| 5747 | NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m, |
| 5748 | @Nullable final IBinder binder, |
| 5749 | @NetworkCallback.Flag int callbackFlags, |
| 5750 | @Nullable String callingAttributionTag) { |
| 5751 | this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags, |
| 5752 | callingAttributionTag); |
| 5753 | } |
| 5754 | |
| 5755 | NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r, |
| 5756 | @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m, |
| 5757 | @Nullable final IBinder binder, |
| 5758 | @NetworkCallback.Flag int callbackFlags, |
| 5759 | @Nullable String callingAttributionTag) { |
| 5760 | super(); |
| 5761 | ensureAllNetworkRequestsHaveType(r); |
| 5762 | mRequests = initializeRequests(r); |
| 5763 | mNetworkRequestForCallback = requestForCallback; |
| 5764 | mMessenger = m; |
| 5765 | mBinder = binder; |
| 5766 | mPid = getCallingPid(); |
| 5767 | mUid = mDeps.getCallingUid(); |
| 5768 | mAsUid = asUid; |
| 5769 | mPendingIntent = null; |
| 5770 | mPerUidCounter = getRequestCounter(this); |
| 5771 | mPerUidCounter.incrementCountOrThrow(mUid); |
| 5772 | mCallbackFlags = callbackFlags; |
| 5773 | mCallingAttributionTag = callingAttributionTag; |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 5774 | mDefaultNetworkPriority = DEFAULT_NETWORK_PRIORITY_NONE; |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 5775 | linkDeathRecipient(); |
| 5776 | } |
| 5777 | |
| 5778 | NetworkRequestInfo(@NonNull final NetworkRequestInfo nri, |
| 5779 | @NonNull final List<NetworkRequest> r) { |
| 5780 | super(); |
| 5781 | ensureAllNetworkRequestsHaveType(r); |
| 5782 | mRequests = initializeRequests(r); |
| 5783 | mNetworkRequestForCallback = nri.getNetworkRequestForCallback(); |
| 5784 | final NetworkAgentInfo satisfier = nri.getSatisfier(); |
| 5785 | if (null != satisfier) { |
| 5786 | // If the old NRI was satisfied by an NAI, then it may have had an active request. |
| 5787 | // The active request is necessary to figure out what callbacks to send, in |
| 5788 | // particular then a network updates its capabilities. |
| 5789 | // As this code creates a new NRI with a new set of requests, figure out which of |
| 5790 | // the list of requests should be the active request. It is always the first |
| 5791 | // request of the list that can be satisfied by the satisfier since the order of |
| 5792 | // requests is a priority order. |
| 5793 | // Note even in the presence of a satisfier there may not be an active request, |
| 5794 | // when the satisfier is the no-service network. |
| 5795 | NetworkRequest activeRequest = null; |
| 5796 | for (final NetworkRequest candidate : r) { |
| 5797 | if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) { |
| 5798 | activeRequest = candidate; |
| 5799 | break; |
| 5800 | } |
| 5801 | } |
| 5802 | setSatisfier(satisfier, activeRequest); |
| 5803 | } |
| 5804 | mMessenger = nri.mMessenger; |
| 5805 | mBinder = nri.mBinder; |
| 5806 | mPid = nri.mPid; |
| 5807 | mUid = nri.mUid; |
| 5808 | mAsUid = nri.mAsUid; |
| 5809 | mPendingIntent = nri.mPendingIntent; |
| 5810 | mPerUidCounter = getRequestCounter(this); |
| 5811 | mPerUidCounter.incrementCountOrThrow(mUid); |
| 5812 | mCallbackFlags = nri.mCallbackFlags; |
| 5813 | mCallingAttributionTag = nri.mCallingAttributionTag; |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 5814 | mDefaultNetworkPriority = DEFAULT_NETWORK_PRIORITY_NONE; |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 5815 | linkDeathRecipient(); |
| 5816 | } |
| 5817 | |
| 5818 | NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) { |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 5819 | this(asUid, Collections.singletonList(r), DEFAULT_NETWORK_PRIORITY_NONE); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 5820 | } |
| 5821 | |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 5822 | NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r, |
| 5823 | final int defaultNetworkPriority) { |
| 5824 | this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */, |
| 5825 | defaultNetworkPriority); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 5826 | } |
| 5827 | |
| 5828 | // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer |
| 5829 | // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning |
| 5830 | // false. |
| 5831 | boolean isBeingSatisfied() { |
| 5832 | return (null != mSatisfier && null != mActiveRequest); |
| 5833 | } |
| 5834 | |
| 5835 | boolean isMultilayerRequest() { |
| 5836 | return mRequests.size() > 1; |
| 5837 | } |
| 5838 | |
| 5839 | private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) { |
| 5840 | // Creating a defensive copy to prevent the sender from modifying the list being |
| 5841 | // reflected in the return value of this method. |
| 5842 | final List<NetworkRequest> tempRequests = new ArrayList<>(r); |
| 5843 | return Collections.unmodifiableList(tempRequests); |
| 5844 | } |
| 5845 | |
| 5846 | void decrementRequestCount() { |
| 5847 | mPerUidCounter.decrementCount(mUid); |
| 5848 | } |
| 5849 | |
| 5850 | void linkDeathRecipient() { |
| 5851 | if (null != mBinder) { |
| 5852 | try { |
| 5853 | mBinder.linkToDeath(this, 0); |
| 5854 | } catch (RemoteException e) { |
| 5855 | binderDied(); |
| 5856 | } |
| 5857 | } |
| 5858 | } |
| 5859 | |
| 5860 | void unlinkDeathRecipient() { |
| 5861 | if (null != mBinder) { |
| 5862 | mBinder.unlinkToDeath(this, 0); |
| 5863 | } |
| 5864 | } |
| 5865 | |
| 5866 | @Override |
| 5867 | public void binderDied() { |
| 5868 | log("ConnectivityService NetworkRequestInfo binderDied(" + |
| 5869 | mRequests + ", " + mBinder + ")"); |
| 5870 | releaseNetworkRequests(mRequests); |
| 5871 | } |
| 5872 | |
| 5873 | @Override |
| 5874 | public String toString() { |
| 5875 | final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid; |
| 5876 | return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: " |
| 5877 | + (mActiveRequest == null ? null : mActiveRequest.requestId) |
| 5878 | + " callbackRequest: " |
| 5879 | + mNetworkRequestForCallback.requestId |
| 5880 | + " " + mRequests |
| 5881 | + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent) |
| 5882 | + " callback flags: " + mCallbackFlags; |
| 5883 | } |
| 5884 | } |
| 5885 | |
| 5886 | private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) { |
| 5887 | final String badCapability = networkCapabilities.describeFirstNonRequestableCapability(); |
| 5888 | if (badCapability != null) { |
| 5889 | throw new IllegalArgumentException("Cannot request network with " + badCapability); |
| 5890 | } |
| 5891 | } |
| 5892 | |
| 5893 | // This checks that the passed capabilities either do not request a |
| 5894 | // specific SSID/SignalStrength, or the calling app has permission to do so. |
| 5895 | private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc, |
| 5896 | int callerPid, int callerUid, String callerPackageName) { |
| 5897 | if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) { |
| 5898 | throw new SecurityException("Insufficient permissions to request a specific SSID"); |
| 5899 | } |
| 5900 | |
| 5901 | if (nc.hasSignalStrength() |
| 5902 | && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) { |
| 5903 | throw new SecurityException( |
| 5904 | "Insufficient permissions to request a specific signal strength"); |
| 5905 | } |
| 5906 | mAppOpsManager.checkPackage(callerUid, callerPackageName); |
| 5907 | |
| 5908 | if (!nc.getSubscriptionIds().isEmpty()) { |
| 5909 | enforceNetworkFactoryPermission(); |
| 5910 | } |
| 5911 | } |
| 5912 | |
| 5913 | private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) { |
| 5914 | final SortedSet<Integer> thresholds = new TreeSet<>(); |
| 5915 | synchronized (nai) { |
| 5916 | // mNetworkRequests may contain the same value multiple times in case of |
| 5917 | // multilayer requests. It won't matter in this case because the thresholds |
| 5918 | // will then be the same and be deduplicated as they enter the `thresholds` set. |
| 5919 | // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like. |
| 5920 | for (final NetworkRequestInfo nri : mNetworkRequests.values()) { |
| 5921 | for (final NetworkRequest req : nri.mRequests) { |
| 5922 | if (req.networkCapabilities.hasSignalStrength() |
| 5923 | && nai.satisfiesImmutableCapabilitiesOf(req)) { |
| 5924 | thresholds.add(req.networkCapabilities.getSignalStrength()); |
| 5925 | } |
| 5926 | } |
| 5927 | } |
| 5928 | } |
| 5929 | return CollectionUtils.toIntArray(new ArrayList<>(thresholds)); |
| 5930 | } |
| 5931 | |
| 5932 | private void updateSignalStrengthThresholds( |
| 5933 | NetworkAgentInfo nai, String reason, NetworkRequest request) { |
| 5934 | final int[] thresholdsArray = getSignalStrengthThresholds(nai); |
| 5935 | |
| 5936 | if (VDBG || (DBG && !"CONNECT".equals(reason))) { |
| 5937 | String detail; |
| 5938 | if (request != null && request.networkCapabilities.hasSignalStrength()) { |
| 5939 | detail = reason + " " + request.networkCapabilities.getSignalStrength(); |
| 5940 | } else { |
| 5941 | detail = reason; |
| 5942 | } |
| 5943 | log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s", |
| 5944 | detail, Arrays.toString(thresholdsArray), nai.toShortString())); |
| 5945 | } |
| 5946 | |
| 5947 | nai.onSignalStrengthThresholdsUpdated(thresholdsArray); |
| 5948 | } |
| 5949 | |
| 5950 | private void ensureValidNetworkSpecifier(NetworkCapabilities nc) { |
| 5951 | if (nc == null) { |
| 5952 | return; |
| 5953 | } |
| 5954 | NetworkSpecifier ns = nc.getNetworkSpecifier(); |
| 5955 | if (ns == null) { |
| 5956 | return; |
| 5957 | } |
| 5958 | if (ns instanceof MatchAllNetworkSpecifier) { |
| 5959 | throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted"); |
| 5960 | } |
| 5961 | } |
| 5962 | |
| 5963 | private void ensureValid(NetworkCapabilities nc) { |
| 5964 | ensureValidNetworkSpecifier(nc); |
| 5965 | if (nc.isPrivateDnsBroken()) { |
| 5966 | throw new IllegalArgumentException("Can't request broken private DNS"); |
| 5967 | } |
| 5968 | } |
| 5969 | |
| 5970 | private boolean isTargetSdkAtleast(int version, int callingUid, |
| 5971 | @NonNull String callingPackageName) { |
| 5972 | final UserHandle user = UserHandle.getUserHandleForUid(callingUid); |
| 5973 | final PackageManager pm = |
| 5974 | mContext.createContextAsUser(user, 0 /* flags */).getPackageManager(); |
| 5975 | try { |
| 5976 | final int callingVersion = pm.getTargetSdkVersion(callingPackageName); |
| 5977 | if (callingVersion < version) return false; |
| 5978 | } catch (PackageManager.NameNotFoundException e) { } |
| 5979 | return true; |
| 5980 | } |
| 5981 | |
| 5982 | @Override |
| 5983 | public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities, |
| 5984 | int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder, |
| 5985 | int legacyType, int callbackFlags, @NonNull String callingPackageName, |
| 5986 | @Nullable String callingAttributionTag) { |
| 5987 | if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) { |
| 5988 | if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(), |
| 5989 | callingPackageName)) { |
| 5990 | throw new SecurityException("Insufficient permissions to specify legacy type"); |
| 5991 | } |
| 5992 | } |
| 5993 | final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities; |
| 5994 | final int callingUid = mDeps.getCallingUid(); |
| 5995 | // Privileged callers can track the default network of another UID by passing in a UID. |
| 5996 | if (asUid != Process.INVALID_UID) { |
| 5997 | enforceSettingsPermission(); |
| 5998 | } else { |
| 5999 | asUid = callingUid; |
| 6000 | } |
| 6001 | final NetworkRequest.Type reqType; |
| 6002 | try { |
| 6003 | reqType = NetworkRequest.Type.values()[reqTypeInt]; |
| 6004 | } catch (ArrayIndexOutOfBoundsException e) { |
| 6005 | throw new IllegalArgumentException("Unsupported request type " + reqTypeInt); |
| 6006 | } |
| 6007 | switch (reqType) { |
| 6008 | case TRACK_DEFAULT: |
| 6009 | // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities} |
| 6010 | // is unused and will be replaced by ones appropriate for the UID (usually, the |
| 6011 | // calling app). This allows callers to keep track of the default network. |
| 6012 | networkCapabilities = copyDefaultNetworkCapabilitiesForUid( |
| 6013 | defaultNc, asUid, callingUid, callingPackageName); |
| 6014 | enforceAccessPermission(); |
| 6015 | break; |
| 6016 | case TRACK_SYSTEM_DEFAULT: |
| 6017 | enforceSettingsPermission(); |
| 6018 | networkCapabilities = new NetworkCapabilities(defaultNc); |
| 6019 | break; |
| 6020 | case BACKGROUND_REQUEST: |
| 6021 | enforceNetworkStackOrSettingsPermission(); |
| 6022 | // Fall-through since other checks are the same with normal requests. |
| 6023 | case REQUEST: |
| 6024 | networkCapabilities = new NetworkCapabilities(networkCapabilities); |
| 6025 | enforceNetworkRequestPermissions(networkCapabilities, callingPackageName, |
| 6026 | callingAttributionTag); |
| 6027 | // TODO: this is incorrect. We mark the request as metered or not depending on |
| 6028 | // the state of the app when the request is filed, but we never change the |
| 6029 | // request if the app changes network state. http://b/29964605 |
| 6030 | enforceMeteredApnPolicy(networkCapabilities); |
| 6031 | break; |
| 6032 | case LISTEN_FOR_BEST: |
| 6033 | enforceAccessPermission(); |
| 6034 | networkCapabilities = new NetworkCapabilities(networkCapabilities); |
| 6035 | break; |
| 6036 | default: |
| 6037 | throw new IllegalArgumentException("Unsupported request type " + reqType); |
| 6038 | } |
| 6039 | ensureRequestableCapabilities(networkCapabilities); |
| 6040 | ensureSufficientPermissionsForRequest(networkCapabilities, |
| 6041 | Binder.getCallingPid(), callingUid, callingPackageName); |
| 6042 | |
| 6043 | // Enforce FOREGROUND if the caller does not have permission to use background network. |
| 6044 | if (reqType == LISTEN_FOR_BEST) { |
| 6045 | restrictBackgroundRequestForCaller(networkCapabilities); |
| 6046 | } |
| 6047 | |
| 6048 | // Set the UID range for this request to the single UID of the requester, unless the |
| 6049 | // requester has the permission to specify other UIDs. |
| 6050 | // This will overwrite any allowed UIDs in the requested capabilities. Though there |
| 6051 | // are no visible methods to set the UIDs, an app could use reflection to try and get |
| 6052 | // networks for other apps so it's essential that the UIDs are overwritten. |
| 6053 | // Also set the requester UID and package name in the request. |
| 6054 | restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities, |
| 6055 | callingUid, callingPackageName); |
| 6056 | |
| 6057 | if (timeoutMs < 0) { |
| 6058 | throw new IllegalArgumentException("Bad timeout specified"); |
| 6059 | } |
| 6060 | ensureValid(networkCapabilities); |
| 6061 | |
| 6062 | final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType, |
| 6063 | nextNetworkRequestId(), reqType); |
| 6064 | final NetworkRequestInfo nri = getNriToRegister( |
| 6065 | asUid, networkRequest, messenger, binder, callbackFlags, |
| 6066 | callingAttributionTag); |
| 6067 | if (DBG) log("requestNetwork for " + nri); |
| 6068 | |
| 6069 | // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were |
| 6070 | // copied from the default request above. (This is necessary to ensure, for example, that |
| 6071 | // the callback does not leak sensitive information to unprivileged apps.) Check that the |
| 6072 | // changes don't alter request matching. |
| 6073 | if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT && |
| 6074 | (!networkCapabilities.equalRequestableCapabilities(defaultNc))) { |
| 6075 | throw new IllegalStateException( |
| 6076 | "TRACK_SYSTEM_DEFAULT capabilities don't match default request: " |
| 6077 | + networkCapabilities + " vs. " + defaultNc); |
| 6078 | } |
| 6079 | |
| 6080 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri)); |
| 6081 | if (timeoutMs > 0) { |
| 6082 | mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST, |
| 6083 | nri), timeoutMs); |
| 6084 | } |
| 6085 | return networkRequest; |
| 6086 | } |
| 6087 | |
| 6088 | /** |
| 6089 | * Return the nri to be used when registering a network request. Specifically, this is used with |
| 6090 | * requests registered to track the default request. If there is currently a per-app default |
| 6091 | * tracking the app requestor, then we need to create a version of this nri that mirrors that of |
| 6092 | * the tracking per-app default so that callbacks are sent to the app requestor appropriately. |
| 6093 | * @param asUid the uid on behalf of which to file the request. Different from requestorUid |
| 6094 | * when a privileged caller is tracking the default network for another uid. |
| 6095 | * @param nr the network request for the nri. |
| 6096 | * @param msgr the messenger for the nri. |
| 6097 | * @param binder the binder for the nri. |
| 6098 | * @param callingAttributionTag the calling attribution tag for the nri. |
| 6099 | * @return the nri to register. |
| 6100 | */ |
| 6101 | private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr, |
| 6102 | @Nullable final Messenger msgr, @Nullable final IBinder binder, |
| 6103 | @NetworkCallback.Flag int callbackFlags, |
| 6104 | @Nullable String callingAttributionTag) { |
| 6105 | final List<NetworkRequest> requests; |
| 6106 | if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) { |
| 6107 | requests = copyDefaultNetworkRequestsForUid( |
| 6108 | asUid, nr.getRequestorUid(), nr.getRequestorPackageName()); |
| 6109 | } else { |
| 6110 | requests = Collections.singletonList(nr); |
| 6111 | } |
| 6112 | return new NetworkRequestInfo( |
| 6113 | asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag); |
| 6114 | } |
| 6115 | |
| 6116 | private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities, |
| 6117 | String callingPackageName, String callingAttributionTag) { |
| 6118 | if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) { |
| 6119 | enforceConnectivityRestrictedNetworksPermission(); |
| 6120 | } else { |
| 6121 | enforceChangePermission(callingPackageName, callingAttributionTag); |
| 6122 | } |
| 6123 | } |
| 6124 | |
| 6125 | @Override |
| 6126 | public boolean requestBandwidthUpdate(Network network) { |
| 6127 | enforceAccessPermission(); |
| 6128 | NetworkAgentInfo nai = null; |
| 6129 | if (network == null) { |
| 6130 | return false; |
| 6131 | } |
| 6132 | synchronized (mNetworkForNetId) { |
| 6133 | nai = mNetworkForNetId.get(network.getNetId()); |
| 6134 | } |
| 6135 | if (nai != null) { |
| 6136 | nai.onBandwidthUpdateRequested(); |
| 6137 | synchronized (mBandwidthRequests) { |
| 6138 | final int uid = mDeps.getCallingUid(); |
| 6139 | Integer uidReqs = mBandwidthRequests.get(uid); |
| 6140 | if (uidReqs == null) { |
| 6141 | uidReqs = 0; |
| 6142 | } |
| 6143 | mBandwidthRequests.put(uid, ++uidReqs); |
| 6144 | } |
| 6145 | return true; |
| 6146 | } |
| 6147 | return false; |
| 6148 | } |
| 6149 | |
| 6150 | private boolean isSystem(int uid) { |
| 6151 | return uid < Process.FIRST_APPLICATION_UID; |
| 6152 | } |
| 6153 | |
| 6154 | private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) { |
| 6155 | final int uid = mDeps.getCallingUid(); |
| 6156 | if (isSystem(uid)) { |
| 6157 | // Exemption for system uid. |
| 6158 | return; |
| 6159 | } |
| 6160 | if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) { |
| 6161 | // Policy already enforced. |
| 6162 | return; |
| 6163 | } |
| 6164 | final long ident = Binder.clearCallingIdentity(); |
| 6165 | try { |
| 6166 | if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) { |
| 6167 | // If UID is restricted, don't allow them to bring up metered APNs. |
| 6168 | networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED); |
| 6169 | } |
| 6170 | } finally { |
| 6171 | Binder.restoreCallingIdentity(ident); |
| 6172 | } |
| 6173 | } |
| 6174 | |
| 6175 | @Override |
| 6176 | public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities, |
| 6177 | PendingIntent operation, @NonNull String callingPackageName, |
| 6178 | @Nullable String callingAttributionTag) { |
| 6179 | Objects.requireNonNull(operation, "PendingIntent cannot be null."); |
| 6180 | final int callingUid = mDeps.getCallingUid(); |
| 6181 | networkCapabilities = new NetworkCapabilities(networkCapabilities); |
| 6182 | enforceNetworkRequestPermissions(networkCapabilities, callingPackageName, |
| 6183 | callingAttributionTag); |
| 6184 | enforceMeteredApnPolicy(networkCapabilities); |
| 6185 | ensureRequestableCapabilities(networkCapabilities); |
| 6186 | ensureSufficientPermissionsForRequest(networkCapabilities, |
| 6187 | Binder.getCallingPid(), callingUid, callingPackageName); |
| 6188 | ensureValidNetworkSpecifier(networkCapabilities); |
| 6189 | restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities, |
| 6190 | callingUid, callingPackageName); |
| 6191 | |
| 6192 | NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE, |
| 6193 | nextNetworkRequestId(), NetworkRequest.Type.REQUEST); |
| 6194 | NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation, |
| 6195 | callingAttributionTag); |
| 6196 | if (DBG) log("pendingRequest for " + nri); |
| 6197 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT, |
| 6198 | nri)); |
| 6199 | return networkRequest; |
| 6200 | } |
| 6201 | |
| 6202 | private void releasePendingNetworkRequestWithDelay(PendingIntent operation) { |
| 6203 | mHandler.sendMessageDelayed( |
| 6204 | mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, |
| 6205 | mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs); |
| 6206 | } |
| 6207 | |
| 6208 | @Override |
| 6209 | public void releasePendingNetworkRequest(PendingIntent operation) { |
| 6210 | Objects.requireNonNull(operation, "PendingIntent cannot be null."); |
| 6211 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, |
| 6212 | mDeps.getCallingUid(), 0, operation)); |
| 6213 | } |
| 6214 | |
| 6215 | // In order to implement the compatibility measure for pre-M apps that call |
| 6216 | // WifiManager.enableNetwork(..., true) without also binding to that network explicitly, |
| 6217 | // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork. |
| 6218 | // This ensures it has permission to do so. |
| 6219 | private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) { |
| 6220 | if (nc == null) { |
| 6221 | return false; |
| 6222 | } |
| 6223 | int[] transportTypes = nc.getTransportTypes(); |
| 6224 | if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) { |
| 6225 | return false; |
| 6226 | } |
| 6227 | try { |
| 6228 | mContext.enforceCallingOrSelfPermission( |
| 6229 | android.Manifest.permission.ACCESS_WIFI_STATE, |
| 6230 | "ConnectivityService"); |
| 6231 | } catch (SecurityException e) { |
| 6232 | return false; |
| 6233 | } |
| 6234 | return true; |
| 6235 | } |
| 6236 | |
| 6237 | @Override |
| 6238 | public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities, |
| 6239 | Messenger messenger, IBinder binder, |
| 6240 | @NetworkCallback.Flag int callbackFlags, |
| 6241 | @NonNull String callingPackageName, @NonNull String callingAttributionTag) { |
| 6242 | final int callingUid = mDeps.getCallingUid(); |
| 6243 | if (!hasWifiNetworkListenPermission(networkCapabilities)) { |
| 6244 | enforceAccessPermission(); |
| 6245 | } |
| 6246 | |
| 6247 | NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities); |
| 6248 | ensureSufficientPermissionsForRequest(networkCapabilities, |
| 6249 | Binder.getCallingPid(), callingUid, callingPackageName); |
| 6250 | restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName); |
| 6251 | // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so |
| 6252 | // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get |
| 6253 | // onLost and onAvailable callbacks when networks move in and out of the background. |
| 6254 | // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE |
| 6255 | // can't request networks. |
| 6256 | restrictBackgroundRequestForCaller(nc); |
| 6257 | ensureValid(nc); |
| 6258 | |
| 6259 | NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(), |
| 6260 | NetworkRequest.Type.LISTEN); |
| 6261 | NetworkRequestInfo nri = |
| 6262 | new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags, |
| 6263 | callingAttributionTag); |
| 6264 | if (VDBG) log("listenForNetwork for " + nri); |
| 6265 | |
| 6266 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); |
| 6267 | return networkRequest; |
| 6268 | } |
| 6269 | |
| 6270 | @Override |
| 6271 | public void pendingListenForNetwork(NetworkCapabilities networkCapabilities, |
| 6272 | PendingIntent operation, @NonNull String callingPackageName, |
| 6273 | @Nullable String callingAttributionTag) { |
| 6274 | Objects.requireNonNull(operation, "PendingIntent cannot be null."); |
| 6275 | final int callingUid = mDeps.getCallingUid(); |
| 6276 | if (!hasWifiNetworkListenPermission(networkCapabilities)) { |
| 6277 | enforceAccessPermission(); |
| 6278 | } |
| 6279 | ensureValid(networkCapabilities); |
| 6280 | ensureSufficientPermissionsForRequest(networkCapabilities, |
| 6281 | Binder.getCallingPid(), callingUid, callingPackageName); |
| 6282 | final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities); |
| 6283 | restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName); |
| 6284 | |
| 6285 | NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(), |
| 6286 | NetworkRequest.Type.LISTEN); |
| 6287 | NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation, |
| 6288 | callingAttributionTag); |
| 6289 | if (VDBG) log("pendingListenForNetwork for " + nri); |
| 6290 | |
Treehugger Robot | 282f743 | 2021-06-30 21:59:16 +0000 | [diff] [blame] | 6291 | mHandler.sendMessage(mHandler.obtainMessage( |
| 6292 | EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri)); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 6293 | } |
| 6294 | |
| 6295 | /** Returns the next Network provider ID. */ |
| 6296 | public final int nextNetworkProviderId() { |
| 6297 | return mNextNetworkProviderId.getAndIncrement(); |
| 6298 | } |
| 6299 | |
| 6300 | private void releaseNetworkRequests(List<NetworkRequest> networkRequests) { |
| 6301 | for (int i = 0; i < networkRequests.size(); i++) { |
| 6302 | releaseNetworkRequest(networkRequests.get(i)); |
| 6303 | } |
| 6304 | } |
| 6305 | |
| 6306 | @Override |
| 6307 | public void releaseNetworkRequest(NetworkRequest networkRequest) { |
| 6308 | ensureNetworkRequestHasType(networkRequest); |
| 6309 | mHandler.sendMessage(mHandler.obtainMessage( |
| 6310 | EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest)); |
| 6311 | } |
| 6312 | |
| 6313 | private void handleRegisterNetworkProvider(NetworkProviderInfo npi) { |
| 6314 | if (mNetworkProviderInfos.containsKey(npi.messenger)) { |
| 6315 | // Avoid creating duplicates. even if an app makes a direct AIDL call. |
| 6316 | // This will never happen if an app calls ConnectivityManager#registerNetworkProvider, |
| 6317 | // as that will throw if a duplicate provider is registered. |
| 6318 | loge("Attempt to register existing NetworkProviderInfo " |
| 6319 | + mNetworkProviderInfos.get(npi.messenger).name); |
| 6320 | return; |
| 6321 | } |
| 6322 | |
| 6323 | if (DBG) log("Got NetworkProvider Messenger for " + npi.name); |
| 6324 | mNetworkProviderInfos.put(npi.messenger, npi); |
| 6325 | npi.connect(mContext, mTrackerHandler); |
| 6326 | } |
| 6327 | |
| 6328 | @Override |
| 6329 | public int registerNetworkProvider(Messenger messenger, String name) { |
| 6330 | enforceNetworkFactoryOrSettingsPermission(); |
| 6331 | Objects.requireNonNull(messenger, "messenger must be non-null"); |
| 6332 | NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger, |
| 6333 | nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger)); |
| 6334 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi)); |
| 6335 | return npi.providerId; |
| 6336 | } |
| 6337 | |
| 6338 | @Override |
| 6339 | public void unregisterNetworkProvider(Messenger messenger) { |
| 6340 | enforceNetworkFactoryOrSettingsPermission(); |
| 6341 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger)); |
| 6342 | } |
| 6343 | |
| 6344 | @Override |
| 6345 | public void offerNetwork(final int providerId, |
| 6346 | @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps, |
| 6347 | @NonNull final INetworkOfferCallback callback) { |
| 6348 | Objects.requireNonNull(score); |
| 6349 | Objects.requireNonNull(caps); |
| 6350 | Objects.requireNonNull(callback); |
| 6351 | final NetworkOffer offer = new NetworkOffer( |
| 6352 | FullScore.makeProspectiveScore(score, caps), caps, callback, providerId); |
| 6353 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer)); |
| 6354 | } |
| 6355 | |
| 6356 | @Override |
| 6357 | public void unofferNetwork(@NonNull final INetworkOfferCallback callback) { |
| 6358 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback)); |
| 6359 | } |
| 6360 | |
| 6361 | private void handleUnregisterNetworkProvider(Messenger messenger) { |
| 6362 | NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger); |
| 6363 | if (npi == null) { |
| 6364 | loge("Failed to find Messenger in unregisterNetworkProvider"); |
| 6365 | return; |
| 6366 | } |
| 6367 | // Unregister all the offers from this provider |
| 6368 | final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>(); |
| 6369 | for (final NetworkOfferInfo noi : mNetworkOffers) { |
| 6370 | if (noi.offer.providerId == npi.providerId) { |
| 6371 | // Can't call handleUnregisterNetworkOffer here because iteration is in progress |
| 6372 | toRemove.add(noi); |
| 6373 | } |
| 6374 | } |
| 6375 | for (final NetworkOfferInfo noi : toRemove) { |
| 6376 | handleUnregisterNetworkOffer(noi); |
| 6377 | } |
| 6378 | if (DBG) log("unregisterNetworkProvider for " + npi.name); |
| 6379 | } |
| 6380 | |
| 6381 | @Override |
| 6382 | public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) { |
| 6383 | if (request.hasTransport(TRANSPORT_TEST)) { |
| 6384 | enforceNetworkFactoryOrTestNetworksPermission(); |
| 6385 | } else { |
| 6386 | enforceNetworkFactoryPermission(); |
| 6387 | } |
| 6388 | final NetworkRequestInfo nri = mNetworkRequests.get(request); |
| 6389 | if (nri != null) { |
| 6390 | // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests. |
| 6391 | ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable"); |
| 6392 | mHandler.post(() -> handleReleaseNetworkRequest( |
| 6393 | nri.mRequests.get(0), mDeps.getCallingUid(), true)); |
| 6394 | } |
| 6395 | } |
| 6396 | |
| 6397 | // NOTE: Accessed on multiple threads, must be synchronized on itself. |
| 6398 | @GuardedBy("mNetworkForNetId") |
| 6399 | private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>(); |
| 6400 | // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId. |
| 6401 | // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so |
| 6402 | // there may not be a strict 1:1 correlation between the two. |
| 6403 | private final NetIdManager mNetIdManager; |
| 6404 | |
Lorenzo Colitti | beb7d92 | 2021-06-09 08:33:36 +0000 | [diff] [blame] | 6405 | // Tracks all NetworkAgents that are currently registered. |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 6406 | // NOTE: Only should be accessed on ConnectivityServiceThread, except dump(). |
| 6407 | private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>(); |
| 6408 | |
| 6409 | // UID ranges for users that are currently blocked by VPNs. |
| 6410 | // This array is accessed and iterated on multiple threads without holding locks, so its |
| 6411 | // contents must never be mutated. When the ranges change, the array is replaced with a new one |
| 6412 | // (on the handler thread). |
| 6413 | private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>(); |
| 6414 | |
| 6415 | // Must only be accessed on the handler thread |
| 6416 | @NonNull |
| 6417 | private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>(); |
| 6418 | |
| 6419 | @GuardedBy("mBlockedAppUids") |
| 6420 | private final HashSet<Integer> mBlockedAppUids = new HashSet<>(); |
| 6421 | |
| 6422 | // Current OEM network preferences. This object must only be written to on the handler thread. |
| 6423 | // Since it is immutable and always non-null, other threads may read it if they only care |
| 6424 | // about seeing a consistent object but not that it is current. |
| 6425 | @NonNull |
| 6426 | private OemNetworkPreferences mOemNetworkPreferences = |
| 6427 | new OemNetworkPreferences.Builder().build(); |
| 6428 | // Current per-profile network preferences. This object follows the same threading rules as |
| 6429 | // the OEM network preferences above. |
| 6430 | @NonNull |
| 6431 | private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences(); |
| 6432 | |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 6433 | // A set of UIDs that should use mobile data preferentially if available. This object follows |
| 6434 | // the same threading rules as the OEM network preferences above. |
| 6435 | @NonNull |
| 6436 | private Set<Integer> mMobileDataPreferredUids = new ArraySet<>(); |
| 6437 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 6438 | // OemNetworkPreferences activity String log entries. |
| 6439 | private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20; |
| 6440 | @NonNull |
| 6441 | private final LocalLog mOemNetworkPreferencesLogs = |
| 6442 | new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS); |
| 6443 | |
| 6444 | /** |
| 6445 | * Determine whether a given package has a mapping in the current OemNetworkPreferences. |
| 6446 | * @param packageName the package name to check existence of a mapping for. |
| 6447 | * @return true if a mapping exists, false otherwise |
| 6448 | */ |
| 6449 | private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) { |
| 6450 | return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName); |
| 6451 | } |
| 6452 | |
| 6453 | // The always-on request for an Internet-capable network that apps without a specific default |
| 6454 | // fall back to. |
| 6455 | @VisibleForTesting |
| 6456 | @NonNull |
| 6457 | final NetworkRequestInfo mDefaultRequest; |
| 6458 | // Collection of NetworkRequestInfo's used for default networks. |
| 6459 | @VisibleForTesting |
| 6460 | @NonNull |
| 6461 | final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>(); |
| 6462 | |
| 6463 | private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) { |
| 6464 | return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri); |
| 6465 | } |
| 6466 | |
| 6467 | /** |
| 6468 | * Return the default network request currently tracking the given uid. |
| 6469 | * @param uid the uid to check. |
| 6470 | * @return the NetworkRequestInfo tracking the given uid. |
| 6471 | */ |
| 6472 | @NonNull |
| 6473 | private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) { |
| 6474 | for (final NetworkRequestInfo nri : mDefaultNetworkRequests) { |
| 6475 | if (nri == mDefaultRequest) { |
| 6476 | continue; |
| 6477 | } |
| 6478 | // Checking the first request is sufficient as only multilayer requests will have more |
| 6479 | // than one request and for multilayer, all requests will track the same uids. |
| 6480 | if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) { |
| 6481 | return nri; |
| 6482 | } |
| 6483 | } |
| 6484 | return mDefaultRequest; |
| 6485 | } |
| 6486 | |
| 6487 | /** |
| 6488 | * Get a copy of the network requests of the default request that is currently tracking the |
| 6489 | * given uid. |
| 6490 | * @param asUid the uid on behalf of which to file the request. Different from requestorUid |
| 6491 | * when a privileged caller is tracking the default network for another uid. |
| 6492 | * @param requestorUid the uid to check the default for. |
| 6493 | * @param requestorPackageName the requestor's package name. |
| 6494 | * @return a copy of the default's NetworkRequest that is tracking the given uid. |
| 6495 | */ |
| 6496 | @NonNull |
| 6497 | private List<NetworkRequest> copyDefaultNetworkRequestsForUid( |
| 6498 | final int asUid, final int requestorUid, @NonNull final String requestorPackageName) { |
| 6499 | return copyNetworkRequestsForUid( |
| 6500 | getDefaultRequestTrackingUid(asUid).mRequests, |
| 6501 | asUid, requestorUid, requestorPackageName); |
| 6502 | } |
| 6503 | |
| 6504 | /** |
| 6505 | * Copy the given nri's NetworkRequest collection. |
| 6506 | * @param requestsToCopy the NetworkRequest collection to be copied. |
| 6507 | * @param asUid the uid on behalf of which to file the request. Different from requestorUid |
| 6508 | * when a privileged caller is tracking the default network for another uid. |
| 6509 | * @param requestorUid the uid to set on the copied collection. |
| 6510 | * @param requestorPackageName the package name to set on the copied collection. |
| 6511 | * @return the copied NetworkRequest collection. |
| 6512 | */ |
| 6513 | @NonNull |
| 6514 | private List<NetworkRequest> copyNetworkRequestsForUid( |
| 6515 | @NonNull final List<NetworkRequest> requestsToCopy, final int asUid, |
| 6516 | final int requestorUid, @NonNull final String requestorPackageName) { |
| 6517 | final List<NetworkRequest> requests = new ArrayList<>(); |
| 6518 | for (final NetworkRequest nr : requestsToCopy) { |
| 6519 | requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid( |
| 6520 | nr.networkCapabilities, asUid, requestorUid, requestorPackageName), |
| 6521 | nr.legacyType, nextNetworkRequestId(), nr.type)); |
| 6522 | } |
| 6523 | return requests; |
| 6524 | } |
| 6525 | |
| 6526 | @NonNull |
| 6527 | private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid( |
| 6528 | @NonNull final NetworkCapabilities netCapToCopy, final int asUid, |
| 6529 | final int requestorUid, @NonNull final String requestorPackageName) { |
| 6530 | // These capabilities are for a TRACK_DEFAULT callback, so: |
| 6531 | // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between |
| 6532 | // mDefaultRequest and a per-UID default request. |
| 6533 | // TODO: stop depending on the fact that these two unrelated things happen to be the same |
| 6534 | // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will |
| 6535 | // not do this in the case of a privileged application. |
| 6536 | final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy); |
| 6537 | netCap.removeCapability(NET_CAPABILITY_NOT_VPN); |
| 6538 | netCap.setSingleUid(asUid); |
| 6539 | restrictRequestUidsForCallerAndSetRequestorInfo( |
| 6540 | netCap, requestorUid, requestorPackageName); |
| 6541 | return netCap; |
| 6542 | } |
| 6543 | |
| 6544 | /** |
| 6545 | * Get the nri that is currently being tracked for callbacks by per-app defaults. |
| 6546 | * @param nr the network request to check for equality against. |
| 6547 | * @return the nri if one exists, null otherwise. |
| 6548 | */ |
| 6549 | @Nullable |
| 6550 | private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) { |
| 6551 | for (final NetworkRequestInfo nri : mNetworkRequests.values()) { |
| 6552 | if (nri.getNetworkRequestForCallback().equals(nr)) { |
| 6553 | return nri; |
| 6554 | } |
| 6555 | } |
| 6556 | return null; |
| 6557 | } |
| 6558 | |
| 6559 | /** |
| 6560 | * Check if an nri is currently being managed by per-app default networking. |
| 6561 | * @param nri the nri to check. |
| 6562 | * @return true if this nri is currently being managed by per-app default networking. |
| 6563 | */ |
| 6564 | private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) { |
| 6565 | // nri.mRequests.get(0) is only different from the original request filed in |
| 6566 | // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default |
| 6567 | // functionality therefore if these two don't match, it means this particular nri is |
| 6568 | // currently being managed by a per-app default. |
| 6569 | return nri.getNetworkRequestForCallback() != nri.mRequests.get(0); |
| 6570 | } |
| 6571 | |
| 6572 | /** |
| 6573 | * Determine if an nri is a managed default request that disallows default networking. |
| 6574 | * @param nri the request to evaluate |
| 6575 | * @return true if device-default networking is disallowed |
| 6576 | */ |
| 6577 | private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) { |
| 6578 | // Check if this nri is a managed default that supports the default network at its |
| 6579 | // lowest priority request. |
| 6580 | final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0); |
| 6581 | final NetworkCapabilities lowestPriorityNetCap = |
| 6582 | nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities; |
| 6583 | return isPerAppDefaultRequest(nri) |
| 6584 | && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities( |
| 6585 | lowestPriorityNetCap)); |
| 6586 | } |
| 6587 | |
| 6588 | // Request used to optionally keep mobile data active even when higher |
| 6589 | // priority networks like Wi-Fi are active. |
| 6590 | private final NetworkRequest mDefaultMobileDataRequest; |
| 6591 | |
| 6592 | // Request used to optionally keep wifi data active even when higher |
| 6593 | // priority networks like ethernet are active. |
| 6594 | private final NetworkRequest mDefaultWifiRequest; |
| 6595 | |
| 6596 | // Request used to optionally keep vehicle internal network always active |
| 6597 | private final NetworkRequest mDefaultVehicleRequest; |
| 6598 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 6599 | // Sentinel NAI used to direct apps with default networks that should have no connectivity to a |
| 6600 | // network with no service. This NAI should never be matched against, nor should any public API |
| 6601 | // ever return the associated network. For this reason, this NAI is not in the list of available |
| 6602 | // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device |
| 6603 | // default requests that don't support using the device default network which will ultimately |
| 6604 | // allow ConnectivityService to use this no-service network when calling makeDefaultForApps(). |
| 6605 | @VisibleForTesting |
| 6606 | final NetworkAgentInfo mNoServiceNetwork; |
| 6607 | |
| 6608 | // The NetworkAgentInfo currently satisfying the default request, if any. |
| 6609 | private NetworkAgentInfo getDefaultNetwork() { |
| 6610 | return mDefaultRequest.mSatisfier; |
| 6611 | } |
| 6612 | |
| 6613 | private NetworkAgentInfo getDefaultNetworkForUid(final int uid) { |
| 6614 | for (final NetworkRequestInfo nri : mDefaultNetworkRequests) { |
| 6615 | // Currently, all network requests will have the same uids therefore checking the first |
| 6616 | // one is sufficient. If/when uids are tracked at the nri level, this can change. |
| 6617 | final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges(); |
| 6618 | if (null == uids) { |
| 6619 | continue; |
| 6620 | } |
| 6621 | for (final UidRange range : uids) { |
| 6622 | if (range.contains(uid)) { |
| 6623 | return nri.getSatisfier(); |
| 6624 | } |
| 6625 | } |
| 6626 | } |
| 6627 | return getDefaultNetwork(); |
| 6628 | } |
| 6629 | |
| 6630 | @Nullable |
| 6631 | private Network getNetwork(@Nullable NetworkAgentInfo nai) { |
| 6632 | return nai != null ? nai.network : null; |
| 6633 | } |
| 6634 | |
| 6635 | private void ensureRunningOnConnectivityServiceThread() { |
| 6636 | if (mHandler.getLooper().getThread() != Thread.currentThread()) { |
| 6637 | throw new IllegalStateException( |
| 6638 | "Not running on ConnectivityService thread: " |
| 6639 | + Thread.currentThread().getName()); |
| 6640 | } |
| 6641 | } |
| 6642 | |
| 6643 | @VisibleForTesting |
| 6644 | protected boolean isDefaultNetwork(NetworkAgentInfo nai) { |
| 6645 | return nai == getDefaultNetwork(); |
| 6646 | } |
| 6647 | |
| 6648 | /** |
| 6649 | * Register a new agent with ConnectivityService to handle a network. |
| 6650 | * |
| 6651 | * @param na a reference for ConnectivityService to contact the agent asynchronously. |
| 6652 | * @param networkInfo the initial info associated with this network. It can be updated later : |
| 6653 | * see {@link #updateNetworkInfo}. |
| 6654 | * @param linkProperties the initial link properties of this network. They can be updated |
| 6655 | * later : see {@link #updateLinkProperties}. |
| 6656 | * @param networkCapabilities the initial capabilites of this network. They can be updated |
| 6657 | * later : see {@link #updateCapabilities}. |
| 6658 | * @param initialScore the initial score of the network. See |
| 6659 | * {@link NetworkAgentInfo#getCurrentScore}. |
| 6660 | * @param networkAgentConfig metadata about the network. This is never updated. |
| 6661 | * @param providerId the ID of the provider owning this NetworkAgent. |
| 6662 | * @return the network created for this agent. |
| 6663 | */ |
| 6664 | public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo, |
| 6665 | LinkProperties linkProperties, NetworkCapabilities networkCapabilities, |
| 6666 | @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig, |
| 6667 | int providerId) { |
| 6668 | Objects.requireNonNull(networkInfo, "networkInfo must not be null"); |
| 6669 | Objects.requireNonNull(linkProperties, "linkProperties must not be null"); |
| 6670 | Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null"); |
| 6671 | Objects.requireNonNull(initialScore, "initialScore must not be null"); |
| 6672 | Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null"); |
| 6673 | if (networkCapabilities.hasTransport(TRANSPORT_TEST)) { |
| 6674 | enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS); |
| 6675 | } else { |
| 6676 | enforceNetworkFactoryPermission(); |
| 6677 | } |
| 6678 | |
| 6679 | final int uid = mDeps.getCallingUid(); |
| 6680 | final long token = Binder.clearCallingIdentity(); |
| 6681 | try { |
| 6682 | return registerNetworkAgentInternal(na, networkInfo, linkProperties, |
| 6683 | networkCapabilities, initialScore, networkAgentConfig, providerId, uid); |
| 6684 | } finally { |
| 6685 | Binder.restoreCallingIdentity(token); |
| 6686 | } |
| 6687 | } |
| 6688 | |
| 6689 | private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo, |
| 6690 | LinkProperties linkProperties, NetworkCapabilities networkCapabilities, |
| 6691 | NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId, |
| 6692 | int uid) { |
| 6693 | if (networkCapabilities.hasTransport(TRANSPORT_TEST)) { |
| 6694 | // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in |
| 6695 | // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never |
| 6696 | // sees capabilities that may be malicious, which might prevent mistakes in the future. |
| 6697 | networkCapabilities = new NetworkCapabilities(networkCapabilities); |
| 6698 | networkCapabilities.restrictCapabilitesForTestNetwork(uid); |
| 6699 | } |
| 6700 | |
| 6701 | LinkProperties lp = new LinkProperties(linkProperties); |
| 6702 | |
| 6703 | final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities); |
| 6704 | final NetworkAgentInfo nai = new NetworkAgentInfo(na, |
| 6705 | new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc, |
| 6706 | currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig), |
| 6707 | this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs, |
| 6708 | mQosCallbackTracker, mDeps); |
| 6709 | |
| 6710 | // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says. |
| 6711 | processCapabilitiesFromAgent(nai, nc); |
| 6712 | nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc)); |
| 6713 | processLinkPropertiesFromAgent(nai, nai.linkProperties); |
| 6714 | |
| 6715 | final String extraInfo = networkInfo.getExtraInfo(); |
| 6716 | final String name = TextUtils.isEmpty(extraInfo) |
| 6717 | ? nai.networkCapabilities.getSsid() : extraInfo; |
| 6718 | if (DBG) log("registerNetworkAgent " + nai); |
| 6719 | mDeps.getNetworkStack().makeNetworkMonitor( |
| 6720 | nai.network, name, new NetworkMonitorCallbacks(nai)); |
| 6721 | // NetworkAgentInfo registration will finish when the NetworkMonitor is created. |
| 6722 | // If the network disconnects or sends any other event before that, messages are deferred by |
| 6723 | // NetworkAgent until nai.connect(), which will be called when finalizing the |
| 6724 | // registration. |
| 6725 | return nai.network; |
| 6726 | } |
| 6727 | |
| 6728 | private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) { |
| 6729 | nai.onNetworkMonitorCreated(networkMonitor); |
| 6730 | if (VDBG) log("Got NetworkAgent Messenger"); |
| 6731 | mNetworkAgentInfos.add(nai); |
| 6732 | synchronized (mNetworkForNetId) { |
| 6733 | mNetworkForNetId.put(nai.network.getNetId(), nai); |
| 6734 | } |
| 6735 | |
| 6736 | try { |
| 6737 | networkMonitor.start(); |
| 6738 | } catch (RemoteException e) { |
| 6739 | e.rethrowAsRuntimeException(); |
| 6740 | } |
| 6741 | nai.notifyRegistered(); |
| 6742 | NetworkInfo networkInfo = nai.networkInfo; |
| 6743 | updateNetworkInfo(nai, networkInfo); |
| 6744 | updateUids(nai, null, nai.networkCapabilities); |
| 6745 | } |
| 6746 | |
| 6747 | private class NetworkOfferInfo implements IBinder.DeathRecipient { |
| 6748 | @NonNull public final NetworkOffer offer; |
| 6749 | |
| 6750 | NetworkOfferInfo(@NonNull final NetworkOffer offer) { |
| 6751 | this.offer = offer; |
| 6752 | } |
| 6753 | |
| 6754 | @Override |
| 6755 | public void binderDied() { |
| 6756 | mHandler.post(() -> handleUnregisterNetworkOffer(this)); |
| 6757 | } |
| 6758 | } |
| 6759 | |
| 6760 | private boolean isNetworkProviderWithIdRegistered(final int providerId) { |
| 6761 | for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) { |
| 6762 | if (npi.providerId == providerId) return true; |
| 6763 | } |
| 6764 | return false; |
| 6765 | } |
| 6766 | |
| 6767 | /** |
| 6768 | * Register or update a network offer. |
| 6769 | * @param newOffer The new offer. If the callback member is the same as an existing |
| 6770 | * offer, it is an update of that offer. |
| 6771 | */ |
| 6772 | private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) { |
| 6773 | ensureRunningOnConnectivityServiceThread(); |
| 6774 | if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) { |
| 6775 | // This may actually happen if a provider updates its score or registers and then |
| 6776 | // immediately unregisters. The offer would still be in the handler queue, but the |
| 6777 | // provider would have been removed. |
| 6778 | if (DBG) log("Received offer from an unregistered provider"); |
| 6779 | return; |
| 6780 | } |
| 6781 | final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback); |
| 6782 | if (null != existingOffer) { |
| 6783 | handleUnregisterNetworkOffer(existingOffer); |
| 6784 | newOffer.migrateFrom(existingOffer.offer); |
| 6785 | } |
| 6786 | final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer); |
| 6787 | try { |
| 6788 | noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */); |
| 6789 | } catch (RemoteException e) { |
| 6790 | noi.binderDied(); |
| 6791 | return; |
| 6792 | } |
| 6793 | mNetworkOffers.add(noi); |
| 6794 | issueNetworkNeeds(noi); |
| 6795 | } |
| 6796 | |
| 6797 | private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) { |
| 6798 | ensureRunningOnConnectivityServiceThread(); |
| 6799 | mNetworkOffers.remove(noi); |
| 6800 | noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */); |
| 6801 | } |
| 6802 | |
| 6803 | @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback( |
| 6804 | @NonNull final INetworkOfferCallback callback) { |
| 6805 | ensureRunningOnConnectivityServiceThread(); |
| 6806 | for (final NetworkOfferInfo noi : mNetworkOffers) { |
| 6807 | if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi; |
| 6808 | } |
| 6809 | return null; |
| 6810 | } |
| 6811 | |
| 6812 | /** |
| 6813 | * Called when receiving LinkProperties directly from a NetworkAgent. |
| 6814 | * Stores into |nai| any data coming from the agent that might also be written to the network's |
| 6815 | * LinkProperties by ConnectivityService itself. This ensures that the data provided by the |
| 6816 | * agent is not lost when updateLinkProperties is called. |
| 6817 | * This method should never alter the agent's LinkProperties, only store data in |nai|. |
| 6818 | */ |
| 6819 | private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) { |
| 6820 | lp.ensureDirectlyConnectedRoutes(); |
| 6821 | nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix()); |
| 6822 | nai.networkAgentPortalData = lp.getCaptivePortalData(); |
| 6823 | } |
| 6824 | |
| 6825 | private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp, |
| 6826 | @NonNull LinkProperties oldLp) { |
| 6827 | int netId = networkAgent.network.getNetId(); |
| 6828 | |
| 6829 | // The NetworkAgent does not know whether clatd is running on its network or not, or whether |
| 6830 | // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure |
| 6831 | // the LinkProperties for the network are accurate. |
| 6832 | networkAgent.clatd.fixupLinkProperties(oldLp, newLp); |
| 6833 | |
| 6834 | updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities); |
| 6835 | |
| 6836 | // update filtering rules, need to happen after the interface update so netd knows about the |
| 6837 | // new interface (the interface name -> index map becomes initialized) |
| 6838 | updateVpnFiltering(newLp, oldLp, networkAgent); |
| 6839 | |
| 6840 | updateMtu(newLp, oldLp); |
| 6841 | // TODO - figure out what to do for clat |
| 6842 | // for (LinkProperties lp : newLp.getStackedLinks()) { |
| 6843 | // updateMtu(lp, null); |
| 6844 | // } |
| 6845 | if (isDefaultNetwork(networkAgent)) { |
| 6846 | updateTcpBufferSizes(newLp.getTcpBufferSizes()); |
| 6847 | } |
| 6848 | |
| 6849 | updateRoutes(newLp, oldLp, netId); |
| 6850 | updateDnses(newLp, oldLp, netId); |
| 6851 | // Make sure LinkProperties represents the latest private DNS status. |
| 6852 | // This does not need to be done before updateDnses because the |
| 6853 | // LinkProperties are not the source of the private DNS configuration. |
| 6854 | // updateDnses will fetch the private DNS configuration from DnsManager. |
| 6855 | mDnsManager.updatePrivateDnsStatus(netId, newLp); |
| 6856 | |
| 6857 | if (isDefaultNetwork(networkAgent)) { |
| 6858 | handleApplyDefaultProxy(newLp.getHttpProxy()); |
| 6859 | } else { |
| 6860 | updateProxy(newLp, oldLp); |
| 6861 | } |
| 6862 | |
| 6863 | updateWakeOnLan(newLp); |
| 6864 | |
| 6865 | // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo. |
| 6866 | // It is not always contained in the LinkProperties sent from NetworkAgents, and if it |
| 6867 | // does, it needs to be merged here. |
| 6868 | newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData, |
| 6869 | networkAgent.capportApiData)); |
| 6870 | |
| 6871 | // TODO - move this check to cover the whole function |
| 6872 | if (!Objects.equals(newLp, oldLp)) { |
| 6873 | synchronized (networkAgent) { |
| 6874 | networkAgent.linkProperties = newLp; |
| 6875 | } |
| 6876 | // Start or stop DNS64 detection and 464xlat according to network state. |
| 6877 | networkAgent.clatd.update(); |
| 6878 | notifyIfacesChangedForNetworkStats(); |
| 6879 | networkAgent.networkMonitor().notifyLinkPropertiesChanged( |
| 6880 | new LinkProperties(newLp, true /* parcelSensitiveFields */)); |
| 6881 | if (networkAgent.everConnected) { |
| 6882 | notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED); |
| 6883 | } |
| 6884 | } |
| 6885 | |
| 6886 | mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent); |
| 6887 | } |
| 6888 | |
| 6889 | /** |
| 6890 | * @param naData captive portal data from NetworkAgent |
| 6891 | * @param apiData captive portal data from capport API |
| 6892 | */ |
| 6893 | @Nullable |
| 6894 | private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData, |
| 6895 | CaptivePortalData apiData) { |
| 6896 | if (naData == null || apiData == null) { |
| 6897 | return naData == null ? apiData : naData; |
| 6898 | } |
| 6899 | final CaptivePortalData.Builder captivePortalBuilder = |
| 6900 | new CaptivePortalData.Builder(naData); |
| 6901 | |
| 6902 | if (apiData.isCaptive()) { |
| 6903 | captivePortalBuilder.setCaptive(true); |
| 6904 | } |
| 6905 | if (apiData.isSessionExtendable()) { |
| 6906 | captivePortalBuilder.setSessionExtendable(true); |
| 6907 | } |
| 6908 | if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) { |
| 6909 | // Expiry time, bytes remaining, refresh time all need to come from the same source, |
| 6910 | // otherwise data would be inconsistent. Prefer the capport API info if present, |
| 6911 | // as it can generally be refreshed more often. |
| 6912 | captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis()); |
| 6913 | captivePortalBuilder.setBytesRemaining(apiData.getByteLimit()); |
| 6914 | captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis()); |
| 6915 | } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) { |
| 6916 | // No source has time / bytes remaining information: surface the newest refresh time |
| 6917 | // for other fields |
| 6918 | captivePortalBuilder.setRefreshTime( |
| 6919 | Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis())); |
| 6920 | } |
| 6921 | |
| 6922 | // Prioritize the user portal URL from the network agent if the source is authenticated. |
| 6923 | if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource() |
| 6924 | != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) { |
| 6925 | captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(), |
| 6926 | apiData.getUserPortalUrlSource()); |
| 6927 | } |
| 6928 | // Prioritize the venue information URL from the network agent if the source is |
| 6929 | // authenticated. |
| 6930 | if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource() |
| 6931 | != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) { |
| 6932 | captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(), |
| 6933 | apiData.getVenueInfoUrlSource()); |
| 6934 | } |
| 6935 | return captivePortalBuilder.build(); |
| 6936 | } |
| 6937 | |
| 6938 | private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) { |
| 6939 | // Marks are only available on WiFi interfaces. Checking for |
| 6940 | // marks on unsupported interfaces is harmless. |
| 6941 | if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { |
| 6942 | return; |
| 6943 | } |
| 6944 | |
| 6945 | int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark); |
| 6946 | int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask); |
| 6947 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 6948 | // Mask/mark of zero will not detect anything interesting. |
| 6949 | // Don't install rules unless both values are nonzero. |
| 6950 | if (mark == 0 || mask == 0) { |
| 6951 | return; |
| 6952 | } |
| 6953 | |
| 6954 | final String prefix = "iface:" + iface; |
| 6955 | try { |
| 6956 | if (add) { |
| 6957 | mNetd.wakeupAddInterface(iface, prefix, mark, mask); |
| 6958 | } else { |
| 6959 | mNetd.wakeupDelInterface(iface, prefix, mark, mask); |
| 6960 | } |
| 6961 | } catch (Exception e) { |
| 6962 | loge("Exception modifying wakeup packet monitoring: " + e); |
| 6963 | } |
| 6964 | |
| 6965 | } |
| 6966 | |
| 6967 | private void updateInterfaces(final @Nullable LinkProperties newLp, |
| 6968 | final @Nullable LinkProperties oldLp, final int netId, |
| 6969 | final @NonNull NetworkCapabilities caps) { |
| 6970 | final CompareResult<String> interfaceDiff = new CompareResult<>( |
| 6971 | oldLp != null ? oldLp.getAllInterfaceNames() : null, |
| 6972 | newLp != null ? newLp.getAllInterfaceNames() : null); |
| 6973 | if (!interfaceDiff.added.isEmpty()) { |
| 6974 | for (final String iface : interfaceDiff.added) { |
| 6975 | try { |
| 6976 | if (DBG) log("Adding iface " + iface + " to network " + netId); |
| 6977 | mNetd.networkAddInterface(netId, iface); |
| 6978 | wakeupModifyInterface(iface, caps, true); |
| 6979 | mDeps.reportNetworkInterfaceForTransports(mContext, iface, |
| 6980 | caps.getTransportTypes()); |
| 6981 | } catch (Exception e) { |
| 6982 | logw("Exception adding interface: " + e); |
| 6983 | } |
| 6984 | } |
| 6985 | } |
| 6986 | for (final String iface : interfaceDiff.removed) { |
| 6987 | try { |
| 6988 | if (DBG) log("Removing iface " + iface + " from network " + netId); |
| 6989 | wakeupModifyInterface(iface, caps, false); |
| 6990 | mNetd.networkRemoveInterface(netId, iface); |
| 6991 | } catch (Exception e) { |
| 6992 | loge("Exception removing interface: " + e); |
| 6993 | } |
| 6994 | } |
| 6995 | } |
| 6996 | |
| 6997 | // TODO: move to frameworks/libs/net. |
| 6998 | private RouteInfoParcel convertRouteInfo(RouteInfo route) { |
| 6999 | final String nextHop; |
| 7000 | |
| 7001 | switch (route.getType()) { |
| 7002 | case RouteInfo.RTN_UNICAST: |
| 7003 | if (route.hasGateway()) { |
| 7004 | nextHop = route.getGateway().getHostAddress(); |
| 7005 | } else { |
| 7006 | nextHop = INetd.NEXTHOP_NONE; |
| 7007 | } |
| 7008 | break; |
| 7009 | case RouteInfo.RTN_UNREACHABLE: |
| 7010 | nextHop = INetd.NEXTHOP_UNREACHABLE; |
| 7011 | break; |
| 7012 | case RouteInfo.RTN_THROW: |
| 7013 | nextHop = INetd.NEXTHOP_THROW; |
| 7014 | break; |
| 7015 | default: |
| 7016 | nextHop = INetd.NEXTHOP_NONE; |
| 7017 | break; |
| 7018 | } |
| 7019 | |
| 7020 | final RouteInfoParcel rip = new RouteInfoParcel(); |
| 7021 | rip.ifName = route.getInterface(); |
| 7022 | rip.destination = route.getDestination().toString(); |
| 7023 | rip.nextHop = nextHop; |
| 7024 | rip.mtu = route.getMtu(); |
| 7025 | |
| 7026 | return rip; |
| 7027 | } |
| 7028 | |
| 7029 | /** |
| 7030 | * Have netd update routes from oldLp to newLp. |
| 7031 | * @return true if routes changed between oldLp and newLp |
| 7032 | */ |
| 7033 | private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) { |
| 7034 | // compare the route diff to determine which routes have been updated |
| 7035 | final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff = |
| 7036 | new CompareOrUpdateResult<>( |
| 7037 | oldLp != null ? oldLp.getAllRoutes() : null, |
| 7038 | newLp != null ? newLp.getAllRoutes() : null, |
| 7039 | (r) -> r.getRouteKey()); |
| 7040 | |
| 7041 | // add routes before removing old in case it helps with continuous connectivity |
| 7042 | |
| 7043 | // do this twice, adding non-next-hop routes first, then routes they are dependent on |
| 7044 | for (RouteInfo route : routeDiff.added) { |
| 7045 | if (route.hasGateway()) continue; |
| 7046 | if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId); |
| 7047 | try { |
| 7048 | mNetd.networkAddRouteParcel(netId, convertRouteInfo(route)); |
| 7049 | } catch (Exception e) { |
| 7050 | if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) { |
| 7051 | loge("Exception in networkAddRouteParcel for non-gateway: " + e); |
| 7052 | } |
| 7053 | } |
| 7054 | } |
| 7055 | for (RouteInfo route : routeDiff.added) { |
| 7056 | if (!route.hasGateway()) continue; |
| 7057 | if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId); |
| 7058 | try { |
| 7059 | mNetd.networkAddRouteParcel(netId, convertRouteInfo(route)); |
| 7060 | } catch (Exception e) { |
| 7061 | if ((route.getGateway() instanceof Inet4Address) || VDBG) { |
| 7062 | loge("Exception in networkAddRouteParcel for gateway: " + e); |
| 7063 | } |
| 7064 | } |
| 7065 | } |
| 7066 | |
| 7067 | for (RouteInfo route : routeDiff.removed) { |
| 7068 | if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId); |
| 7069 | try { |
| 7070 | mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route)); |
| 7071 | } catch (Exception e) { |
| 7072 | loge("Exception in networkRemoveRouteParcel: " + e); |
| 7073 | } |
| 7074 | } |
| 7075 | |
| 7076 | for (RouteInfo route : routeDiff.updated) { |
| 7077 | if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId); |
| 7078 | try { |
| 7079 | mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route)); |
| 7080 | } catch (Exception e) { |
| 7081 | loge("Exception in networkUpdateRouteParcel: " + e); |
| 7082 | } |
| 7083 | } |
| 7084 | return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty() |
| 7085 | || !routeDiff.updated.isEmpty(); |
| 7086 | } |
| 7087 | |
| 7088 | private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) { |
| 7089 | if (oldLp != null && newLp.isIdenticalDnses(oldLp)) { |
| 7090 | return; // no updating necessary |
| 7091 | } |
| 7092 | |
| 7093 | if (DBG) { |
| 7094 | final Collection<InetAddress> dnses = newLp.getDnsServers(); |
| 7095 | log("Setting DNS servers for network " + netId + " to " + dnses); |
| 7096 | } |
| 7097 | try { |
| 7098 | mDnsManager.noteDnsServersForNetwork(netId, newLp); |
| 7099 | mDnsManager.flushVmDnsCache(); |
| 7100 | } catch (Exception e) { |
| 7101 | loge("Exception in setDnsConfigurationForNetwork: " + e); |
| 7102 | } |
| 7103 | } |
| 7104 | |
| 7105 | private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp, |
| 7106 | NetworkAgentInfo nai) { |
| 7107 | final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null; |
| 7108 | final String newIface = newLp != null ? newLp.getInterfaceName() : null; |
| 7109 | final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp); |
| 7110 | final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp); |
| 7111 | |
| 7112 | if (!wasFiltering && !needsFiltering) { |
| 7113 | // Nothing to do. |
| 7114 | return; |
| 7115 | } |
| 7116 | |
| 7117 | if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) { |
| 7118 | // Nothing changed. |
| 7119 | return; |
| 7120 | } |
| 7121 | |
| 7122 | final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges(); |
| 7123 | final int vpnAppUid = nai.networkCapabilities.getOwnerUid(); |
| 7124 | // TODO: this create a window of opportunity for apps to receive traffic between the time |
| 7125 | // when the old rules are removed and the time when new rules are added. To fix this, |
| 7126 | // make eBPF support two allowlisted interfaces so here new rules can be added before the |
| 7127 | // old rules are being removed. |
| 7128 | if (wasFiltering) { |
| 7129 | mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid); |
| 7130 | } |
| 7131 | if (needsFiltering) { |
| 7132 | mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid); |
| 7133 | } |
| 7134 | } |
| 7135 | |
| 7136 | private void updateWakeOnLan(@NonNull LinkProperties lp) { |
| 7137 | if (mWolSupportedInterfaces == null) { |
| 7138 | mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray( |
| 7139 | R.array.config_wakeonlan_supported_interfaces)); |
| 7140 | } |
| 7141 | lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName())); |
| 7142 | } |
| 7143 | |
| 7144 | private int getNetworkPermission(NetworkCapabilities nc) { |
| 7145 | if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) { |
| 7146 | return INetd.PERMISSION_SYSTEM; |
| 7147 | } |
| 7148 | if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) { |
| 7149 | return INetd.PERMISSION_NETWORK; |
| 7150 | } |
| 7151 | return INetd.PERMISSION_NONE; |
| 7152 | } |
| 7153 | |
| 7154 | private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai, |
| 7155 | @NonNull final NetworkCapabilities newNc) { |
| 7156 | final int oldPermission = getNetworkPermission(nai.networkCapabilities); |
| 7157 | final int newPermission = getNetworkPermission(newNc); |
| 7158 | if (oldPermission != newPermission && nai.created && !nai.isVPN()) { |
| 7159 | try { |
| 7160 | mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission); |
| 7161 | } catch (RemoteException | ServiceSpecificException e) { |
| 7162 | loge("Exception in networkSetPermissionForNetwork: " + e); |
| 7163 | } |
| 7164 | } |
| 7165 | } |
| 7166 | |
| 7167 | /** |
| 7168 | * Called when receiving NetworkCapabilities directly from a NetworkAgent. |
| 7169 | * Stores into |nai| any data coming from the agent that might also be written to the network's |
| 7170 | * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the |
| 7171 | * agent is not lost when updateCapabilities is called. |
| 7172 | * This method should never alter the agent's NetworkCapabilities, only store data in |nai|. |
| 7173 | */ |
| 7174 | private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) { |
| 7175 | // Note: resetting the owner UID before storing the agent capabilities in NAI means that if |
| 7176 | // the agent attempts to change the owner UID, then nai.declaredCapabilities will not |
| 7177 | // actually be the same as the capabilities sent by the agent. Still, it is safer to reset |
| 7178 | // the owner UID here and behave as if the agent had never tried to change it. |
| 7179 | if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) { |
| 7180 | Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from " |
| 7181 | + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid()); |
| 7182 | nc.setOwnerUid(nai.networkCapabilities.getOwnerUid()); |
| 7183 | } |
| 7184 | nai.declaredCapabilities = new NetworkCapabilities(nc); |
| 7185 | } |
| 7186 | |
| 7187 | /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */ |
| 7188 | @VisibleForTesting |
| 7189 | void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks, |
| 7190 | @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) { |
| 7191 | underlyingNetworks = underlyingNetworksOrDefault( |
| 7192 | agentCaps.getOwnerUid(), underlyingNetworks); |
| 7193 | long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes()); |
| 7194 | int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED; |
| 7195 | int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED; |
| 7196 | // metered if any underlying is metered, or originally declared metered by the agent. |
| 7197 | boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED); |
| 7198 | boolean roaming = false; // roaming if any underlying is roaming |
| 7199 | boolean congested = false; // congested if any underlying is congested |
| 7200 | boolean suspended = true; // suspended if all underlying are suspended |
| 7201 | |
| 7202 | boolean hadUnderlyingNetworks = false; |
| 7203 | if (null != underlyingNetworks) { |
| 7204 | for (Network underlyingNetwork : underlyingNetworks) { |
| 7205 | final NetworkAgentInfo underlying = |
| 7206 | getNetworkAgentInfoForNetwork(underlyingNetwork); |
| 7207 | if (underlying == null) continue; |
| 7208 | |
| 7209 | final NetworkCapabilities underlyingCaps = underlying.networkCapabilities; |
| 7210 | hadUnderlyingNetworks = true; |
| 7211 | for (int underlyingType : underlyingCaps.getTransportTypes()) { |
| 7212 | transportTypes |= 1L << underlyingType; |
| 7213 | } |
| 7214 | |
| 7215 | // Merge capabilities of this underlying network. For bandwidth, assume the |
| 7216 | // worst case. |
| 7217 | downKbps = NetworkCapabilities.minBandwidth(downKbps, |
| 7218 | underlyingCaps.getLinkDownstreamBandwidthKbps()); |
| 7219 | upKbps = NetworkCapabilities.minBandwidth(upKbps, |
| 7220 | underlyingCaps.getLinkUpstreamBandwidthKbps()); |
| 7221 | // If this underlying network is metered, the VPN is metered (it may cost money |
| 7222 | // to send packets on this network). |
| 7223 | metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED); |
| 7224 | // If this underlying network is roaming, the VPN is roaming (the billing structure |
| 7225 | // is different than the usual, local one). |
| 7226 | roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING); |
| 7227 | // If this underlying network is congested, the VPN is congested (the current |
| 7228 | // condition of the network affects the performance of this network). |
| 7229 | congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED); |
| 7230 | // If this network is not suspended, the VPN is not suspended (the VPN |
| 7231 | // is able to transfer some data). |
| 7232 | suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED); |
| 7233 | } |
| 7234 | } |
| 7235 | if (!hadUnderlyingNetworks) { |
| 7236 | // No idea what the underlying networks are; assume reasonable defaults |
| 7237 | metered = true; |
| 7238 | roaming = false; |
| 7239 | congested = false; |
| 7240 | suspended = false; |
| 7241 | } |
| 7242 | |
| 7243 | newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes)); |
| 7244 | newNc.setLinkDownstreamBandwidthKbps(downKbps); |
| 7245 | newNc.setLinkUpstreamBandwidthKbps(upKbps); |
| 7246 | newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered); |
| 7247 | newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming); |
| 7248 | newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested); |
| 7249 | newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended); |
| 7250 | } |
| 7251 | |
| 7252 | /** |
| 7253 | * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are |
| 7254 | * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal, |
| 7255 | * and foreground status). |
| 7256 | */ |
| 7257 | @NonNull |
| 7258 | private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) { |
| 7259 | // Once a NetworkAgent is connected, complain if some immutable capabilities are removed. |
| 7260 | // Don't complain for VPNs since they're not driven by requests and there is no risk of |
| 7261 | // causing a connect/teardown loop. |
| 7262 | // TODO: remove this altogether and make it the responsibility of the NetworkProviders to |
| 7263 | // avoid connect/teardown loops. |
| 7264 | if (nai.everConnected && |
| 7265 | !nai.isVPN() && |
| 7266 | !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) { |
| 7267 | // TODO: consider not complaining when a network agent degrades its capabilities if this |
| 7268 | // does not cause any request (that is not a listen) currently matching that agent to |
| 7269 | // stop being matched by the updated agent. |
| 7270 | String diff = nai.networkCapabilities.describeImmutableDifferences(nc); |
| 7271 | if (!TextUtils.isEmpty(diff)) { |
| 7272 | Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff); |
| 7273 | } |
| 7274 | } |
| 7275 | |
| 7276 | // Don't modify caller's NetworkCapabilities. |
| 7277 | final NetworkCapabilities newNc = new NetworkCapabilities(nc); |
| 7278 | if (nai.lastValidated) { |
| 7279 | newNc.addCapability(NET_CAPABILITY_VALIDATED); |
| 7280 | } else { |
| 7281 | newNc.removeCapability(NET_CAPABILITY_VALIDATED); |
| 7282 | } |
| 7283 | if (nai.lastCaptivePortalDetected) { |
| 7284 | newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL); |
| 7285 | } else { |
| 7286 | newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL); |
| 7287 | } |
| 7288 | if (nai.isBackgroundNetwork()) { |
| 7289 | newNc.removeCapability(NET_CAPABILITY_FOREGROUND); |
| 7290 | } else { |
| 7291 | newNc.addCapability(NET_CAPABILITY_FOREGROUND); |
| 7292 | } |
| 7293 | if (nai.partialConnectivity) { |
| 7294 | newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY); |
| 7295 | } else { |
| 7296 | newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY); |
| 7297 | } |
| 7298 | newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken()); |
| 7299 | |
| 7300 | // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING |
| 7301 | if (!newNc.hasTransport(TRANSPORT_CELLULAR)) { |
| 7302 | newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED); |
| 7303 | newNc.addCapability(NET_CAPABILITY_NOT_ROAMING); |
| 7304 | } |
| 7305 | |
| 7306 | if (nai.supportsUnderlyingNetworks()) { |
| 7307 | applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities, |
| 7308 | newNc); |
| 7309 | } |
| 7310 | |
| 7311 | return newNc; |
| 7312 | } |
| 7313 | |
| 7314 | private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai, |
| 7315 | NetworkCapabilities prevNc, NetworkCapabilities newNc) { |
| 7316 | final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED); |
| 7317 | final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED); |
| 7318 | final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING); |
| 7319 | final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING); |
| 7320 | if (prevSuspended != suspended) { |
| 7321 | // TODO (b/73132094) : remove this call once the few users of onSuspended and |
| 7322 | // onResumed have been removed. |
| 7323 | notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED |
| 7324 | : ConnectivityManager.CALLBACK_RESUMED); |
| 7325 | } |
| 7326 | if (prevSuspended != suspended || prevRoaming != roaming) { |
| 7327 | // updateNetworkInfo will mix in the suspended info from the capabilities and |
| 7328 | // take appropriate action for the network having possibly changed state. |
| 7329 | updateNetworkInfo(nai, nai.networkInfo); |
| 7330 | } |
| 7331 | } |
| 7332 | |
| 7333 | /** |
| 7334 | * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically: |
| 7335 | * |
| 7336 | * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the |
| 7337 | * capabilities we manage and store in {@code nai}, such as validated status and captive |
| 7338 | * portal status) |
| 7339 | * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and |
| 7340 | * potentially triggers rematches. |
| 7341 | * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the |
| 7342 | * change.) |
| 7343 | * |
| 7344 | * @param oldScore score of the network before any of the changes that prompted us |
| 7345 | * to call this function. |
| 7346 | * @param nai the network having its capabilities updated. |
| 7347 | * @param nc the new network capabilities. |
| 7348 | */ |
| 7349 | private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai, |
| 7350 | @NonNull final NetworkCapabilities nc) { |
| 7351 | NetworkCapabilities newNc = mixInCapabilities(nai, nc); |
| 7352 | if (Objects.equals(nai.networkCapabilities, newNc)) return; |
| 7353 | updateNetworkPermissions(nai, newNc); |
| 7354 | final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc); |
| 7355 | |
| 7356 | updateUids(nai, prevNc, newNc); |
| 7357 | nai.updateScoreForNetworkAgentUpdate(); |
| 7358 | |
| 7359 | if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) { |
| 7360 | // If the requestable capabilities haven't changed, and the score hasn't changed, then |
| 7361 | // the change we're processing can't affect any requests, it can only affect the listens |
| 7362 | // on this network. We might have been called by rematchNetworkAndRequests when a |
| 7363 | // network changed foreground state. |
| 7364 | processListenRequests(nai); |
| 7365 | } else { |
| 7366 | // If the requestable capabilities have changed or the score changed, we can't have been |
| 7367 | // called by rematchNetworkAndRequests, so it's safe to start a rematch. |
| 7368 | rematchAllNetworksAndRequests(); |
| 7369 | notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED); |
| 7370 | } |
| 7371 | updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc); |
| 7372 | |
| 7373 | final boolean oldMetered = prevNc.isMetered(); |
| 7374 | final boolean newMetered = newNc.isMetered(); |
| 7375 | final boolean meteredChanged = oldMetered != newMetered; |
| 7376 | |
| 7377 | if (meteredChanged) { |
| 7378 | maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, |
| 7379 | mVpnBlockedUidRanges, mVpnBlockedUidRanges); |
| 7380 | } |
| 7381 | |
| 7382 | final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) |
| 7383 | != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING); |
| 7384 | |
| 7385 | // Report changes that are interesting for network statistics tracking. |
| 7386 | if (meteredChanged || roamingChanged) { |
| 7387 | notifyIfacesChangedForNetworkStats(); |
| 7388 | } |
| 7389 | |
| 7390 | // This network might have been underlying another network. Propagate its capabilities. |
| 7391 | propagateUnderlyingNetworkCapabilities(nai.network); |
| 7392 | |
| 7393 | if (!newNc.equalsTransportTypes(prevNc)) { |
| 7394 | mDnsManager.updateTransportsForNetwork( |
| 7395 | nai.network.getNetId(), newNc.getTransportTypes()); |
| 7396 | } |
Lucas Lin | 950a65f | 2021-06-15 09:28:16 +0000 | [diff] [blame] | 7397 | |
| 7398 | maybeSendProxyBroadcast(nai, prevNc, newNc); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 7399 | } |
| 7400 | |
| 7401 | /** Convenience method to update the capabilities for a given network. */ |
| 7402 | private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) { |
| 7403 | updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities); |
| 7404 | } |
| 7405 | |
| 7406 | /** |
| 7407 | * Returns whether VPN isolation (ingress interface filtering) should be applied on the given |
| 7408 | * network. |
| 7409 | * |
| 7410 | * Ingress interface filtering enforces that all apps under the given network can only receive |
| 7411 | * packets from the network's interface (and loopback). This is important for VPNs because |
| 7412 | * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any |
| 7413 | * non-VPN interfaces. |
| 7414 | * |
| 7415 | * As a result, this method should return true iff |
| 7416 | * 1. the network is an app VPN (not legacy VPN) |
| 7417 | * 2. the VPN does not allow bypass |
| 7418 | * 3. the VPN is fully-routed |
| 7419 | * 4. the VPN interface is non-null |
| 7420 | * |
| 7421 | * @see INetd#firewallAddUidInterfaceRules |
| 7422 | * @see INetd#firewallRemoveUidInterfaceRules |
| 7423 | */ |
| 7424 | private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc, |
| 7425 | LinkProperties lp) { |
| 7426 | if (nc == null || lp == null) return false; |
| 7427 | return nai.isVPN() |
| 7428 | && !nai.networkAgentConfig.allowBypass |
| 7429 | && nc.getOwnerUid() != Process.SYSTEM_UID |
| 7430 | && lp.getInterfaceName() != null |
| 7431 | && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute()) |
| 7432 | && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute()); |
| 7433 | } |
| 7434 | |
| 7435 | private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) { |
| 7436 | final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()]; |
| 7437 | int index = 0; |
| 7438 | for (UidRange range : ranges) { |
| 7439 | stableRanges[index] = new UidRangeParcel(range.start, range.stop); |
| 7440 | index++; |
| 7441 | } |
| 7442 | return stableRanges; |
| 7443 | } |
| 7444 | |
| 7445 | private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) { |
| 7446 | final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length]; |
| 7447 | for (int i = 0; i < ranges.length; i++) { |
| 7448 | stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop); |
| 7449 | } |
| 7450 | return stableRanges; |
| 7451 | } |
| 7452 | |
| 7453 | private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges, |
| 7454 | int[] exemptUids) { |
| 7455 | if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) { |
| 7456 | try { |
| 7457 | mNetd.socketDestroy(ranges, exemptUids); |
| 7458 | } catch (Exception e) { |
| 7459 | loge("Exception in socket destroy: ", e); |
| 7460 | } |
| 7461 | } |
| 7462 | } |
| 7463 | |
| 7464 | private void updateUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) { |
| 7465 | int[] exemptUids = new int[2]; |
| 7466 | // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used |
| 7467 | // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when |
| 7468 | // starting a legacy VPN, and remove VPN_UID here. (b/176542831) |
| 7469 | exemptUids[0] = VPN_UID; |
| 7470 | exemptUids[1] = nai.networkCapabilities.getOwnerUid(); |
| 7471 | UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges); |
| 7472 | |
| 7473 | maybeCloseSockets(nai, ranges, exemptUids); |
| 7474 | try { |
| 7475 | if (add) { |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 7476 | // TODO: Passing default network priority to netd. |
| 7477 | mNetd.networkAddUidRanges(nai.network.netId, ranges |
| 7478 | /* DEFAULT_NETWORK_PRIORITY_NONE */); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 7479 | } else { |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 7480 | // TODO: Passing default network priority to netd. |
| 7481 | mNetd.networkRemoveUidRanges(nai.network.netId, ranges |
| 7482 | /* DEFAULT_NETWORK_PRIORITY_NONE */); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 7483 | } |
| 7484 | } catch (Exception e) { |
| 7485 | loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges + |
| 7486 | " on netId " + nai.network.netId + ". " + e); |
| 7487 | } |
| 7488 | maybeCloseSockets(nai, ranges, exemptUids); |
| 7489 | } |
| 7490 | |
Lucas Lin | 950a65f | 2021-06-15 09:28:16 +0000 | [diff] [blame] | 7491 | private boolean isProxySetOnAnyDefaultNetwork() { |
| 7492 | ensureRunningOnConnectivityServiceThread(); |
| 7493 | for (final NetworkRequestInfo nri : mDefaultNetworkRequests) { |
| 7494 | final NetworkAgentInfo nai = nri.getSatisfier(); |
| 7495 | if (nai != null && nai.linkProperties.getHttpProxy() != null) { |
| 7496 | return true; |
| 7497 | } |
| 7498 | } |
| 7499 | return false; |
| 7500 | } |
| 7501 | |
| 7502 | private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc, |
| 7503 | NetworkCapabilities newNc) { |
| 7504 | // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that |
| 7505 | // the proxy might be changed since the default network satisfied by the apps might also |
| 7506 | // changed. |
| 7507 | // TODO: Try to track the default network that apps use and only send a proxy broadcast when |
| 7508 | // that happens to prevent false alarms. |
| 7509 | if (nai.isVPN() && nai.everConnected && !NetworkCapabilities.hasSameUids(prevNc, newNc) |
| 7510 | && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) { |
| 7511 | mProxyTracker.sendProxyBroadcast(); |
| 7512 | } |
| 7513 | } |
| 7514 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 7515 | private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc, |
| 7516 | NetworkCapabilities newNc) { |
| 7517 | Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges(); |
| 7518 | Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges(); |
| 7519 | if (null == prevRanges) prevRanges = new ArraySet<>(); |
| 7520 | if (null == newRanges) newRanges = new ArraySet<>(); |
| 7521 | final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges); |
| 7522 | |
| 7523 | prevRanges.removeAll(newRanges); |
| 7524 | newRanges.removeAll(prevRangesCopy); |
| 7525 | |
| 7526 | try { |
| 7527 | // When updating the VPN uid routing rules, add the new range first then remove the old |
| 7528 | // range. If old range were removed first, there would be a window between the old |
| 7529 | // range being removed and the new range being added, during which UIDs contained |
| 7530 | // in both ranges are not subject to any VPN routing rules. Adding new range before |
| 7531 | // removing old range works because, unlike the filtering rules below, it's possible to |
| 7532 | // add duplicate UID routing rules. |
| 7533 | // TODO: calculate the intersection of add & remove. Imagining that we are trying to |
| 7534 | // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is: |
| 7535 | // [1-5] & [1-2],[4-5] == [3] |
| 7536 | // Then we can do: |
| 7537 | // maybeCloseSockets([3]) |
| 7538 | // mNetd.networkAddUidRanges([1-2],[4-5]) |
| 7539 | // mNetd.networkRemoveUidRanges([1-5]) |
| 7540 | // maybeCloseSockets([3]) |
| 7541 | // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the |
| 7542 | // number of binder calls from 6 to 4. |
| 7543 | if (!newRanges.isEmpty()) { |
| 7544 | updateUidRanges(true, nai, newRanges); |
| 7545 | } |
| 7546 | if (!prevRanges.isEmpty()) { |
| 7547 | updateUidRanges(false, nai, prevRanges); |
| 7548 | } |
| 7549 | final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties); |
| 7550 | final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties); |
| 7551 | final String iface = nai.linkProperties.getInterfaceName(); |
| 7552 | // For VPN uid interface filtering, old ranges need to be removed before new ranges can |
| 7553 | // be added, due to the range being expanded and stored as individual UIDs. For example |
| 7554 | // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means |
| 7555 | // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges |
| 7556 | // were added first and then newRanges got removed later, there would be only one uid |
| 7557 | // 10013 left. A consequence of removing old ranges before adding new ranges is that |
| 7558 | // there is now a window of opportunity when the UIDs are not subject to any filtering. |
| 7559 | // Note that this is in contrast with the (more robust) update of VPN routing rules |
| 7560 | // above, where the addition of new ranges happens before the removal of old ranges. |
| 7561 | // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range |
| 7562 | // to be removed will never overlap with the new range to be added. |
| 7563 | if (wasFiltering && !prevRanges.isEmpty()) { |
| 7564 | mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid()); |
| 7565 | } |
| 7566 | if (shouldFilter && !newRanges.isEmpty()) { |
| 7567 | mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid()); |
| 7568 | } |
| 7569 | } catch (Exception e) { |
| 7570 | // Never crash! |
| 7571 | loge("Exception in updateUids: ", e); |
| 7572 | } |
| 7573 | } |
| 7574 | |
| 7575 | public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) { |
| 7576 | ensureRunningOnConnectivityServiceThread(); |
| 7577 | |
Lorenzo Colitti | beb7d92 | 2021-06-09 08:33:36 +0000 | [diff] [blame] | 7578 | if (!mNetworkAgentInfos.contains(nai)) { |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 7579 | // Ignore updates for disconnected networks |
| 7580 | return; |
| 7581 | } |
| 7582 | if (VDBG || DDBG) { |
| 7583 | log("Update of LinkProperties for " + nai.toShortString() |
| 7584 | + "; created=" + nai.created |
| 7585 | + "; everConnected=" + nai.everConnected); |
| 7586 | } |
| 7587 | // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not |
| 7588 | // modify its oldLp parameter. |
| 7589 | updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties)); |
| 7590 | } |
| 7591 | |
| 7592 | private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent, |
| 7593 | int notificationType) { |
| 7594 | if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) { |
| 7595 | Intent intent = new Intent(); |
| 7596 | intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network); |
| 7597 | // If apps could file multi-layer requests with PendingIntents, they'd need to know |
| 7598 | // which of the layer is satisfied alongside with some ID for the request. Hence, if |
| 7599 | // such an API is ever implemented, there is no doubt the right request to send in |
Remi NGUYEN VAN | 4cb6189 | 2021-06-28 07:27:47 +0000 | [diff] [blame] | 7600 | // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would |
| 7601 | // need to be sent as a separate extra. |
| 7602 | final NetworkRequest req = nri.isMultilayerRequest() |
| 7603 | ? nri.getActiveRequest() |
| 7604 | // Non-multilayer listen requests do not have an active request |
| 7605 | : nri.mRequests.get(0); |
| 7606 | if (req == null) { |
| 7607 | Log.wtf(TAG, "No request in NRI " + nri); |
| 7608 | } |
| 7609 | intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 7610 | nri.mPendingIntentSent = true; |
| 7611 | sendIntent(nri.mPendingIntent, intent); |
| 7612 | } |
| 7613 | // else not handled |
| 7614 | } |
| 7615 | |
| 7616 | private void sendIntent(PendingIntent pendingIntent, Intent intent) { |
| 7617 | mPendingIntentWakeLock.acquire(); |
| 7618 | try { |
| 7619 | if (DBG) log("Sending " + pendingIntent); |
| 7620 | pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */); |
| 7621 | } catch (PendingIntent.CanceledException e) { |
| 7622 | if (DBG) log(pendingIntent + " was not sent, it had been canceled."); |
| 7623 | mPendingIntentWakeLock.release(); |
| 7624 | releasePendingNetworkRequest(pendingIntent); |
| 7625 | } |
| 7626 | // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished() |
| 7627 | } |
| 7628 | |
| 7629 | @Override |
| 7630 | public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, |
| 7631 | String resultData, Bundle resultExtras) { |
| 7632 | if (DBG) log("Finished sending " + pendingIntent); |
| 7633 | mPendingIntentWakeLock.release(); |
| 7634 | // Release with a delay so the receiving client has an opportunity to put in its |
| 7635 | // own request. |
| 7636 | releasePendingNetworkRequestWithDelay(pendingIntent); |
| 7637 | } |
| 7638 | |
| 7639 | private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri, |
| 7640 | @NonNull final NetworkAgentInfo networkAgent, final int notificationType, |
| 7641 | final int arg1) { |
| 7642 | if (nri.mMessenger == null) { |
| 7643 | // Default request has no msgr. Also prevents callbacks from being invoked for |
| 7644 | // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks |
| 7645 | // are Type.LISTEN, but should not have NetworkCallbacks invoked. |
| 7646 | return; |
| 7647 | } |
| 7648 | Bundle bundle = new Bundle(); |
| 7649 | // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects. |
| 7650 | // TODO: check if defensive copies of data is needed. |
| 7651 | final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback(); |
| 7652 | putParcelable(bundle, nrForCallback); |
| 7653 | Message msg = Message.obtain(); |
| 7654 | if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) { |
| 7655 | putParcelable(bundle, networkAgent.network); |
| 7656 | } |
| 7657 | final boolean includeLocationSensitiveInfo = |
| 7658 | (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0; |
| 7659 | switch (notificationType) { |
| 7660 | case ConnectivityManager.CALLBACK_AVAILABLE: { |
| 7661 | final NetworkCapabilities nc = |
| 7662 | networkCapabilitiesRestrictedForCallerPermissions( |
| 7663 | networkAgent.networkCapabilities, nri.mPid, nri.mUid); |
| 7664 | putParcelable( |
| 7665 | bundle, |
| 7666 | createWithLocationInfoSanitizedIfNecessaryWhenParceled( |
| 7667 | nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid, |
| 7668 | nrForCallback.getRequestorPackageName(), |
| 7669 | nri.mCallingAttributionTag)); |
| 7670 | putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions( |
| 7671 | networkAgent.linkProperties, nri.mPid, nri.mUid)); |
| 7672 | // For this notification, arg1 contains the blocked status. |
| 7673 | msg.arg1 = arg1; |
| 7674 | break; |
| 7675 | } |
| 7676 | case ConnectivityManager.CALLBACK_LOSING: { |
| 7677 | msg.arg1 = arg1; |
| 7678 | break; |
| 7679 | } |
| 7680 | case ConnectivityManager.CALLBACK_CAP_CHANGED: { |
| 7681 | // networkAgent can't be null as it has been accessed a few lines above. |
| 7682 | final NetworkCapabilities netCap = |
| 7683 | networkCapabilitiesRestrictedForCallerPermissions( |
| 7684 | networkAgent.networkCapabilities, nri.mPid, nri.mUid); |
| 7685 | putParcelable( |
| 7686 | bundle, |
| 7687 | createWithLocationInfoSanitizedIfNecessaryWhenParceled( |
| 7688 | netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid, |
| 7689 | nrForCallback.getRequestorPackageName(), |
| 7690 | nri.mCallingAttributionTag)); |
| 7691 | break; |
| 7692 | } |
| 7693 | case ConnectivityManager.CALLBACK_IP_CHANGED: { |
| 7694 | putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions( |
| 7695 | networkAgent.linkProperties, nri.mPid, nri.mUid)); |
| 7696 | break; |
| 7697 | } |
| 7698 | case ConnectivityManager.CALLBACK_BLK_CHANGED: { |
| 7699 | maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1); |
| 7700 | msg.arg1 = arg1; |
| 7701 | break; |
| 7702 | } |
| 7703 | } |
| 7704 | msg.what = notificationType; |
| 7705 | msg.setData(bundle); |
| 7706 | try { |
| 7707 | if (VDBG) { |
| 7708 | String notification = ConnectivityManager.getCallbackName(notificationType); |
| 7709 | log("sending notification " + notification + " for " + nrForCallback); |
| 7710 | } |
| 7711 | nri.mMessenger.send(msg); |
| 7712 | } catch (RemoteException e) { |
| 7713 | // may occur naturally in the race of binder death. |
| 7714 | loge("RemoteException caught trying to send a callback msg for " + nrForCallback); |
| 7715 | } |
| 7716 | } |
| 7717 | |
| 7718 | private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) { |
| 7719 | bundle.putParcelable(t.getClass().getSimpleName(), t); |
| 7720 | } |
| 7721 | |
| 7722 | private void teardownUnneededNetwork(NetworkAgentInfo nai) { |
| 7723 | if (nai.numRequestNetworkRequests() != 0) { |
| 7724 | for (int i = 0; i < nai.numNetworkRequests(); i++) { |
| 7725 | NetworkRequest nr = nai.requestAt(i); |
| 7726 | // Ignore listening and track default requests. |
| 7727 | if (!nr.isRequest()) continue; |
| 7728 | loge("Dead network still had at least " + nr); |
| 7729 | break; |
| 7730 | } |
| 7731 | } |
| 7732 | nai.disconnect(); |
| 7733 | } |
| 7734 | |
| 7735 | private void handleLingerComplete(NetworkAgentInfo oldNetwork) { |
| 7736 | if (oldNetwork == null) { |
| 7737 | loge("Unknown NetworkAgentInfo in handleLingerComplete"); |
| 7738 | return; |
| 7739 | } |
| 7740 | if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString()); |
| 7741 | |
| 7742 | // If we get here it means that the last linger timeout for this network expired. So there |
| 7743 | // must be no other active linger timers, and we must stop lingering. |
| 7744 | oldNetwork.clearInactivityState(); |
| 7745 | |
| 7746 | if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) { |
| 7747 | // Tear the network down. |
| 7748 | teardownUnneededNetwork(oldNetwork); |
| 7749 | } else { |
| 7750 | // Put the network in the background if it doesn't satisfy any foreground request. |
| 7751 | updateCapabilitiesForNetwork(oldNetwork); |
| 7752 | } |
| 7753 | } |
| 7754 | |
| 7755 | private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) { |
| 7756 | boolean isDefaultChanged = false; |
| 7757 | for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) { |
| 7758 | final NetworkReassignment.RequestReassignment reassignment = |
| 7759 | changes.getReassignment(defaultRequestInfo); |
| 7760 | if (null == reassignment) { |
| 7761 | continue; |
| 7762 | } |
| 7763 | // reassignment only contains those instances where the satisfying network changed. |
| 7764 | isDefaultChanged = true; |
| 7765 | // Notify system services of the new default. |
| 7766 | makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork); |
| 7767 | } |
| 7768 | |
| 7769 | if (isDefaultChanged) { |
| 7770 | // Hold a wakelock for a short time to help apps in migrating to a new default. |
| 7771 | scheduleReleaseNetworkTransitionWakelock(); |
| 7772 | } |
| 7773 | } |
| 7774 | |
| 7775 | private void makeDefault(@NonNull final NetworkRequestInfo nri, |
| 7776 | @Nullable final NetworkAgentInfo oldDefaultNetwork, |
| 7777 | @Nullable final NetworkAgentInfo newDefaultNetwork) { |
| 7778 | if (DBG) { |
| 7779 | log("Switching to new default network for: " + nri + " using " + newDefaultNetwork); |
| 7780 | } |
| 7781 | |
| 7782 | // Fix up the NetworkCapabilities of any networks that have this network as underlying. |
| 7783 | if (newDefaultNetwork != null) { |
| 7784 | propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network); |
| 7785 | } |
| 7786 | |
| 7787 | // Set an app level managed default and return since further processing only applies to the |
| 7788 | // default network. |
| 7789 | if (mDefaultRequest != nri) { |
| 7790 | makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork); |
| 7791 | return; |
| 7792 | } |
| 7793 | |
| 7794 | makeDefaultNetwork(newDefaultNetwork); |
| 7795 | |
| 7796 | if (oldDefaultNetwork != null) { |
| 7797 | mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork); |
| 7798 | } |
| 7799 | mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork); |
| 7800 | handleApplyDefaultProxy(null != newDefaultNetwork |
| 7801 | ? newDefaultNetwork.linkProperties.getHttpProxy() : null); |
| 7802 | updateTcpBufferSizes(null != newDefaultNetwork |
| 7803 | ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null); |
| 7804 | notifyIfacesChangedForNetworkStats(); |
| 7805 | } |
| 7806 | |
| 7807 | private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri, |
| 7808 | @Nullable final NetworkAgentInfo oldDefaultNetwork, |
| 7809 | @Nullable final NetworkAgentInfo newDefaultNetwork) { |
| 7810 | try { |
| 7811 | if (VDBG) { |
| 7812 | log("Setting default network for " + nri |
| 7813 | + " using UIDs " + nri.getUids() |
| 7814 | + " with old network " + (oldDefaultNetwork != null |
| 7815 | ? oldDefaultNetwork.network().getNetId() : "null") |
| 7816 | + " and new network " + (newDefaultNetwork != null |
| 7817 | ? newDefaultNetwork.network().getNetId() : "null")); |
| 7818 | } |
| 7819 | if (nri.getUids().isEmpty()) { |
| 7820 | throw new IllegalStateException("makeDefaultForApps called without specifying" |
| 7821 | + " any applications to set as the default." + nri); |
| 7822 | } |
| 7823 | if (null != newDefaultNetwork) { |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 7824 | // TODO: Passing default network priority to netd. |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 7825 | mNetd.networkAddUidRanges( |
| 7826 | newDefaultNetwork.network.getNetId(), |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 7827 | toUidRangeStableParcels(nri.getUids()) |
| 7828 | /* nri.getDefaultNetworkPriority() */); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 7829 | } |
| 7830 | if (null != oldDefaultNetwork) { |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 7831 | // TODO: Passing default network priority to netd. |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 7832 | mNetd.networkRemoveUidRanges( |
| 7833 | oldDefaultNetwork.network.getNetId(), |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 7834 | toUidRangeStableParcels(nri.getUids()) |
| 7835 | /* nri.getDefaultNetworkPriority() */); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 7836 | } |
| 7837 | } catch (RemoteException | ServiceSpecificException e) { |
| 7838 | loge("Exception setting app default network", e); |
| 7839 | } |
| 7840 | } |
| 7841 | |
| 7842 | private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) { |
| 7843 | try { |
| 7844 | if (null != newDefaultNetwork) { |
| 7845 | mNetd.networkSetDefault(newDefaultNetwork.network.getNetId()); |
| 7846 | } else { |
| 7847 | mNetd.networkClearDefault(); |
| 7848 | } |
| 7849 | } catch (RemoteException | ServiceSpecificException e) { |
| 7850 | loge("Exception setting default network :" + e); |
| 7851 | } |
| 7852 | } |
| 7853 | |
| 7854 | private void processListenRequests(@NonNull final NetworkAgentInfo nai) { |
| 7855 | // For consistency with previous behaviour, send onLost callbacks before onAvailable. |
| 7856 | processNewlyLostListenRequests(nai); |
| 7857 | notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED); |
| 7858 | processNewlySatisfiedListenRequests(nai); |
| 7859 | } |
| 7860 | |
| 7861 | private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) { |
| 7862 | for (final NetworkRequestInfo nri : mNetworkRequests.values()) { |
| 7863 | if (nri.isMultilayerRequest()) { |
| 7864 | continue; |
| 7865 | } |
| 7866 | final NetworkRequest nr = nri.mRequests.get(0); |
| 7867 | if (!nr.isListen()) continue; |
| 7868 | if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) { |
| 7869 | nai.removeRequest(nr.requestId); |
| 7870 | callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0); |
| 7871 | } |
| 7872 | } |
| 7873 | } |
| 7874 | |
| 7875 | private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) { |
| 7876 | for (final NetworkRequestInfo nri : mNetworkRequests.values()) { |
| 7877 | if (nri.isMultilayerRequest()) { |
| 7878 | continue; |
| 7879 | } |
| 7880 | final NetworkRequest nr = nri.mRequests.get(0); |
| 7881 | if (!nr.isListen()) continue; |
| 7882 | if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) { |
| 7883 | nai.addRequest(nr); |
| 7884 | notifyNetworkAvailable(nai, nri); |
| 7885 | } |
| 7886 | } |
| 7887 | } |
| 7888 | |
| 7889 | // An accumulator class to gather the list of changes that result from a rematch. |
| 7890 | private static class NetworkReassignment { |
| 7891 | static class RequestReassignment { |
| 7892 | @NonNull public final NetworkRequestInfo mNetworkRequestInfo; |
| 7893 | @Nullable public final NetworkRequest mOldNetworkRequest; |
| 7894 | @Nullable public final NetworkRequest mNewNetworkRequest; |
| 7895 | @Nullable public final NetworkAgentInfo mOldNetwork; |
| 7896 | @Nullable public final NetworkAgentInfo mNewNetwork; |
| 7897 | RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo, |
| 7898 | @Nullable final NetworkRequest oldNetworkRequest, |
| 7899 | @Nullable final NetworkRequest newNetworkRequest, |
| 7900 | @Nullable final NetworkAgentInfo oldNetwork, |
| 7901 | @Nullable final NetworkAgentInfo newNetwork) { |
| 7902 | mNetworkRequestInfo = networkRequestInfo; |
| 7903 | mOldNetworkRequest = oldNetworkRequest; |
| 7904 | mNewNetworkRequest = newNetworkRequest; |
| 7905 | mOldNetwork = oldNetwork; |
| 7906 | mNewNetwork = newNetwork; |
| 7907 | } |
| 7908 | |
| 7909 | public String toString() { |
| 7910 | final NetworkRequest requestToShow = null != mNewNetworkRequest |
| 7911 | ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0); |
| 7912 | return requestToShow.requestId + " : " |
| 7913 | + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null") |
| 7914 | + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null"); |
| 7915 | } |
| 7916 | } |
| 7917 | |
| 7918 | @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>(); |
| 7919 | |
| 7920 | @NonNull Iterable<RequestReassignment> getRequestReassignments() { |
| 7921 | return mReassignments; |
| 7922 | } |
| 7923 | |
| 7924 | void addRequestReassignment(@NonNull final RequestReassignment reassignment) { |
| 7925 | if (Build.isDebuggable()) { |
| 7926 | // The code is never supposed to add two reassignments of the same request. Make |
| 7927 | // sure this stays true, but without imposing this expensive check on all |
| 7928 | // reassignments on all user devices. |
| 7929 | for (final RequestReassignment existing : mReassignments) { |
| 7930 | if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) { |
| 7931 | throw new IllegalStateException("Trying to reassign [" |
| 7932 | + reassignment + "] but already have [" |
| 7933 | + existing + "]"); |
| 7934 | } |
| 7935 | } |
| 7936 | } |
| 7937 | mReassignments.add(reassignment); |
| 7938 | } |
| 7939 | |
| 7940 | // Will return null if this reassignment does not change the network assigned to |
| 7941 | // the passed request. |
| 7942 | @Nullable |
| 7943 | private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) { |
| 7944 | for (final RequestReassignment event : getRequestReassignments()) { |
| 7945 | if (nri == event.mNetworkRequestInfo) return event; |
| 7946 | } |
| 7947 | return null; |
| 7948 | } |
| 7949 | |
| 7950 | public String toString() { |
| 7951 | final StringJoiner sj = new StringJoiner(", " /* delimiter */, |
| 7952 | "NetReassign [" /* prefix */, "]" /* suffix */); |
| 7953 | if (mReassignments.isEmpty()) return sj.add("no changes").toString(); |
| 7954 | for (final RequestReassignment rr : getRequestReassignments()) { |
| 7955 | sj.add(rr.toString()); |
| 7956 | } |
| 7957 | return sj.toString(); |
| 7958 | } |
| 7959 | |
| 7960 | public String debugString() { |
| 7961 | final StringBuilder sb = new StringBuilder(); |
| 7962 | sb.append("NetworkReassignment :"); |
| 7963 | if (mReassignments.isEmpty()) return sb.append(" no changes").toString(); |
| 7964 | for (final RequestReassignment rr : getRequestReassignments()) { |
| 7965 | sb.append("\n ").append(rr); |
| 7966 | } |
| 7967 | return sb.append("\n").toString(); |
| 7968 | } |
| 7969 | } |
| 7970 | |
| 7971 | private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri, |
| 7972 | @Nullable final NetworkRequest previousRequest, |
| 7973 | @Nullable final NetworkRequest newRequest, |
| 7974 | @Nullable final NetworkAgentInfo previousSatisfier, |
| 7975 | @Nullable final NetworkAgentInfo newSatisfier, |
| 7976 | final long now) { |
| 7977 | if (null != newSatisfier && mNoServiceNetwork != newSatisfier) { |
| 7978 | if (VDBG) log("rematch for " + newSatisfier.toShortString()); |
| 7979 | if (null != previousRequest && null != previousSatisfier) { |
| 7980 | if (VDBG || DDBG) { |
| 7981 | log(" accepting network in place of " + previousSatisfier.toShortString()); |
| 7982 | } |
| 7983 | previousSatisfier.removeRequest(previousRequest.requestId); |
| 7984 | previousSatisfier.lingerRequest(previousRequest.requestId, now); |
| 7985 | } else { |
| 7986 | if (VDBG || DDBG) log(" accepting network in place of null"); |
| 7987 | } |
| 7988 | |
| 7989 | // To prevent constantly CPU wake up for nascent timer, if a network comes up |
| 7990 | // and immediately satisfies a request then remove the timer. This will happen for |
| 7991 | // all networks except in the case of an underlying network for a VCN. |
| 7992 | if (newSatisfier.isNascent()) { |
| 7993 | newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE); |
| 7994 | newSatisfier.unsetInactive(); |
| 7995 | } |
| 7996 | |
| 7997 | // if newSatisfier is not null, then newRequest may not be null. |
| 7998 | newSatisfier.unlingerRequest(newRequest.requestId); |
| 7999 | if (!newSatisfier.addRequest(newRequest)) { |
| 8000 | Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has " |
| 8001 | + newRequest); |
| 8002 | } |
| 8003 | } else if (null != previousRequest && null != previousSatisfier) { |
| 8004 | if (DBG) { |
| 8005 | log("Network " + previousSatisfier.toShortString() + " stopped satisfying" |
| 8006 | + " request " + previousRequest.requestId); |
| 8007 | } |
| 8008 | previousSatisfier.removeRequest(previousRequest.requestId); |
| 8009 | } |
| 8010 | nri.setSatisfier(newSatisfier, newRequest); |
| 8011 | } |
| 8012 | |
| 8013 | /** |
| 8014 | * This function is triggered when something can affect what network should satisfy what |
| 8015 | * request, and it computes the network reassignment from the passed collection of requests to |
| 8016 | * network match to the one that the system should now have. That data is encoded in an |
| 8017 | * object that is a list of changes, each of them having an NRI, and old satisfier, and a new |
| 8018 | * satisfier. |
| 8019 | * |
| 8020 | * After the reassignment is computed, it is applied to the state objects. |
| 8021 | * |
| 8022 | * @param networkRequests the nri objects to evaluate for possible network reassignment |
| 8023 | * @return NetworkReassignment listing of proposed network assignment changes |
| 8024 | */ |
| 8025 | @NonNull |
| 8026 | private NetworkReassignment computeNetworkReassignment( |
| 8027 | @NonNull final Collection<NetworkRequestInfo> networkRequests) { |
| 8028 | final NetworkReassignment changes = new NetworkReassignment(); |
| 8029 | |
| 8030 | // Gather the list of all relevant agents. |
| 8031 | final ArrayList<NetworkAgentInfo> nais = new ArrayList<>(); |
| 8032 | for (final NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 8033 | if (!nai.everConnected) { |
| 8034 | continue; |
| 8035 | } |
| 8036 | nais.add(nai); |
| 8037 | } |
| 8038 | |
| 8039 | for (final NetworkRequestInfo nri : networkRequests) { |
| 8040 | // Non-multilayer listen requests can be ignored. |
| 8041 | if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) { |
| 8042 | continue; |
| 8043 | } |
| 8044 | NetworkAgentInfo bestNetwork = null; |
| 8045 | NetworkRequest bestRequest = null; |
| 8046 | for (final NetworkRequest req : nri.mRequests) { |
| 8047 | bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier()); |
| 8048 | // Stop evaluating as the highest possible priority request is satisfied. |
| 8049 | if (null != bestNetwork) { |
| 8050 | bestRequest = req; |
| 8051 | break; |
| 8052 | } |
| 8053 | } |
| 8054 | if (null == bestNetwork && isDefaultBlocked(nri)) { |
| 8055 | // Remove default networking if disallowed for managed default requests. |
| 8056 | bestNetwork = mNoServiceNetwork; |
| 8057 | } |
| 8058 | if (nri.getSatisfier() != bestNetwork) { |
| 8059 | // bestNetwork may be null if no network can satisfy this request. |
| 8060 | changes.addRequestReassignment(new NetworkReassignment.RequestReassignment( |
| 8061 | nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork)); |
| 8062 | } |
| 8063 | } |
| 8064 | return changes; |
| 8065 | } |
| 8066 | |
| 8067 | private Set<NetworkRequestInfo> getNrisFromGlobalRequests() { |
| 8068 | return new HashSet<>(mNetworkRequests.values()); |
| 8069 | } |
| 8070 | |
| 8071 | /** |
| 8072 | * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks |
| 8073 | * being disconnected. |
| 8074 | */ |
| 8075 | private void rematchAllNetworksAndRequests() { |
| 8076 | rematchNetworksAndRequests(getNrisFromGlobalRequests()); |
| 8077 | } |
| 8078 | |
| 8079 | /** |
| 8080 | * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks |
| 8081 | * being disconnected. |
| 8082 | */ |
| 8083 | private void rematchNetworksAndRequests( |
| 8084 | @NonNull final Set<NetworkRequestInfo> networkRequests) { |
| 8085 | ensureRunningOnConnectivityServiceThread(); |
| 8086 | // TODO: This may be slow, and should be optimized. |
| 8087 | final long now = SystemClock.elapsedRealtime(); |
| 8088 | final NetworkReassignment changes = computeNetworkReassignment(networkRequests); |
| 8089 | if (VDBG || DDBG) { |
| 8090 | log(changes.debugString()); |
| 8091 | } else if (DBG) { |
| 8092 | log(changes.toString()); // Shorter form, only one line of log |
| 8093 | } |
| 8094 | applyNetworkReassignment(changes, now); |
| 8095 | issueNetworkNeeds(); |
| 8096 | } |
| 8097 | |
| 8098 | private void applyNetworkReassignment(@NonNull final NetworkReassignment changes, |
| 8099 | final long now) { |
| 8100 | final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos; |
| 8101 | |
| 8102 | // Since most of the time there are only 0 or 1 background networks, it would probably |
| 8103 | // be more efficient to just use an ArrayList here. TODO : measure performance |
| 8104 | final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>(); |
| 8105 | for (final NetworkAgentInfo nai : nais) { |
| 8106 | if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai); |
| 8107 | } |
| 8108 | |
| 8109 | // First, update the lists of satisfied requests in the network agents. This is necessary |
| 8110 | // because some code later depends on this state to be correct, most prominently computing |
| 8111 | // the linger status. |
| 8112 | for (final NetworkReassignment.RequestReassignment event : |
| 8113 | changes.getRequestReassignments()) { |
| 8114 | updateSatisfiersForRematchRequest(event.mNetworkRequestInfo, |
| 8115 | event.mOldNetworkRequest, event.mNewNetworkRequest, |
| 8116 | event.mOldNetwork, event.mNewNetwork, |
| 8117 | now); |
| 8118 | } |
| 8119 | |
| 8120 | // Process default network changes if applicable. |
| 8121 | processDefaultNetworkChanges(changes); |
| 8122 | |
| 8123 | // Notify requested networks are available after the default net is switched, but |
| 8124 | // before LegacyTypeTracker sends legacy broadcasts |
| 8125 | for (final NetworkReassignment.RequestReassignment event : |
| 8126 | changes.getRequestReassignments()) { |
| 8127 | if (null != event.mNewNetwork) { |
| 8128 | notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo); |
| 8129 | } else { |
| 8130 | callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork, |
| 8131 | ConnectivityManager.CALLBACK_LOST, 0); |
| 8132 | } |
| 8133 | } |
| 8134 | |
| 8135 | // Update the inactivity state before processing listen callbacks, because the background |
| 8136 | // computation depends on whether the network is inactive. Don't send the LOSING callbacks |
| 8137 | // just yet though, because they have to be sent after the listens are processed to keep |
| 8138 | // backward compatibility. |
| 8139 | final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>(); |
| 8140 | for (final NetworkAgentInfo nai : nais) { |
| 8141 | // Rematching may have altered the inactivity state of some networks, so update all |
| 8142 | // inactivity timers. updateInactivityState reads the state from the network agent |
| 8143 | // and does nothing if the state has not changed : the source of truth is controlled |
| 8144 | // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which |
| 8145 | // have been called while rematching the individual networks above. |
| 8146 | if (updateInactivityState(nai, now)) { |
| 8147 | inactiveNetworks.add(nai); |
| 8148 | } |
| 8149 | } |
| 8150 | |
| 8151 | for (final NetworkAgentInfo nai : nais) { |
| 8152 | if (!nai.everConnected) continue; |
| 8153 | final boolean oldBackground = oldBgNetworks.contains(nai); |
| 8154 | // Process listen requests and update capabilities if the background state has |
| 8155 | // changed for this network. For consistency with previous behavior, send onLost |
| 8156 | // callbacks before onAvailable. |
| 8157 | processNewlyLostListenRequests(nai); |
| 8158 | if (oldBackground != nai.isBackgroundNetwork()) { |
| 8159 | applyBackgroundChangeForRematch(nai); |
| 8160 | } |
| 8161 | processNewlySatisfiedListenRequests(nai); |
| 8162 | } |
| 8163 | |
| 8164 | for (final NetworkAgentInfo nai : inactiveNetworks) { |
| 8165 | // For nascent networks, if connecting with no foreground request, skip broadcasting |
| 8166 | // LOSING for backward compatibility. This is typical when mobile data connected while |
| 8167 | // wifi connected with mobile data always-on enabled. |
| 8168 | if (nai.isNascent()) continue; |
| 8169 | notifyNetworkLosing(nai, now); |
| 8170 | } |
| 8171 | |
| 8172 | updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais); |
| 8173 | |
| 8174 | // Tear down all unneeded networks. |
| 8175 | for (NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 8176 | if (unneeded(nai, UnneededFor.TEARDOWN)) { |
| 8177 | if (nai.getInactivityExpiry() > 0) { |
| 8178 | // This network has active linger timers and no requests, but is not |
| 8179 | // lingering. Linger it. |
| 8180 | // |
| 8181 | // One way (the only way?) this can happen if this network is unvalidated |
| 8182 | // and became unneeded due to another network improving its score to the |
| 8183 | // point where this network will no longer be able to satisfy any requests |
| 8184 | // even if it validates. |
| 8185 | if (updateInactivityState(nai, now)) { |
| 8186 | notifyNetworkLosing(nai, now); |
| 8187 | } |
| 8188 | } else { |
| 8189 | if (DBG) log("Reaping " + nai.toShortString()); |
| 8190 | teardownUnneededNetwork(nai); |
| 8191 | } |
| 8192 | } |
| 8193 | } |
| 8194 | } |
| 8195 | |
| 8196 | /** |
| 8197 | * Apply a change in background state resulting from rematching networks with requests. |
| 8198 | * |
| 8199 | * During rematch, a network may change background states by starting to satisfy or stopping |
| 8200 | * to satisfy a foreground request. Listens don't count for this. When a network changes |
| 8201 | * background states, its capabilities need to be updated and callbacks fired for the |
| 8202 | * capability change. |
| 8203 | * |
| 8204 | * @param nai The network that changed background states |
| 8205 | */ |
| 8206 | private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) { |
| 8207 | final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities); |
| 8208 | if (Objects.equals(nai.networkCapabilities, newNc)) return; |
| 8209 | updateNetworkPermissions(nai, newNc); |
| 8210 | nai.getAndSetNetworkCapabilities(newNc); |
| 8211 | notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED); |
| 8212 | } |
| 8213 | |
| 8214 | private void updateLegacyTypeTrackerAndVpnLockdownForRematch( |
| 8215 | @NonNull final NetworkReassignment changes, |
| 8216 | @NonNull final Collection<NetworkAgentInfo> nais) { |
| 8217 | final NetworkReassignment.RequestReassignment reassignmentOfDefault = |
| 8218 | changes.getReassignment(mDefaultRequest); |
| 8219 | final NetworkAgentInfo oldDefaultNetwork = |
| 8220 | null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null; |
| 8221 | final NetworkAgentInfo newDefaultNetwork = |
| 8222 | null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null; |
| 8223 | |
| 8224 | if (oldDefaultNetwork != newDefaultNetwork) { |
| 8225 | // Maintain the illusion : since the legacy API only understands one network at a time, |
| 8226 | // if the default network changed, apps should see a disconnected broadcast for the |
| 8227 | // old default network before they see a connected broadcast for the new one. |
| 8228 | if (oldDefaultNetwork != null) { |
| 8229 | mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(), |
| 8230 | oldDefaultNetwork, true); |
| 8231 | } |
| 8232 | if (newDefaultNetwork != null) { |
| 8233 | // The new default network can be newly null if and only if the old default |
| 8234 | // network doesn't satisfy the default request any more because it lost a |
| 8235 | // capability. |
| 8236 | mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0; |
| 8237 | mLegacyTypeTracker.add( |
| 8238 | newDefaultNetwork.networkInfo.getType(), newDefaultNetwork); |
| 8239 | } |
| 8240 | } |
| 8241 | |
| 8242 | // Now that all the callbacks have been sent, send the legacy network broadcasts |
| 8243 | // as needed. This is necessary so that legacy requests correctly bind dns |
| 8244 | // requests to this network. The legacy users are listening for this broadcast |
| 8245 | // and will generally do a dns request so they can ensureRouteToHost and if |
| 8246 | // they do that before the callbacks happen they'll use the default network. |
| 8247 | // |
| 8248 | // TODO: Is there still a race here? The legacy broadcast will be sent after sending |
| 8249 | // callbacks, but if apps can receive the broadcast before the callback, they still might |
| 8250 | // have an inconsistent view of networking. |
| 8251 | // |
| 8252 | // This *does* introduce a race where if the user uses the new api |
| 8253 | // (notification callbacks) and then uses the old api (getNetworkInfo(type)) |
| 8254 | // they may get old info. Reverse this after the old startUsing api is removed. |
| 8255 | // This is on top of the multiple intent sequencing referenced in the todo above. |
| 8256 | for (NetworkAgentInfo nai : nais) { |
| 8257 | if (nai.everConnected) { |
| 8258 | addNetworkToLegacyTypeTracker(nai); |
| 8259 | } |
| 8260 | } |
| 8261 | } |
| 8262 | |
| 8263 | private void issueNetworkNeeds() { |
| 8264 | ensureRunningOnConnectivityServiceThread(); |
| 8265 | for (final NetworkOfferInfo noi : mNetworkOffers) { |
| 8266 | issueNetworkNeeds(noi); |
| 8267 | } |
| 8268 | } |
| 8269 | |
| 8270 | private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) { |
| 8271 | ensureRunningOnConnectivityServiceThread(); |
| 8272 | for (final NetworkRequestInfo nri : mNetworkRequests.values()) { |
| 8273 | informOffer(nri, noi.offer, mNetworkRanker); |
| 8274 | } |
| 8275 | } |
| 8276 | |
| 8277 | /** |
| 8278 | * Inform a NetworkOffer about any new situation of a request. |
| 8279 | * |
| 8280 | * This function handles updates to offers. A number of events may happen that require |
| 8281 | * updating the registrant for this offer about the situation : |
| 8282 | * • The offer itself was updated. This may lead the offer to no longer being able |
| 8283 | * to satisfy a request or beat a satisfier (and therefore be no longer needed), |
| 8284 | * or conversely being strengthened enough to beat the satisfier (and therefore |
| 8285 | * start being needed) |
| 8286 | * • The network satisfying a request changed (including cases where the request |
| 8287 | * starts or stops being satisfied). The new network may be a stronger or weaker |
| 8288 | * match than the old one, possibly affecting whether the offer is needed. |
| 8289 | * • The network satisfying a request updated their score. This may lead the offer |
| 8290 | * to no longer be able to beat it if the current satisfier got better, or |
| 8291 | * conversely start being a good choice if the current satisfier got weaker. |
| 8292 | * |
| 8293 | * @param nri The request |
| 8294 | * @param offer The offer. This may be an updated offer. |
| 8295 | */ |
| 8296 | private static void informOffer(@NonNull NetworkRequestInfo nri, |
| 8297 | @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) { |
| 8298 | final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null; |
| 8299 | final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null; |
| 8300 | |
| 8301 | // Multi-layer requests have a currently active request, the one being satisfied. |
| 8302 | // Since the system will try to bring up a better network than is currently satisfying |
| 8303 | // the request, NetworkProviders need to be told the offers matching the requests *above* |
| 8304 | // the currently satisfied one are needed, that the ones *below* the satisfied one are |
| 8305 | // not needed, and the offer is needed for the active request iff the offer can beat |
| 8306 | // the satisfier. |
| 8307 | // For non-multilayer requests, the logic above gracefully degenerates to only the |
| 8308 | // last case. |
| 8309 | // To achieve this, the loop below will proceed in three steps. In a first phase, inform |
| 8310 | // providers that the offer is needed for this request, until the active request is found. |
| 8311 | // In a second phase, deal with the currently active request. In a third phase, inform |
| 8312 | // the providers that offer is unneeded for the remaining requests. |
| 8313 | |
| 8314 | // First phase : inform providers of all requests above the active request. |
| 8315 | int i; |
| 8316 | for (i = 0; nri.mRequests.size() > i; ++i) { |
| 8317 | final NetworkRequest request = nri.mRequests.get(i); |
| 8318 | if (activeRequest == request) break; // Found the active request : go to phase 2 |
| 8319 | if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers |
| 8320 | // Since this request is higher-priority than the one currently satisfied, if the |
| 8321 | // offer can satisfy it, the provider should try and bring up the network for sure ; |
| 8322 | // no need to even ask the ranker – an offer that can satisfy is always better than |
| 8323 | // no network. Hence tell the provider so unless it already knew. |
| 8324 | if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) { |
| 8325 | offer.onNetworkNeeded(request); |
| 8326 | } |
| 8327 | } |
| 8328 | |
| 8329 | // Second phase : deal with the active request (if any) |
| 8330 | if (null != activeRequest && activeRequest.isRequest()) { |
| 8331 | final boolean oldNeeded = offer.neededFor(activeRequest); |
| 8332 | // An offer is needed if it is currently served by this provider or if this offer |
| 8333 | // can beat the current satisfier. |
| 8334 | final boolean currentlyServing = satisfier != null |
| 8335 | && satisfier.factorySerialNumber == offer.providerId; |
| 8336 | final boolean newNeeded = (currentlyServing |
| 8337 | || (activeRequest.canBeSatisfiedBy(offer.caps) |
| 8338 | && networkRanker.mightBeat(activeRequest, satisfier, offer))); |
| 8339 | if (newNeeded != oldNeeded) { |
| 8340 | if (newNeeded) { |
| 8341 | offer.onNetworkNeeded(activeRequest); |
| 8342 | } else { |
| 8343 | // The offer used to be able to beat the satisfier. Now it can't. |
| 8344 | offer.onNetworkUnneeded(activeRequest); |
| 8345 | } |
| 8346 | } |
| 8347 | } |
| 8348 | |
| 8349 | // Third phase : inform the providers that the offer isn't needed for any request |
| 8350 | // below the active one. |
| 8351 | for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) { |
| 8352 | final NetworkRequest request = nri.mRequests.get(i); |
| 8353 | if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers |
| 8354 | // Since this request is lower-priority than the one currently satisfied, if the |
| 8355 | // offer can satisfy it, the provider should not try and bring up the network. |
| 8356 | // Hence tell the provider so unless it already knew. |
| 8357 | if (offer.neededFor(request)) { |
| 8358 | offer.onNetworkUnneeded(request); |
| 8359 | } |
| 8360 | } |
| 8361 | } |
| 8362 | |
| 8363 | private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) { |
| 8364 | for (int i = 0; i < nai.numNetworkRequests(); i++) { |
| 8365 | NetworkRequest nr = nai.requestAt(i); |
| 8366 | if (nr.legacyType != TYPE_NONE && nr.isRequest()) { |
| 8367 | // legacy type tracker filters out repeat adds |
| 8368 | mLegacyTypeTracker.add(nr.legacyType, nai); |
| 8369 | } |
| 8370 | } |
| 8371 | |
| 8372 | // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above, |
| 8373 | // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest |
| 8374 | // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the |
| 8375 | // newNetwork to the tracker explicitly (it's a no-op if it has already been added). |
| 8376 | if (nai.isVPN()) { |
| 8377 | mLegacyTypeTracker.add(TYPE_VPN, nai); |
| 8378 | } |
| 8379 | } |
| 8380 | |
| 8381 | private void updateInetCondition(NetworkAgentInfo nai) { |
| 8382 | // Don't bother updating until we've graduated to validated at least once. |
| 8383 | if (!nai.everValidated) return; |
| 8384 | // For now only update icons for the default connection. |
| 8385 | // TODO: Update WiFi and cellular icons separately. b/17237507 |
| 8386 | if (!isDefaultNetwork(nai)) return; |
| 8387 | |
| 8388 | int newInetCondition = nai.lastValidated ? 100 : 0; |
| 8389 | // Don't repeat publish. |
| 8390 | if (newInetCondition == mDefaultInetConditionPublished) return; |
| 8391 | |
| 8392 | mDefaultInetConditionPublished = newInetCondition; |
| 8393 | sendInetConditionBroadcast(nai.networkInfo); |
| 8394 | } |
| 8395 | |
| 8396 | @NonNull |
| 8397 | private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) { |
| 8398 | final NetworkInfo newInfo = new NetworkInfo(info); |
| 8399 | // The suspended and roaming bits are managed in NetworkCapabilities. |
| 8400 | final boolean suspended = |
| 8401 | !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED); |
| 8402 | if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) { |
| 8403 | // Only override the state with SUSPENDED if the network is currently in CONNECTED |
| 8404 | // state. This is because the network could have been suspended before connecting, |
| 8405 | // or it could be disconnecting while being suspended, and in both these cases |
| 8406 | // the state should not be overridden. Note that the only detailed state that |
| 8407 | // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to |
| 8408 | // worry about multiple different substates of CONNECTED. |
| 8409 | newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(), |
| 8410 | info.getExtraInfo()); |
| 8411 | } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) { |
| 8412 | // SUSPENDED state is currently only overridden from CONNECTED state. In the case the |
| 8413 | // network agent is created, then goes to suspended, then goes out of suspended without |
| 8414 | // ever setting connected. Check if network agent is ever connected to update the state. |
| 8415 | newInfo.setDetailedState(nai.everConnected |
| 8416 | ? NetworkInfo.DetailedState.CONNECTED |
| 8417 | : NetworkInfo.DetailedState.CONNECTING, |
| 8418 | info.getReason(), |
| 8419 | info.getExtraInfo()); |
| 8420 | } |
| 8421 | newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)); |
| 8422 | return newInfo; |
| 8423 | } |
| 8424 | |
| 8425 | private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) { |
| 8426 | final NetworkInfo newInfo = mixInInfo(networkAgent, info); |
| 8427 | |
| 8428 | final NetworkInfo.State state = newInfo.getState(); |
| 8429 | NetworkInfo oldInfo = null; |
| 8430 | synchronized (networkAgent) { |
| 8431 | oldInfo = networkAgent.networkInfo; |
| 8432 | networkAgent.networkInfo = newInfo; |
| 8433 | } |
| 8434 | |
| 8435 | if (DBG) { |
| 8436 | log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from " |
| 8437 | + oldInfo.getState() + " to " + state); |
| 8438 | } |
| 8439 | |
| 8440 | if (!networkAgent.created |
| 8441 | && (state == NetworkInfo.State.CONNECTED |
| 8442 | || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) { |
| 8443 | |
| 8444 | // A network that has just connected has zero requests and is thus a foreground network. |
| 8445 | networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND); |
| 8446 | |
| 8447 | if (!createNativeNetwork(networkAgent)) return; |
| 8448 | if (networkAgent.supportsUnderlyingNetworks()) { |
| 8449 | // Initialize the network's capabilities to their starting values according to the |
| 8450 | // underlying networks. This ensures that the capabilities are correct before |
| 8451 | // anything happens to the network. |
| 8452 | updateCapabilitiesForNetwork(networkAgent); |
| 8453 | } |
| 8454 | networkAgent.created = true; |
| 8455 | networkAgent.onNetworkCreated(); |
| 8456 | } |
| 8457 | |
| 8458 | if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) { |
| 8459 | networkAgent.everConnected = true; |
| 8460 | |
| 8461 | // NetworkCapabilities need to be set before sending the private DNS config to |
| 8462 | // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required. |
| 8463 | networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities); |
| 8464 | |
| 8465 | handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig()); |
| 8466 | updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties), |
| 8467 | null); |
| 8468 | |
| 8469 | // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect |
| 8470 | // command must be sent after updating LinkProperties to maximize chances of |
| 8471 | // NetworkMonitor seeing the correct LinkProperties when starting. |
| 8472 | // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call. |
| 8473 | if (networkAgent.networkAgentConfig.acceptPartialConnectivity) { |
| 8474 | networkAgent.networkMonitor().setAcceptPartialConnectivity(); |
| 8475 | } |
| 8476 | networkAgent.networkMonitor().notifyNetworkConnected( |
| 8477 | new LinkProperties(networkAgent.linkProperties, |
| 8478 | true /* parcelSensitiveFields */), |
| 8479 | networkAgent.networkCapabilities); |
| 8480 | scheduleUnvalidatedPrompt(networkAgent); |
| 8481 | |
| 8482 | // Whether a particular NetworkRequest listen should cause signal strength thresholds to |
| 8483 | // be communicated to a particular NetworkAgent depends only on the network's immutable, |
| 8484 | // capabilities, so it only needs to be done once on initial connect, not every time the |
| 8485 | // network's capabilities change. Note that we do this before rematching the network, |
| 8486 | // so we could decide to tear it down immediately afterwards. That's fine though - on |
| 8487 | // disconnection NetworkAgents should stop any signal strength monitoring they have been |
| 8488 | // doing. |
| 8489 | updateSignalStrengthThresholds(networkAgent, "CONNECT", null); |
| 8490 | |
| 8491 | // Before first rematching networks, put an inactivity timer without any request, this |
| 8492 | // allows {@code updateInactivityState} to update the state accordingly and prevent |
| 8493 | // tearing down for any {@code unneeded} evaluation in this period. |
| 8494 | // Note that the timer will not be rescheduled since the expiry time is |
| 8495 | // fixed after connection regardless of the network satisfying other requests or not. |
| 8496 | // But it will be removed as soon as the network satisfies a request for the first time. |
| 8497 | networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE, |
| 8498 | SystemClock.elapsedRealtime(), mNascentDelayMs); |
| 8499 | networkAgent.setInactive(); |
| 8500 | |
| 8501 | // Consider network even though it is not yet validated. |
| 8502 | rematchAllNetworksAndRequests(); |
| 8503 | |
| 8504 | // This has to happen after matching the requests, because callbacks are just requests. |
| 8505 | notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK); |
| 8506 | } else if (state == NetworkInfo.State.DISCONNECTED) { |
| 8507 | networkAgent.disconnect(); |
| 8508 | if (networkAgent.isVPN()) { |
| 8509 | updateUids(networkAgent, networkAgent.networkCapabilities, null); |
| 8510 | } |
| 8511 | disconnectAndDestroyNetwork(networkAgent); |
| 8512 | if (networkAgent.isVPN()) { |
| 8513 | // As the active or bound network changes for apps, broadcast the default proxy, as |
| 8514 | // apps may need to update their proxy data. This is called after disconnecting from |
| 8515 | // VPN to make sure we do not broadcast the old proxy data. |
| 8516 | // TODO(b/122649188): send the broadcast only to VPN users. |
| 8517 | mProxyTracker.sendProxyBroadcast(); |
| 8518 | } |
| 8519 | } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED || |
| 8520 | state == NetworkInfo.State.SUSPENDED)) { |
| 8521 | mLegacyTypeTracker.update(networkAgent); |
| 8522 | } |
| 8523 | } |
| 8524 | |
| 8525 | private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) { |
| 8526 | if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score); |
| 8527 | nai.setScore(score); |
| 8528 | rematchAllNetworksAndRequests(); |
| 8529 | } |
| 8530 | |
| 8531 | // Notify only this one new request of the current state. Transfer all the |
| 8532 | // current state by calling NetworkCapabilities and LinkProperties callbacks |
| 8533 | // so that callers can be guaranteed to have as close to atomicity in state |
| 8534 | // transfer as can be supported by this current API. |
| 8535 | protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) { |
| 8536 | mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri); |
| 8537 | if (nri.mPendingIntent != null) { |
| 8538 | sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE); |
| 8539 | // Attempt no subsequent state pushes where intents are involved. |
| 8540 | return; |
| 8541 | } |
| 8542 | |
| 8543 | final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE); |
| 8544 | final boolean metered = nai.networkCapabilities.isMetered(); |
| 8545 | final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges); |
| 8546 | callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, |
| 8547 | getBlockedState(blockedReasons, metered, vpnBlocked)); |
| 8548 | } |
| 8549 | |
| 8550 | // Notify the requests on this NAI that the network is now lingered. |
| 8551 | private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) { |
| 8552 | final int lingerTime = (int) (nai.getInactivityExpiry() - now); |
| 8553 | notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime); |
| 8554 | } |
| 8555 | |
| 8556 | private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) { |
| 8557 | if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK; |
| 8558 | return vpnBlocked |
| 8559 | ? reasons | BLOCKED_REASON_LOCKDOWN_VPN |
| 8560 | : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN; |
| 8561 | } |
| 8562 | |
| 8563 | private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) { |
| 8564 | if (blockedReasons == BLOCKED_REASON_NONE) { |
| 8565 | mUidBlockedReasons.delete(uid); |
| 8566 | } else { |
| 8567 | mUidBlockedReasons.put(uid, blockedReasons); |
| 8568 | } |
| 8569 | } |
| 8570 | |
| 8571 | /** |
| 8572 | * Notify of the blocked state apps with a registered callback matching a given NAI. |
| 8573 | * |
| 8574 | * Unlike other callbacks, blocked status is different between each individual uid. So for |
| 8575 | * any given nai, all requests need to be considered according to the uid who filed it. |
| 8576 | * |
| 8577 | * @param nai The target NetworkAgentInfo. |
| 8578 | * @param oldMetered True if the previous network capabilities were metered. |
| 8579 | * @param newMetered True if the current network capabilities are metered. |
| 8580 | * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN. |
| 8581 | * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN. |
| 8582 | */ |
| 8583 | private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered, |
| 8584 | boolean newMetered, List<UidRange> oldBlockedUidRanges, |
| 8585 | List<UidRange> newBlockedUidRanges) { |
| 8586 | |
| 8587 | for (int i = 0; i < nai.numNetworkRequests(); i++) { |
| 8588 | NetworkRequest nr = nai.requestAt(i); |
| 8589 | NetworkRequestInfo nri = mNetworkRequests.get(nr); |
| 8590 | |
| 8591 | final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE); |
| 8592 | final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges); |
| 8593 | final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges) |
| 8594 | ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges) |
| 8595 | : oldVpnBlocked; |
| 8596 | |
| 8597 | final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked); |
| 8598 | final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked); |
| 8599 | if (oldBlockedState != newBlockedState) { |
| 8600 | callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, |
| 8601 | newBlockedState); |
| 8602 | } |
| 8603 | } |
| 8604 | } |
| 8605 | |
| 8606 | /** |
| 8607 | * Notify apps with a given UID of the new blocked state according to new uid state. |
| 8608 | * @param uid The uid for which the rules changed. |
| 8609 | * @param blockedReasons The reasons for why an uid is blocked. |
| 8610 | */ |
| 8611 | private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) { |
| 8612 | for (final NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 8613 | final boolean metered = nai.networkCapabilities.isMetered(); |
| 8614 | final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges); |
| 8615 | |
| 8616 | final int oldBlockedState = getBlockedState( |
| 8617 | mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked); |
| 8618 | final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked); |
| 8619 | if (oldBlockedState == newBlockedState) { |
| 8620 | continue; |
| 8621 | } |
| 8622 | for (int i = 0; i < nai.numNetworkRequests(); i++) { |
| 8623 | NetworkRequest nr = nai.requestAt(i); |
| 8624 | NetworkRequestInfo nri = mNetworkRequests.get(nr); |
| 8625 | if (nri != null && nri.mAsUid == uid) { |
| 8626 | callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED, |
| 8627 | newBlockedState); |
| 8628 | } |
| 8629 | } |
| 8630 | } |
| 8631 | } |
| 8632 | |
| 8633 | @VisibleForTesting |
| 8634 | protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) { |
| 8635 | // The NetworkInfo we actually send out has no bearing on the real |
| 8636 | // state of affairs. For example, if the default connection is mobile, |
| 8637 | // and a request for HIPRI has just gone away, we need to pretend that |
| 8638 | // HIPRI has just disconnected. So we need to set the type to HIPRI and |
| 8639 | // the state to DISCONNECTED, even though the network is of type MOBILE |
| 8640 | // and is still connected. |
| 8641 | NetworkInfo info = new NetworkInfo(nai.networkInfo); |
| 8642 | info.setType(type); |
| 8643 | filterForLegacyLockdown(info); |
| 8644 | if (state != DetailedState.DISCONNECTED) { |
| 8645 | info.setDetailedState(state, null, info.getExtraInfo()); |
| 8646 | sendConnectedBroadcast(info); |
| 8647 | } else { |
| 8648 | info.setDetailedState(state, info.getReason(), info.getExtraInfo()); |
| 8649 | Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); |
| 8650 | intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); |
| 8651 | intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); |
| 8652 | if (info.isFailover()) { |
| 8653 | intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); |
| 8654 | nai.networkInfo.setFailover(false); |
| 8655 | } |
| 8656 | if (info.getReason() != null) { |
| 8657 | intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); |
| 8658 | } |
| 8659 | if (info.getExtraInfo() != null) { |
| 8660 | intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo()); |
| 8661 | } |
| 8662 | NetworkAgentInfo newDefaultAgent = null; |
| 8663 | if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) { |
| 8664 | newDefaultAgent = mDefaultRequest.getSatisfier(); |
| 8665 | if (newDefaultAgent != null) { |
| 8666 | intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, |
| 8667 | newDefaultAgent.networkInfo); |
| 8668 | } else { |
| 8669 | intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); |
| 8670 | } |
| 8671 | } |
| 8672 | intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, |
| 8673 | mDefaultInetConditionPublished); |
| 8674 | sendStickyBroadcast(intent); |
| 8675 | if (newDefaultAgent != null) { |
| 8676 | sendConnectedBroadcast(newDefaultAgent.networkInfo); |
| 8677 | } |
| 8678 | } |
| 8679 | } |
| 8680 | |
| 8681 | protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) { |
| 8682 | if (VDBG || DDBG) { |
| 8683 | String notification = ConnectivityManager.getCallbackName(notifyType); |
| 8684 | log("notifyType " + notification + " for " + networkAgent.toShortString()); |
| 8685 | } |
| 8686 | for (int i = 0; i < networkAgent.numNetworkRequests(); i++) { |
| 8687 | NetworkRequest nr = networkAgent.requestAt(i); |
| 8688 | NetworkRequestInfo nri = mNetworkRequests.get(nr); |
| 8689 | if (VDBG) log(" sending notification for " + nr); |
| 8690 | if (nri.mPendingIntent == null) { |
| 8691 | callCallbackForRequest(nri, networkAgent, notifyType, arg1); |
| 8692 | } else { |
| 8693 | sendPendingIntentForRequest(nri, networkAgent, notifyType); |
| 8694 | } |
| 8695 | } |
| 8696 | } |
| 8697 | |
| 8698 | protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) { |
| 8699 | notifyNetworkCallbacks(networkAgent, notifyType, 0); |
| 8700 | } |
| 8701 | |
| 8702 | /** |
| 8703 | * Returns the list of all interfaces that could be used by network traffic that does not |
| 8704 | * explicitly specify a network. This includes the default network, but also all VPNs that are |
| 8705 | * currently connected. |
| 8706 | * |
| 8707 | * Must be called on the handler thread. |
| 8708 | */ |
| 8709 | @NonNull |
| 8710 | private ArrayList<Network> getDefaultNetworks() { |
| 8711 | ensureRunningOnConnectivityServiceThread(); |
| 8712 | final ArrayList<Network> defaultNetworks = new ArrayList<>(); |
| 8713 | final Set<Integer> activeNetIds = new ArraySet<>(); |
| 8714 | for (final NetworkRequestInfo nri : mDefaultNetworkRequests) { |
| 8715 | if (nri.isBeingSatisfied()) { |
| 8716 | activeNetIds.add(nri.getSatisfier().network().netId); |
| 8717 | } |
| 8718 | } |
| 8719 | for (NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 8720 | if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) { |
| 8721 | defaultNetworks.add(nai.network); |
| 8722 | } |
| 8723 | } |
| 8724 | return defaultNetworks; |
| 8725 | } |
| 8726 | |
| 8727 | /** |
| 8728 | * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the |
| 8729 | * active iface's tracked properties has changed. |
| 8730 | */ |
| 8731 | private void notifyIfacesChangedForNetworkStats() { |
| 8732 | ensureRunningOnConnectivityServiceThread(); |
| 8733 | String activeIface = null; |
| 8734 | LinkProperties activeLinkProperties = getActiveLinkProperties(); |
| 8735 | if (activeLinkProperties != null) { |
| 8736 | activeIface = activeLinkProperties.getInterfaceName(); |
| 8737 | } |
| 8738 | |
| 8739 | final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo(); |
| 8740 | try { |
| 8741 | final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>(); |
junyulai | 0f57022 | 2021-03-05 14:46:25 +0800 | [diff] [blame] | 8742 | for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) { |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 8743 | snapshots.add(snapshot); |
| 8744 | } |
| 8745 | mStatsManager.notifyNetworkStatus(getDefaultNetworks(), |
| 8746 | snapshots, activeIface, Arrays.asList(underlyingNetworkInfos)); |
| 8747 | } catch (Exception ignored) { |
| 8748 | } |
| 8749 | } |
| 8750 | |
| 8751 | @Override |
| 8752 | public String getCaptivePortalServerUrl() { |
| 8753 | enforceNetworkStackOrSettingsPermission(); |
| 8754 | String settingUrl = mResources.get().getString( |
| 8755 | R.string.config_networkCaptivePortalServerUrl); |
| 8756 | |
| 8757 | if (!TextUtils.isEmpty(settingUrl)) { |
| 8758 | return settingUrl; |
| 8759 | } |
| 8760 | |
| 8761 | settingUrl = Settings.Global.getString(mContext.getContentResolver(), |
| 8762 | ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL); |
| 8763 | if (!TextUtils.isEmpty(settingUrl)) { |
| 8764 | return settingUrl; |
| 8765 | } |
| 8766 | |
| 8767 | return DEFAULT_CAPTIVE_PORTAL_HTTP_URL; |
| 8768 | } |
| 8769 | |
| 8770 | @Override |
| 8771 | public void startNattKeepalive(Network network, int intervalSeconds, |
| 8772 | ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) { |
| 8773 | enforceKeepalivePermission(); |
| 8774 | mKeepaliveTracker.startNattKeepalive( |
| 8775 | getNetworkAgentInfoForNetwork(network), null /* fd */, |
| 8776 | intervalSeconds, cb, |
| 8777 | srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT); |
| 8778 | } |
| 8779 | |
| 8780 | @Override |
| 8781 | public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId, |
| 8782 | int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr, |
| 8783 | String dstAddr) { |
| 8784 | try { |
| 8785 | final FileDescriptor fd = pfd.getFileDescriptor(); |
| 8786 | mKeepaliveTracker.startNattKeepalive( |
| 8787 | getNetworkAgentInfoForNetwork(network), fd, resourceId, |
| 8788 | intervalSeconds, cb, |
| 8789 | srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT); |
| 8790 | } finally { |
| 8791 | // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks. |
| 8792 | // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately. |
| 8793 | if (pfd != null && Binder.getCallingPid() != Process.myPid()) { |
| 8794 | IoUtils.closeQuietly(pfd); |
| 8795 | } |
| 8796 | } |
| 8797 | } |
| 8798 | |
| 8799 | @Override |
| 8800 | public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds, |
| 8801 | ISocketKeepaliveCallback cb) { |
| 8802 | try { |
| 8803 | enforceKeepalivePermission(); |
| 8804 | final FileDescriptor fd = pfd.getFileDescriptor(); |
| 8805 | mKeepaliveTracker.startTcpKeepalive( |
| 8806 | getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb); |
| 8807 | } finally { |
| 8808 | // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks. |
| 8809 | // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately. |
| 8810 | if (pfd != null && Binder.getCallingPid() != Process.myPid()) { |
| 8811 | IoUtils.closeQuietly(pfd); |
| 8812 | } |
| 8813 | } |
| 8814 | } |
| 8815 | |
| 8816 | @Override |
| 8817 | public void stopKeepalive(Network network, int slot) { |
| 8818 | mHandler.sendMessage(mHandler.obtainMessage( |
| 8819 | NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network)); |
| 8820 | } |
| 8821 | |
| 8822 | @Override |
| 8823 | public void factoryReset() { |
| 8824 | enforceSettingsPermission(); |
| 8825 | |
Treehugger Robot | fac2a72 | 2021-05-21 02:42:59 +0000 | [diff] [blame] | 8826 | final int uid = mDeps.getCallingUid(); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 8827 | final long token = Binder.clearCallingIdentity(); |
| 8828 | try { |
Treehugger Robot | fac2a72 | 2021-05-21 02:42:59 +0000 | [diff] [blame] | 8829 | if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET, |
| 8830 | UserHandle.getUserHandleForUid(uid))) { |
| 8831 | return; |
| 8832 | } |
| 8833 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 8834 | final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext); |
| 8835 | ipMemoryStore.factoryReset(); |
Treehugger Robot | fac2a72 | 2021-05-21 02:42:59 +0000 | [diff] [blame] | 8836 | |
| 8837 | // Turn airplane mode off |
| 8838 | setAirplaneMode(false); |
| 8839 | |
| 8840 | // restore private DNS settings to default mode (opportunistic) |
| 8841 | if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS, |
| 8842 | UserHandle.getUserHandleForUid(uid))) { |
| 8843 | ConnectivitySettingsManager.setPrivateDnsMode(mContext, |
| 8844 | PRIVATE_DNS_MODE_OPPORTUNISTIC); |
| 8845 | } |
| 8846 | |
| 8847 | Settings.Global.putString(mContext.getContentResolver(), |
| 8848 | ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 8849 | } finally { |
| 8850 | Binder.restoreCallingIdentity(token); |
| 8851 | } |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 8852 | } |
| 8853 | |
| 8854 | @Override |
| 8855 | public byte[] getNetworkWatchlistConfigHash() { |
| 8856 | NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class); |
| 8857 | if (nwm == null) { |
| 8858 | loge("Unable to get NetworkWatchlistManager"); |
| 8859 | return null; |
| 8860 | } |
| 8861 | // Redirect it to network watchlist service to access watchlist file and calculate hash. |
| 8862 | return nwm.getWatchlistConfigHash(); |
| 8863 | } |
| 8864 | |
| 8865 | private void logNetworkEvent(NetworkAgentInfo nai, int evtype) { |
| 8866 | int[] transports = nai.networkCapabilities.getTransportTypes(); |
| 8867 | mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype)); |
| 8868 | } |
| 8869 | |
| 8870 | private static boolean toBool(int encodedBoolean) { |
| 8871 | return encodedBoolean != 0; // Only 0 means false. |
| 8872 | } |
| 8873 | |
| 8874 | private static int encodeBool(boolean b) { |
| 8875 | return b ? 1 : 0; |
| 8876 | } |
| 8877 | |
| 8878 | @Override |
| 8879 | public int handleShellCommand(@NonNull ParcelFileDescriptor in, |
| 8880 | @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err, |
| 8881 | @NonNull String[] args) { |
| 8882 | return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(), |
| 8883 | err.getFileDescriptor(), args); |
| 8884 | } |
| 8885 | |
| 8886 | private class ShellCmd extends BasicShellCommandHandler { |
| 8887 | @Override |
| 8888 | public int onCommand(String cmd) { |
| 8889 | if (cmd == null) { |
| 8890 | return handleDefaultCommands(cmd); |
| 8891 | } |
| 8892 | final PrintWriter pw = getOutPrintWriter(); |
| 8893 | try { |
| 8894 | switch (cmd) { |
| 8895 | case "airplane-mode": |
| 8896 | final String action = getNextArg(); |
| 8897 | if ("enable".equals(action)) { |
| 8898 | setAirplaneMode(true); |
| 8899 | return 0; |
| 8900 | } else if ("disable".equals(action)) { |
| 8901 | setAirplaneMode(false); |
| 8902 | return 0; |
| 8903 | } else if (action == null) { |
| 8904 | final ContentResolver cr = mContext.getContentResolver(); |
| 8905 | final int enabled = Settings.Global.getInt(cr, |
| 8906 | Settings.Global.AIRPLANE_MODE_ON); |
| 8907 | pw.println(enabled == 0 ? "disabled" : "enabled"); |
| 8908 | return 0; |
| 8909 | } else { |
| 8910 | onHelp(); |
| 8911 | return -1; |
| 8912 | } |
| 8913 | default: |
| 8914 | return handleDefaultCommands(cmd); |
| 8915 | } |
| 8916 | } catch (Exception e) { |
| 8917 | pw.println(e); |
| 8918 | } |
| 8919 | return -1; |
| 8920 | } |
| 8921 | |
| 8922 | @Override |
| 8923 | public void onHelp() { |
| 8924 | PrintWriter pw = getOutPrintWriter(); |
| 8925 | pw.println("Connectivity service commands:"); |
| 8926 | pw.println(" help"); |
| 8927 | pw.println(" Print this help text."); |
| 8928 | pw.println(" airplane-mode [enable|disable]"); |
| 8929 | pw.println(" Turn airplane mode on or off."); |
| 8930 | pw.println(" airplane-mode"); |
| 8931 | pw.println(" Get airplane mode."); |
| 8932 | } |
| 8933 | } |
| 8934 | |
| 8935 | private int getVpnType(@Nullable NetworkAgentInfo vpn) { |
| 8936 | if (vpn == null) return VpnManager.TYPE_VPN_NONE; |
| 8937 | final TransportInfo ti = vpn.networkCapabilities.getTransportInfo(); |
| 8938 | if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE; |
| 8939 | return ((VpnTransportInfo) ti).getType(); |
| 8940 | } |
| 8941 | |
| 8942 | /** |
| 8943 | * @param connectionInfo the connection to resolve. |
| 8944 | * @return {@code uid} if the connection is found and the app has permission to observe it |
| 8945 | * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the |
| 8946 | * connection is not found. |
| 8947 | */ |
| 8948 | public int getConnectionOwnerUid(ConnectionInfo connectionInfo) { |
| 8949 | if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) { |
| 8950 | throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol); |
| 8951 | } |
| 8952 | |
| 8953 | final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol, |
| 8954 | connectionInfo.local, connectionInfo.remote); |
| 8955 | |
| 8956 | if (uid == INVALID_UID) return uid; // Not found. |
| 8957 | |
| 8958 | // Connection owner UIDs are visible only to the network stack and to the VpnService-based |
| 8959 | // VPN, if any, that applies to the UID that owns the connection. |
| 8960 | if (checkNetworkStackPermission()) return uid; |
| 8961 | |
| 8962 | final NetworkAgentInfo vpn = getVpnForUid(uid); |
| 8963 | if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE |
| 8964 | || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) { |
| 8965 | return INVALID_UID; |
| 8966 | } |
| 8967 | |
| 8968 | return uid; |
| 8969 | } |
| 8970 | |
| 8971 | /** |
| 8972 | * Returns a IBinder to a TestNetworkService. Will be lazily created as needed. |
| 8973 | * |
| 8974 | * <p>The TestNetworkService must be run in the system server due to TUN creation. |
| 8975 | */ |
| 8976 | @Override |
| 8977 | public IBinder startOrGetTestNetworkService() { |
| 8978 | synchronized (mTNSLock) { |
| 8979 | TestNetworkService.enforceTestNetworkPermissions(mContext); |
| 8980 | |
| 8981 | if (mTNS == null) { |
| 8982 | mTNS = new TestNetworkService(mContext); |
| 8983 | } |
| 8984 | |
| 8985 | return mTNS; |
| 8986 | } |
| 8987 | } |
| 8988 | |
| 8989 | /** |
| 8990 | * Handler used for managing all Connectivity Diagnostics related functions. |
| 8991 | * |
| 8992 | * @see android.net.ConnectivityDiagnosticsManager |
| 8993 | * |
| 8994 | * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file |
| 8995 | */ |
| 8996 | @VisibleForTesting |
| 8997 | class ConnectivityDiagnosticsHandler extends Handler { |
| 8998 | private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName(); |
| 8999 | |
| 9000 | /** |
| 9001 | * Used to handle ConnectivityDiagnosticsCallback registration events from {@link |
| 9002 | * android.net.ConnectivityDiagnosticsManager}. |
| 9003 | * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and |
| 9004 | * NetworkRequestInfo to be registered |
| 9005 | */ |
| 9006 | private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1; |
| 9007 | |
| 9008 | /** |
| 9009 | * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link |
| 9010 | * android.net.ConnectivityDiagnosticsManager}. |
| 9011 | * obj = the IConnectivityDiagnosticsCallback to be unregistered |
| 9012 | * arg1 = the uid of the caller |
| 9013 | */ |
| 9014 | private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2; |
| 9015 | |
| 9016 | /** |
| 9017 | * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks |
| 9018 | * after processing {@link #EVENT_NETWORK_TESTED} events. |
| 9019 | * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from |
| 9020 | * NetworkMonitor. |
| 9021 | * data = PersistableBundle of extras passed from NetworkMonitor. |
| 9022 | * |
| 9023 | * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}. |
| 9024 | */ |
| 9025 | private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED; |
| 9026 | |
| 9027 | /** |
| 9028 | * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has |
| 9029 | * been detected on the network. |
| 9030 | * obj = Long the timestamp (in millis) for when the suspected data stall was detected. |
| 9031 | * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method. |
| 9032 | * arg2 = NetID. |
| 9033 | * data = PersistableBundle of extras passed from NetworkMonitor. |
| 9034 | */ |
| 9035 | private static final int EVENT_DATA_STALL_SUSPECTED = 4; |
| 9036 | |
| 9037 | /** |
| 9038 | * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to |
| 9039 | * the platform. This event will invoke {@link |
| 9040 | * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned |
| 9041 | * callbacks. |
| 9042 | * obj = Network that was reported on |
| 9043 | * arg1 = boolint for the quality reported |
| 9044 | */ |
| 9045 | private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5; |
| 9046 | |
| 9047 | private ConnectivityDiagnosticsHandler(Looper looper) { |
| 9048 | super(looper); |
| 9049 | } |
| 9050 | |
| 9051 | @Override |
| 9052 | public void handleMessage(Message msg) { |
| 9053 | switch (msg.what) { |
| 9054 | case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: { |
| 9055 | handleRegisterConnectivityDiagnosticsCallback( |
| 9056 | (ConnectivityDiagnosticsCallbackInfo) msg.obj); |
| 9057 | break; |
| 9058 | } |
| 9059 | case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: { |
| 9060 | handleUnregisterConnectivityDiagnosticsCallback( |
| 9061 | (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1); |
| 9062 | break; |
| 9063 | } |
| 9064 | case EVENT_NETWORK_TESTED: { |
| 9065 | final ConnectivityReportEvent reportEvent = |
| 9066 | (ConnectivityReportEvent) msg.obj; |
| 9067 | |
| 9068 | handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras); |
| 9069 | break; |
| 9070 | } |
| 9071 | case EVENT_DATA_STALL_SUSPECTED: { |
| 9072 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2); |
| 9073 | final Pair<Long, PersistableBundle> arg = |
| 9074 | (Pair<Long, PersistableBundle>) msg.obj; |
| 9075 | if (nai == null) break; |
| 9076 | |
| 9077 | handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second); |
| 9078 | break; |
| 9079 | } |
| 9080 | case EVENT_NETWORK_CONNECTIVITY_REPORTED: { |
| 9081 | handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1)); |
| 9082 | break; |
| 9083 | } |
| 9084 | default: { |
| 9085 | Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what); |
| 9086 | } |
| 9087 | } |
| 9088 | } |
| 9089 | } |
| 9090 | |
| 9091 | /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */ |
| 9092 | @VisibleForTesting |
| 9093 | class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient { |
| 9094 | @NonNull private final IConnectivityDiagnosticsCallback mCb; |
| 9095 | @NonNull private final NetworkRequestInfo mRequestInfo; |
| 9096 | @NonNull private final String mCallingPackageName; |
| 9097 | |
| 9098 | @VisibleForTesting |
| 9099 | ConnectivityDiagnosticsCallbackInfo( |
| 9100 | @NonNull IConnectivityDiagnosticsCallback cb, |
| 9101 | @NonNull NetworkRequestInfo nri, |
| 9102 | @NonNull String callingPackageName) { |
| 9103 | mCb = cb; |
| 9104 | mRequestInfo = nri; |
| 9105 | mCallingPackageName = callingPackageName; |
| 9106 | } |
| 9107 | |
| 9108 | @Override |
| 9109 | public void binderDied() { |
| 9110 | log("ConnectivityDiagnosticsCallback IBinder died."); |
| 9111 | unregisterConnectivityDiagnosticsCallback(mCb); |
| 9112 | } |
| 9113 | } |
| 9114 | |
| 9115 | /** |
| 9116 | * Class used for sending information from {@link |
| 9117 | * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it. |
| 9118 | */ |
| 9119 | private static class NetworkTestedResults { |
| 9120 | private final int mNetId; |
| 9121 | private final int mTestResult; |
| 9122 | private final long mTimestampMillis; |
| 9123 | @Nullable private final String mRedirectUrl; |
| 9124 | |
| 9125 | private NetworkTestedResults( |
| 9126 | int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) { |
| 9127 | mNetId = netId; |
| 9128 | mTestResult = testResult; |
| 9129 | mTimestampMillis = timestampMillis; |
| 9130 | mRedirectUrl = redirectUrl; |
| 9131 | } |
| 9132 | } |
| 9133 | |
| 9134 | /** |
| 9135 | * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link |
| 9136 | * ConnectivityDiagnosticsHandler}. |
| 9137 | */ |
| 9138 | private static class ConnectivityReportEvent { |
| 9139 | private final long mTimestampMillis; |
| 9140 | @NonNull private final NetworkAgentInfo mNai; |
| 9141 | private final PersistableBundle mExtras; |
| 9142 | |
| 9143 | private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai, |
| 9144 | PersistableBundle p) { |
| 9145 | mTimestampMillis = timestampMillis; |
| 9146 | mNai = nai; |
| 9147 | mExtras = p; |
| 9148 | } |
| 9149 | } |
| 9150 | |
| 9151 | private void handleRegisterConnectivityDiagnosticsCallback( |
| 9152 | @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) { |
| 9153 | ensureRunningOnConnectivityServiceThread(); |
| 9154 | |
| 9155 | final IConnectivityDiagnosticsCallback cb = cbInfo.mCb; |
| 9156 | final IBinder iCb = cb.asBinder(); |
| 9157 | final NetworkRequestInfo nri = cbInfo.mRequestInfo; |
| 9158 | |
| 9159 | // Connectivity Diagnostics are meant to be used with a single network request. It would be |
| 9160 | // confusing for these networks to change when an NRI is satisfied in another layer. |
| 9161 | if (nri.isMultilayerRequest()) { |
| 9162 | throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer " |
| 9163 | + "network requests."); |
| 9164 | } |
| 9165 | |
| 9166 | // This means that the client registered the same callback multiple times. Do |
| 9167 | // not override the previous entry, and exit silently. |
| 9168 | if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) { |
| 9169 | if (VDBG) log("Diagnostics callback is already registered"); |
| 9170 | |
| 9171 | // Decrement the reference count for this NetworkRequestInfo. The reference count is |
| 9172 | // incremented when the NetworkRequestInfo is created as part of |
| 9173 | // enforceRequestCountLimit(). |
| 9174 | nri.decrementRequestCount(); |
| 9175 | return; |
| 9176 | } |
| 9177 | |
| 9178 | mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo); |
| 9179 | |
| 9180 | try { |
| 9181 | iCb.linkToDeath(cbInfo, 0); |
| 9182 | } catch (RemoteException e) { |
| 9183 | cbInfo.binderDied(); |
| 9184 | return; |
| 9185 | } |
| 9186 | |
| 9187 | // Once registered, provide ConnectivityReports for matching Networks |
| 9188 | final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>(); |
| 9189 | synchronized (mNetworkForNetId) { |
| 9190 | for (int i = 0; i < mNetworkForNetId.size(); i++) { |
| 9191 | final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i); |
| 9192 | // Connectivity Diagnostics rejects multilayer requests at registration hence get(0) |
| 9193 | if (nai.satisfies(nri.mRequests.get(0))) { |
| 9194 | matchingNetworks.add(nai); |
| 9195 | } |
| 9196 | } |
| 9197 | } |
| 9198 | for (final NetworkAgentInfo nai : matchingNetworks) { |
| 9199 | final ConnectivityReport report = nai.getConnectivityReport(); |
| 9200 | if (report == null) { |
| 9201 | continue; |
| 9202 | } |
| 9203 | if (!checkConnectivityDiagnosticsPermissions( |
| 9204 | nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) { |
| 9205 | continue; |
| 9206 | } |
| 9207 | |
| 9208 | try { |
| 9209 | cb.onConnectivityReportAvailable(report); |
| 9210 | } catch (RemoteException e) { |
| 9211 | // Exception while sending the ConnectivityReport. Move on to the next network. |
| 9212 | } |
| 9213 | } |
| 9214 | } |
| 9215 | |
| 9216 | private void handleUnregisterConnectivityDiagnosticsCallback( |
| 9217 | @NonNull IConnectivityDiagnosticsCallback cb, int uid) { |
| 9218 | ensureRunningOnConnectivityServiceThread(); |
| 9219 | final IBinder iCb = cb.asBinder(); |
| 9220 | |
| 9221 | final ConnectivityDiagnosticsCallbackInfo cbInfo = |
| 9222 | mConnectivityDiagnosticsCallbacks.remove(iCb); |
| 9223 | if (cbInfo == null) { |
| 9224 | if (VDBG) log("Removing diagnostics callback that is not currently registered"); |
| 9225 | return; |
| 9226 | } |
| 9227 | |
| 9228 | final NetworkRequestInfo nri = cbInfo.mRequestInfo; |
| 9229 | |
| 9230 | // Caller's UID must either be the registrants (if they are unregistering) or the System's |
| 9231 | // (if the Binder died) |
| 9232 | if (uid != nri.mUid && uid != Process.SYSTEM_UID) { |
| 9233 | if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's"); |
| 9234 | return; |
| 9235 | } |
| 9236 | |
| 9237 | // Decrement the reference count for this NetworkRequestInfo. The reference count is |
| 9238 | // incremented when the NetworkRequestInfo is created as part of |
| 9239 | // enforceRequestCountLimit(). |
| 9240 | nri.decrementRequestCount(); |
| 9241 | |
| 9242 | iCb.unlinkToDeath(cbInfo, 0); |
| 9243 | } |
| 9244 | |
| 9245 | private void handleNetworkTestedWithExtras( |
| 9246 | @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) { |
| 9247 | final NetworkAgentInfo nai = reportEvent.mNai; |
| 9248 | final NetworkCapabilities networkCapabilities = |
| 9249 | getNetworkCapabilitiesWithoutUids(nai.networkCapabilities); |
| 9250 | final ConnectivityReport report = |
| 9251 | new ConnectivityReport( |
| 9252 | reportEvent.mNai.network, |
| 9253 | reportEvent.mTimestampMillis, |
| 9254 | nai.linkProperties, |
| 9255 | networkCapabilities, |
| 9256 | extras); |
| 9257 | nai.setConnectivityReport(report); |
| 9258 | final List<IConnectivityDiagnosticsCallback> results = |
| 9259 | getMatchingPermissionedCallbacks(nai); |
| 9260 | for (final IConnectivityDiagnosticsCallback cb : results) { |
| 9261 | try { |
| 9262 | cb.onConnectivityReportAvailable(report); |
| 9263 | } catch (RemoteException ex) { |
| 9264 | loge("Error invoking onConnectivityReport", ex); |
| 9265 | } |
| 9266 | } |
| 9267 | } |
| 9268 | |
| 9269 | private void handleDataStallSuspected( |
| 9270 | @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod, |
| 9271 | @NonNull PersistableBundle extras) { |
| 9272 | final NetworkCapabilities networkCapabilities = |
| 9273 | getNetworkCapabilitiesWithoutUids(nai.networkCapabilities); |
| 9274 | final DataStallReport report = |
| 9275 | new DataStallReport( |
| 9276 | nai.network, |
| 9277 | timestampMillis, |
| 9278 | detectionMethod, |
| 9279 | nai.linkProperties, |
| 9280 | networkCapabilities, |
| 9281 | extras); |
| 9282 | final List<IConnectivityDiagnosticsCallback> results = |
| 9283 | getMatchingPermissionedCallbacks(nai); |
| 9284 | for (final IConnectivityDiagnosticsCallback cb : results) { |
| 9285 | try { |
| 9286 | cb.onDataStallSuspected(report); |
| 9287 | } catch (RemoteException ex) { |
| 9288 | loge("Error invoking onDataStallSuspected", ex); |
| 9289 | } |
| 9290 | } |
| 9291 | } |
| 9292 | |
| 9293 | private void handleNetworkConnectivityReported( |
| 9294 | @NonNull NetworkAgentInfo nai, boolean connectivity) { |
| 9295 | final List<IConnectivityDiagnosticsCallback> results = |
| 9296 | getMatchingPermissionedCallbacks(nai); |
| 9297 | for (final IConnectivityDiagnosticsCallback cb : results) { |
| 9298 | try { |
| 9299 | cb.onNetworkConnectivityReported(nai.network, connectivity); |
| 9300 | } catch (RemoteException ex) { |
| 9301 | loge("Error invoking onNetworkConnectivityReported", ex); |
| 9302 | } |
| 9303 | } |
| 9304 | } |
| 9305 | |
| 9306 | private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) { |
| 9307 | final NetworkCapabilities sanitized = new NetworkCapabilities(nc, |
| 9308 | NetworkCapabilities.REDACT_ALL); |
| 9309 | sanitized.setUids(null); |
| 9310 | sanitized.setAdministratorUids(new int[0]); |
| 9311 | sanitized.setOwnerUid(Process.INVALID_UID); |
| 9312 | return sanitized; |
| 9313 | } |
| 9314 | |
| 9315 | private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks( |
| 9316 | @NonNull NetworkAgentInfo nai) { |
| 9317 | final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>(); |
| 9318 | for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry : |
| 9319 | mConnectivityDiagnosticsCallbacks.entrySet()) { |
| 9320 | final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue(); |
| 9321 | final NetworkRequestInfo nri = cbInfo.mRequestInfo; |
| 9322 | // Connectivity Diagnostics rejects multilayer requests at registration hence get(0). |
| 9323 | if (nai.satisfies(nri.mRequests.get(0))) { |
| 9324 | if (checkConnectivityDiagnosticsPermissions( |
| 9325 | nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) { |
| 9326 | results.add(entry.getValue().mCb); |
| 9327 | } |
| 9328 | } |
| 9329 | } |
| 9330 | return results; |
| 9331 | } |
| 9332 | |
Treehugger Robot | 27b6888 | 2021-06-07 19:42:39 +0000 | [diff] [blame] | 9333 | private boolean isLocationPermissionRequiredForConnectivityDiagnostics( |
| 9334 | @NonNull NetworkAgentInfo nai) { |
| 9335 | // TODO(b/188483916): replace with a transport-agnostic location-aware check |
| 9336 | return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI); |
| 9337 | } |
| 9338 | |
Cody Kesting | 0b4be02 | 2021-05-20 22:57:07 +0000 | [diff] [blame] | 9339 | private boolean hasLocationPermission(String packageName, int uid) { |
| 9340 | // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid |
| 9341 | // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the |
| 9342 | // call in a try-catch. |
| 9343 | try { |
| 9344 | if (!mLocationPermissionChecker.checkLocationPermission( |
| 9345 | packageName, null /* featureId */, uid, null /* message */)) { |
| 9346 | return false; |
| 9347 | } |
| 9348 | } catch (SecurityException e) { |
| 9349 | return false; |
| 9350 | } |
| 9351 | |
| 9352 | return true; |
| 9353 | } |
| 9354 | |
| 9355 | private boolean ownsVpnRunningOverNetwork(int uid, Network network) { |
| 9356 | for (NetworkAgentInfo virtual : mNetworkAgentInfos) { |
| 9357 | if (virtual.supportsUnderlyingNetworks() |
| 9358 | && virtual.networkCapabilities.getOwnerUid() == uid |
| 9359 | && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) { |
| 9360 | return true; |
| 9361 | } |
| 9362 | } |
| 9363 | |
| 9364 | return false; |
| 9365 | } |
| 9366 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 9367 | @VisibleForTesting |
| 9368 | boolean checkConnectivityDiagnosticsPermissions( |
| 9369 | int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) { |
| 9370 | if (checkNetworkStackPermission(callbackPid, callbackUid)) { |
| 9371 | return true; |
| 9372 | } |
| 9373 | |
Cody Kesting | 0b4be02 | 2021-05-20 22:57:07 +0000 | [diff] [blame] | 9374 | // Administrator UIDs also contains the Owner UID |
| 9375 | final int[] administratorUids = nai.networkCapabilities.getAdministratorUids(); |
| 9376 | if (!CollectionUtils.contains(administratorUids, callbackUid) |
| 9377 | && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) { |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 9378 | return false; |
| 9379 | } |
| 9380 | |
Treehugger Robot | 27b6888 | 2021-06-07 19:42:39 +0000 | [diff] [blame] | 9381 | return !isLocationPermissionRequiredForConnectivityDiagnostics(nai) |
| 9382 | || hasLocationPermission(callbackPackageName, callbackUid); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 9383 | } |
| 9384 | |
| 9385 | @Override |
| 9386 | public void registerConnectivityDiagnosticsCallback( |
| 9387 | @NonNull IConnectivityDiagnosticsCallback callback, |
| 9388 | @NonNull NetworkRequest request, |
| 9389 | @NonNull String callingPackageName) { |
| 9390 | if (request.legacyType != TYPE_NONE) { |
| 9391 | throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated." |
| 9392 | + " Please use NetworkCapabilities instead."); |
| 9393 | } |
| 9394 | final int callingUid = mDeps.getCallingUid(); |
| 9395 | mAppOpsManager.checkPackage(callingUid, callingPackageName); |
| 9396 | |
| 9397 | // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid |
| 9398 | // and administrator uids to be safe. |
| 9399 | final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities); |
| 9400 | restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName); |
| 9401 | |
| 9402 | final NetworkRequest requestWithId = |
| 9403 | new NetworkRequest( |
| 9404 | nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN); |
| 9405 | |
| 9406 | // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit. |
| 9407 | // |
| 9408 | // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in |
| 9409 | // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the |
| 9410 | // callback's binder death. |
| 9411 | final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId); |
| 9412 | final ConnectivityDiagnosticsCallbackInfo cbInfo = |
| 9413 | new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName); |
| 9414 | |
| 9415 | mConnectivityDiagnosticsHandler.sendMessage( |
| 9416 | mConnectivityDiagnosticsHandler.obtainMessage( |
| 9417 | ConnectivityDiagnosticsHandler |
| 9418 | .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK, |
| 9419 | cbInfo)); |
| 9420 | } |
| 9421 | |
| 9422 | @Override |
| 9423 | public void unregisterConnectivityDiagnosticsCallback( |
| 9424 | @NonNull IConnectivityDiagnosticsCallback callback) { |
| 9425 | Objects.requireNonNull(callback, "callback must be non-null"); |
| 9426 | mConnectivityDiagnosticsHandler.sendMessage( |
| 9427 | mConnectivityDiagnosticsHandler.obtainMessage( |
| 9428 | ConnectivityDiagnosticsHandler |
| 9429 | .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK, |
| 9430 | mDeps.getCallingUid(), |
| 9431 | 0, |
| 9432 | callback)); |
| 9433 | } |
| 9434 | |
| 9435 | @Override |
| 9436 | public void simulateDataStall(int detectionMethod, long timestampMillis, |
| 9437 | @NonNull Network network, @NonNull PersistableBundle extras) { |
| 9438 | enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS, |
| 9439 | android.Manifest.permission.NETWORK_STACK); |
| 9440 | final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network); |
| 9441 | if (!nc.hasTransport(TRANSPORT_TEST)) { |
| 9442 | throw new SecurityException("Data Stall simluation is only possible for test networks"); |
| 9443 | } |
| 9444 | |
| 9445 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); |
| 9446 | if (nai == null || nai.creatorUid != mDeps.getCallingUid()) { |
| 9447 | throw new SecurityException("Data Stall simulation is only possible for network " |
| 9448 | + "creators"); |
| 9449 | } |
| 9450 | |
| 9451 | // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat |
| 9452 | // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the |
| 9453 | // Data Stall information as a DataStallReportParcelable and passing to |
| 9454 | // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are |
| 9455 | // still passed to ConnectivityDiagnostics (with new detection methods masked). |
| 9456 | final DataStallReportParcelable p = new DataStallReportParcelable(); |
| 9457 | p.timestampMillis = timestampMillis; |
| 9458 | p.detectionMethod = detectionMethod; |
| 9459 | |
| 9460 | if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) { |
| 9461 | p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS); |
| 9462 | } |
| 9463 | if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) { |
| 9464 | p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE); |
| 9465 | p.tcpMetricsCollectionPeriodMillis = extras.getInt( |
| 9466 | KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS); |
| 9467 | } |
| 9468 | |
| 9469 | notifyDataStallSuspected(p, network.getNetId()); |
| 9470 | } |
| 9471 | |
| 9472 | private class NetdCallback extends BaseNetdUnsolicitedEventListener { |
| 9473 | @Override |
| 9474 | public void onInterfaceClassActivityChanged(boolean isActive, int transportType, |
| 9475 | long timestampNs, int uid) { |
| 9476 | mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs); |
| 9477 | } |
| 9478 | |
| 9479 | @Override |
| 9480 | public void onInterfaceLinkStateChanged(String iface, boolean up) { |
| 9481 | for (NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 9482 | nai.clatd.interfaceLinkStateChanged(iface, up); |
| 9483 | } |
| 9484 | } |
| 9485 | |
| 9486 | @Override |
| 9487 | public void onInterfaceRemoved(String iface) { |
| 9488 | for (NetworkAgentInfo nai : mNetworkAgentInfos) { |
| 9489 | nai.clatd.interfaceRemoved(iface); |
| 9490 | } |
| 9491 | } |
| 9492 | } |
| 9493 | |
| 9494 | private final LegacyNetworkActivityTracker mNetworkActivityTracker; |
| 9495 | |
| 9496 | /** |
| 9497 | * Class used for updating network activity tracking with netd and notify network activity |
| 9498 | * changes. |
| 9499 | */ |
| 9500 | private static final class LegacyNetworkActivityTracker { |
| 9501 | private static final int NO_UID = -1; |
| 9502 | private final Context mContext; |
| 9503 | private final INetd mNetd; |
| 9504 | private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners = |
| 9505 | new RemoteCallbackList<>(); |
| 9506 | // Indicate the current system default network activity is active or not. |
| 9507 | @GuardedBy("mActiveIdleTimers") |
| 9508 | private boolean mNetworkActive; |
| 9509 | @GuardedBy("mActiveIdleTimers") |
| 9510 | private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap(); |
| 9511 | private final Handler mHandler; |
| 9512 | |
| 9513 | private class IdleTimerParams { |
| 9514 | public final int timeout; |
| 9515 | public final int transportType; |
| 9516 | |
| 9517 | IdleTimerParams(int timeout, int transport) { |
| 9518 | this.timeout = timeout; |
| 9519 | this.transportType = transport; |
| 9520 | } |
| 9521 | } |
| 9522 | |
| 9523 | LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler, |
| 9524 | @NonNull INetd netd) { |
| 9525 | mContext = context; |
| 9526 | mNetd = netd; |
| 9527 | mHandler = handler; |
| 9528 | } |
| 9529 | |
| 9530 | public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) { |
| 9531 | sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos); |
| 9532 | synchronized (mActiveIdleTimers) { |
| 9533 | mNetworkActive = active; |
| 9534 | // If there are no idle timers, it means that system is not monitoring |
| 9535 | // activity, so the system default network for those default network |
| 9536 | // unspecified apps is always considered active. |
| 9537 | // |
| 9538 | // TODO: If the mActiveIdleTimers is empty, netd will actually not send |
| 9539 | // any network activity change event. Whenever this event is received, |
| 9540 | // the mActiveIdleTimers should be always not empty. The legacy behavior |
| 9541 | // is no-op. Remove to refer to mNetworkActive only. |
| 9542 | if (mNetworkActive || mActiveIdleTimers.isEmpty()) { |
| 9543 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY)); |
| 9544 | } |
| 9545 | } |
| 9546 | } |
| 9547 | |
| 9548 | // The network activity should only be updated from ConnectivityService handler thread |
| 9549 | // when mActiveIdleTimers lock is held. |
| 9550 | @GuardedBy("mActiveIdleTimers") |
| 9551 | private void reportNetworkActive() { |
| 9552 | final int length = mNetworkActivityListeners.beginBroadcast(); |
| 9553 | if (DDBG) log("reportNetworkActive, notify " + length + " listeners"); |
| 9554 | try { |
| 9555 | for (int i = 0; i < length; i++) { |
| 9556 | try { |
| 9557 | mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive(); |
| 9558 | } catch (RemoteException | RuntimeException e) { |
| 9559 | loge("Fail to send network activie to listener " + e); |
| 9560 | } |
| 9561 | } |
| 9562 | } finally { |
| 9563 | mNetworkActivityListeners.finishBroadcast(); |
| 9564 | } |
| 9565 | } |
| 9566 | |
| 9567 | @GuardedBy("mActiveIdleTimers") |
| 9568 | public void handleReportNetworkActivity() { |
| 9569 | synchronized (mActiveIdleTimers) { |
| 9570 | reportNetworkActive(); |
| 9571 | } |
| 9572 | } |
| 9573 | |
| 9574 | // This is deprecated and only to support legacy use cases. |
| 9575 | private int transportTypeToLegacyType(int type) { |
| 9576 | switch (type) { |
| 9577 | case NetworkCapabilities.TRANSPORT_CELLULAR: |
| 9578 | return TYPE_MOBILE; |
| 9579 | case NetworkCapabilities.TRANSPORT_WIFI: |
| 9580 | return TYPE_WIFI; |
| 9581 | case NetworkCapabilities.TRANSPORT_BLUETOOTH: |
| 9582 | return TYPE_BLUETOOTH; |
| 9583 | case NetworkCapabilities.TRANSPORT_ETHERNET: |
| 9584 | return TYPE_ETHERNET; |
| 9585 | default: |
| 9586 | loge("Unexpected transport in transportTypeToLegacyType: " + type); |
| 9587 | } |
| 9588 | return ConnectivityManager.TYPE_NONE; |
| 9589 | } |
| 9590 | |
| 9591 | public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) { |
| 9592 | final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE); |
| 9593 | intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType); |
| 9594 | intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active); |
| 9595 | intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos); |
| 9596 | final long ident = Binder.clearCallingIdentity(); |
| 9597 | try { |
| 9598 | mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL, |
| 9599 | RECEIVE_DATA_ACTIVITY_CHANGE, |
| 9600 | null /* resultReceiver */, |
| 9601 | null /* scheduler */, |
| 9602 | 0 /* initialCode */, |
| 9603 | null /* initialData */, |
| 9604 | null /* initialExtra */); |
| 9605 | } finally { |
| 9606 | Binder.restoreCallingIdentity(ident); |
| 9607 | } |
| 9608 | } |
| 9609 | |
| 9610 | /** |
| 9611 | * Setup data activity tracking for the given network. |
| 9612 | * |
| 9613 | * Every {@code setupDataActivityTracking} should be paired with a |
| 9614 | * {@link #removeDataActivityTracking} for cleanup. |
| 9615 | */ |
| 9616 | private void setupDataActivityTracking(NetworkAgentInfo networkAgent) { |
| 9617 | final String iface = networkAgent.linkProperties.getInterfaceName(); |
| 9618 | |
| 9619 | final int timeout; |
| 9620 | final int type; |
| 9621 | |
| 9622 | if (networkAgent.networkCapabilities.hasTransport( |
| 9623 | NetworkCapabilities.TRANSPORT_CELLULAR)) { |
| 9624 | timeout = Settings.Global.getInt(mContext.getContentResolver(), |
| 9625 | ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE, |
| 9626 | 10); |
| 9627 | type = NetworkCapabilities.TRANSPORT_CELLULAR; |
| 9628 | } else if (networkAgent.networkCapabilities.hasTransport( |
| 9629 | NetworkCapabilities.TRANSPORT_WIFI)) { |
| 9630 | timeout = Settings.Global.getInt(mContext.getContentResolver(), |
| 9631 | ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI, |
| 9632 | 15); |
| 9633 | type = NetworkCapabilities.TRANSPORT_WIFI; |
| 9634 | } else { |
| 9635 | return; // do not track any other networks |
| 9636 | } |
| 9637 | |
| 9638 | updateRadioPowerState(true /* isActive */, type); |
| 9639 | |
| 9640 | if (timeout > 0 && iface != null) { |
| 9641 | try { |
| 9642 | synchronized (mActiveIdleTimers) { |
| 9643 | // Networks start up. |
| 9644 | mNetworkActive = true; |
| 9645 | mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type)); |
| 9646 | mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type)); |
| 9647 | reportNetworkActive(); |
| 9648 | } |
| 9649 | } catch (Exception e) { |
| 9650 | // You shall not crash! |
| 9651 | loge("Exception in setupDataActivityTracking " + e); |
| 9652 | } |
| 9653 | } |
| 9654 | } |
| 9655 | |
| 9656 | /** |
| 9657 | * Remove data activity tracking when network disconnects. |
| 9658 | */ |
| 9659 | private void removeDataActivityTracking(NetworkAgentInfo networkAgent) { |
| 9660 | final String iface = networkAgent.linkProperties.getInterfaceName(); |
| 9661 | final NetworkCapabilities caps = networkAgent.networkCapabilities; |
| 9662 | |
| 9663 | if (iface == null) return; |
| 9664 | |
| 9665 | final int type; |
| 9666 | if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) { |
| 9667 | type = NetworkCapabilities.TRANSPORT_CELLULAR; |
| 9668 | } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { |
| 9669 | type = NetworkCapabilities.TRANSPORT_WIFI; |
| 9670 | } else { |
| 9671 | return; // do not track any other networks |
| 9672 | } |
| 9673 | |
| 9674 | try { |
| 9675 | updateRadioPowerState(false /* isActive */, type); |
| 9676 | synchronized (mActiveIdleTimers) { |
| 9677 | final IdleTimerParams params = mActiveIdleTimers.remove(iface); |
| 9678 | // The call fails silently if no idle timer setup for this interface |
| 9679 | mNetd.idletimerRemoveInterface(iface, params.timeout, |
| 9680 | Integer.toString(params.transportType)); |
| 9681 | } |
| 9682 | } catch (Exception e) { |
| 9683 | // You shall not crash! |
| 9684 | loge("Exception in removeDataActivityTracking " + e); |
| 9685 | } |
| 9686 | } |
| 9687 | |
| 9688 | /** |
| 9689 | * Update data activity tracking when network state is updated. |
| 9690 | */ |
| 9691 | public void updateDataActivityTracking(NetworkAgentInfo newNetwork, |
| 9692 | NetworkAgentInfo oldNetwork) { |
| 9693 | if (newNetwork != null) { |
| 9694 | setupDataActivityTracking(newNetwork); |
| 9695 | } |
| 9696 | if (oldNetwork != null) { |
| 9697 | removeDataActivityTracking(oldNetwork); |
| 9698 | } |
| 9699 | } |
| 9700 | |
| 9701 | private void updateRadioPowerState(boolean isActive, int transportType) { |
| 9702 | final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class); |
| 9703 | switch (transportType) { |
| 9704 | case NetworkCapabilities.TRANSPORT_CELLULAR: |
| 9705 | bs.reportMobileRadioPowerState(isActive, NO_UID); |
| 9706 | break; |
| 9707 | case NetworkCapabilities.TRANSPORT_WIFI: |
| 9708 | bs.reportWifiRadioPowerState(isActive, NO_UID); |
| 9709 | break; |
| 9710 | default: |
| 9711 | logw("Untracked transport type:" + transportType); |
| 9712 | } |
| 9713 | } |
| 9714 | |
| 9715 | public boolean isDefaultNetworkActive() { |
| 9716 | synchronized (mActiveIdleTimers) { |
| 9717 | // If there are no idle timers, it means that system is not monitoring activity, |
| 9718 | // so the default network is always considered active. |
| 9719 | // |
| 9720 | // TODO : Distinguish between the cases where mActiveIdleTimers is empty because |
| 9721 | // tracking is disabled (negative idle timer value configured), or no active default |
| 9722 | // network. In the latter case, this reports active but it should report inactive. |
| 9723 | return mNetworkActive || mActiveIdleTimers.isEmpty(); |
| 9724 | } |
| 9725 | } |
| 9726 | |
| 9727 | public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) { |
| 9728 | mNetworkActivityListeners.register(l); |
| 9729 | } |
| 9730 | |
| 9731 | public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) { |
| 9732 | mNetworkActivityListeners.unregister(l); |
| 9733 | } |
| 9734 | |
| 9735 | public void dump(IndentingPrintWriter pw) { |
| 9736 | synchronized (mActiveIdleTimers) { |
| 9737 | pw.print("mNetworkActive="); pw.println(mNetworkActive); |
| 9738 | pw.println("Idle timers:"); |
| 9739 | for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) { |
| 9740 | pw.print(" "); pw.print(ent.getKey()); pw.println(":"); |
| 9741 | final IdleTimerParams params = ent.getValue(); |
| 9742 | pw.print(" timeout="); pw.print(params.timeout); |
| 9743 | pw.print(" type="); pw.println(params.transportType); |
| 9744 | } |
| 9745 | } |
| 9746 | } |
| 9747 | } |
| 9748 | |
| 9749 | /** |
| 9750 | * Registers {@link QosSocketFilter} with {@link IQosCallback}. |
| 9751 | * |
| 9752 | * @param socketInfo the socket information |
| 9753 | * @param callback the callback to register |
| 9754 | */ |
| 9755 | @Override |
| 9756 | public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo, |
| 9757 | @NonNull final IQosCallback callback) { |
| 9758 | final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork()); |
| 9759 | if (nai == null || nai.networkCapabilities == null) { |
| 9760 | try { |
| 9761 | callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED); |
| 9762 | } catch (final RemoteException ex) { |
| 9763 | loge("registerQosCallbackInternal: RemoteException", ex); |
| 9764 | } |
| 9765 | return; |
| 9766 | } |
| 9767 | registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai); |
| 9768 | } |
| 9769 | |
| 9770 | /** |
| 9771 | * Register a {@link IQosCallback} with base {@link QosFilter}. |
| 9772 | * |
| 9773 | * @param filter the filter to register |
| 9774 | * @param callback the callback to register |
| 9775 | * @param nai the agent information related to the filter's network |
| 9776 | */ |
| 9777 | @VisibleForTesting |
| 9778 | public void registerQosCallbackInternal(@NonNull final QosFilter filter, |
| 9779 | @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) { |
| 9780 | if (filter == null) throw new IllegalArgumentException("filter must be non-null"); |
| 9781 | if (callback == null) throw new IllegalArgumentException("callback must be non-null"); |
| 9782 | |
| 9783 | if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) { |
| 9784 | enforceConnectivityRestrictedNetworksPermission(); |
| 9785 | } |
| 9786 | mQosCallbackTracker.registerCallback(callback, filter, nai); |
| 9787 | } |
| 9788 | |
| 9789 | /** |
| 9790 | * Unregisters the given callback. |
| 9791 | * |
| 9792 | * @param callback the callback to unregister |
| 9793 | */ |
| 9794 | @Override |
| 9795 | public void unregisterQosCallback(@NonNull final IQosCallback callback) { |
| 9796 | Objects.requireNonNull(callback, "callback must be non-null"); |
| 9797 | mQosCallbackTracker.unregisterCallback(callback); |
| 9798 | } |
| 9799 | |
| 9800 | // Network preference per-profile and OEM network preferences can't be set at the same |
| 9801 | // time, because it is unclear what should happen if both preferences are active for |
| 9802 | // one given UID. To make it possible, the stack would have to clarify what would happen |
| 9803 | // in case both are active at the same time. The implementation may have to be adjusted |
| 9804 | // to implement the resulting rules. For example, a priority could be defined between them, |
| 9805 | // where the OEM preference would be considered less or more important than the enterprise |
| 9806 | // preference ; this would entail implementing the priorities somehow, e.g. by doing |
| 9807 | // UID arithmetic with UID ranges or passing a priority to netd so that the routing rules |
| 9808 | // are set at the right level. Other solutions are possible, e.g. merging of the |
| 9809 | // preferences for the relevant UIDs. |
| 9810 | private static void throwConcurrentPreferenceException() { |
| 9811 | throw new IllegalStateException("Can't set NetworkPreferenceForUser and " |
| 9812 | + "set OemNetworkPreference at the same time"); |
| 9813 | } |
| 9814 | |
| 9815 | /** |
| 9816 | * Request that a user profile is put by default on a network matching a given preference. |
| 9817 | * |
| 9818 | * See the documentation for the individual preferences for a description of the supported |
| 9819 | * behaviors. |
| 9820 | * |
| 9821 | * @param profile the profile concerned. |
| 9822 | * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_* |
| 9823 | * constants. |
| 9824 | * @param listener an optional listener to listen for completion of the operation. |
| 9825 | */ |
| 9826 | @Override |
| 9827 | public void setProfileNetworkPreference(@NonNull final UserHandle profile, |
| 9828 | @ConnectivityManager.ProfileNetworkPreference final int preference, |
| 9829 | @Nullable final IOnCompleteListener listener) { |
| 9830 | Objects.requireNonNull(profile); |
| 9831 | PermissionUtils.enforceNetworkStackPermission(mContext); |
| 9832 | if (DBG) { |
| 9833 | log("setProfileNetworkPreference " + profile + " to " + preference); |
| 9834 | } |
| 9835 | if (profile.getIdentifier() < 0) { |
| 9836 | throw new IllegalArgumentException("Must explicitly specify a user handle (" |
| 9837 | + "UserHandle.CURRENT not supported)"); |
| 9838 | } |
| 9839 | final UserManager um = mContext.getSystemService(UserManager.class); |
| 9840 | if (!um.isManagedProfile(profile.getIdentifier())) { |
| 9841 | throw new IllegalArgumentException("Profile must be a managed profile"); |
| 9842 | } |
| 9843 | // Strictly speaking, mOemNetworkPreferences should only be touched on the |
| 9844 | // handler thread. However it is an immutable object, so reading the reference is |
| 9845 | // safe - it's just possible the value is slightly outdated. For the final check, |
| 9846 | // see #handleSetProfileNetworkPreference. But if this can be caught here it is a |
| 9847 | // lot easier to understand, so opportunistically check it. |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 9848 | // TODO: Have a priority for each preference. |
| 9849 | if (!mOemNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) { |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 9850 | throwConcurrentPreferenceException(); |
| 9851 | } |
| 9852 | final NetworkCapabilities nc; |
| 9853 | switch (preference) { |
| 9854 | case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT: |
| 9855 | nc = null; |
| 9856 | break; |
| 9857 | case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE: |
| 9858 | final UidRange uids = UidRange.createForUser(profile); |
| 9859 | nc = createDefaultNetworkCapabilitiesForUidRange(uids); |
| 9860 | nc.addCapability(NET_CAPABILITY_ENTERPRISE); |
| 9861 | nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED); |
| 9862 | break; |
| 9863 | default: |
| 9864 | throw new IllegalArgumentException( |
| 9865 | "Invalid preference in setProfileNetworkPreference"); |
| 9866 | } |
| 9867 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE, |
| 9868 | new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener))); |
| 9869 | } |
| 9870 | |
| 9871 | private void validateNetworkCapabilitiesOfProfileNetworkPreference( |
| 9872 | @Nullable final NetworkCapabilities nc) { |
| 9873 | if (null == nc) return; // Null caps are always allowed. It means to remove the setting. |
| 9874 | ensureRequestableCapabilities(nc); |
| 9875 | } |
| 9876 | |
| 9877 | private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences( |
| 9878 | @NonNull final ProfileNetworkPreferences prefs) { |
| 9879 | final ArraySet<NetworkRequestInfo> result = new ArraySet<>(); |
| 9880 | for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) { |
| 9881 | // The NRI for a user should be comprised of two layers: |
| 9882 | // - The request for the capabilities |
| 9883 | // - The request for the default network, for fallback. Create an image of it to |
| 9884 | // have the correct UIDs in it (also a request can only be part of one NRI, because |
| 9885 | // of lookups in 1:1 associations like mNetworkRequests). |
| 9886 | // Note that denying a fallback can be implemented simply by not adding the second |
| 9887 | // request. |
| 9888 | final ArrayList<NetworkRequest> nrs = new ArrayList<>(); |
| 9889 | nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities)); |
| 9890 | nrs.add(createDefaultInternetRequestForTransport( |
| 9891 | TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT)); |
| 9892 | setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids())); |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 9893 | final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs, |
| 9894 | DEFAULT_NETWORK_PRIORITY_PROFILE); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 9895 | result.add(nri); |
| 9896 | } |
| 9897 | return result; |
| 9898 | } |
| 9899 | |
| 9900 | private void handleSetProfileNetworkPreference( |
| 9901 | @NonNull final ProfileNetworkPreferences.Preference preference, |
| 9902 | @Nullable final IOnCompleteListener listener) { |
| 9903 | // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in |
| 9904 | // particular because it's not clear what preference should win in case both apply |
| 9905 | // to the same app. |
| 9906 | // The binder call has already checked this, but as mOemNetworkPreferences is only |
| 9907 | // touched on the handler thread, it's theoretically not impossible that it has changed |
| 9908 | // since. |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 9909 | // TODO: Have a priority for each preference. |
| 9910 | if (!mOemNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) { |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 9911 | // This may happen on a device with an OEM preference set when a user is removed. |
| 9912 | // In this case, it's safe to ignore. In particular this happens in the tests. |
| 9913 | loge("handleSetProfileNetworkPreference, but OEM network preferences not empty"); |
| 9914 | return; |
| 9915 | } |
| 9916 | |
| 9917 | validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities); |
| 9918 | |
| 9919 | mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference); |
| 9920 | mSystemNetworkRequestCounter.transact( |
| 9921 | mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(), |
| 9922 | () -> { |
| 9923 | final ArraySet<NetworkRequestInfo> nris = |
| 9924 | createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences); |
| 9925 | replaceDefaultNetworkRequestsForPreference(nris); |
| 9926 | }); |
| 9927 | // Finally, rematch. |
| 9928 | rematchAllNetworksAndRequests(); |
| 9929 | |
| 9930 | if (null != listener) { |
| 9931 | try { |
| 9932 | listener.onComplete(); |
| 9933 | } catch (RemoteException e) { |
| 9934 | loge("Listener for setProfileNetworkPreference has died"); |
| 9935 | } |
| 9936 | } |
| 9937 | } |
| 9938 | |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 9939 | @VisibleForTesting |
| 9940 | @NonNull |
| 9941 | ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids( |
| 9942 | @NonNull final Set<Integer> uids) { |
| 9943 | final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(); |
| 9944 | if (uids.size() == 0) { |
| 9945 | // Should not create NetworkRequestInfo if no preferences. Without uid range in |
| 9946 | // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI. |
| 9947 | if (DBG) log("Don't create NetworkRequestInfo because no preferences"); |
| 9948 | return nris; |
| 9949 | } |
| 9950 | |
| 9951 | final List<NetworkRequest> requests = new ArrayList<>(); |
| 9952 | // The NRI should be comprised of two layers: |
| 9953 | // - The request for the mobile network preferred. |
| 9954 | // - The request for the default network, for fallback. |
| 9955 | requests.add(createDefaultInternetRequestForTransport( |
Paul Hu | 07950df | 2021-07-02 01:44:52 +0000 | [diff] [blame^] | 9956 | TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST)); |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 9957 | requests.add(createDefaultInternetRequestForTransport( |
| 9958 | TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT)); |
| 9959 | final Set<UidRange> ranges = new ArraySet<>(); |
| 9960 | for (final int uid : uids) { |
| 9961 | ranges.add(new UidRange(uid, uid)); |
| 9962 | } |
| 9963 | setNetworkRequestUids(requests, ranges); |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 9964 | nris.add(new NetworkRequestInfo(Process.myUid(), requests, |
| 9965 | DEFAULT_NETWORK_PRIORITY_MOBILE_DATA_PREFERRED)); |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 9966 | return nris; |
| 9967 | } |
| 9968 | |
| 9969 | private void handleMobileDataPreferredUidsChanged() { |
| 9970 | // Ignore update preference because it's not clear what preference should win in case both |
| 9971 | // apply to the same app. |
| 9972 | // TODO: Have a priority for each preference. |
| 9973 | if (!mOemNetworkPreferences.isEmpty() || !mProfileNetworkPreferences.isEmpty()) { |
| 9974 | loge("Ignore mobile data preference change because other preferences are not empty"); |
| 9975 | return; |
| 9976 | } |
| 9977 | |
| 9978 | mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext); |
| 9979 | mSystemNetworkRequestCounter.transact( |
| 9980 | mDeps.getCallingUid(), 1 /* numOfNewRequests */, |
| 9981 | () -> { |
| 9982 | final ArraySet<NetworkRequestInfo> nris = |
| 9983 | createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids); |
| 9984 | replaceDefaultNetworkRequestsForPreference(nris); |
| 9985 | }); |
| 9986 | // Finally, rematch. |
| 9987 | rematchAllNetworksAndRequests(); |
| 9988 | } |
| 9989 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 9990 | private void enforceAutomotiveDevice() { |
| 9991 | final boolean isAutomotiveDevice = |
| 9992 | mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE); |
| 9993 | if (!isAutomotiveDevice) { |
| 9994 | throw new UnsupportedOperationException( |
| 9995 | "setOemNetworkPreference() is only available on automotive devices."); |
| 9996 | } |
| 9997 | } |
| 9998 | |
| 9999 | /** |
| 10000 | * Used by automotive devices to set the network preferences used to direct traffic at an |
| 10001 | * application level as per the given OemNetworkPreferences. An example use-case would be an |
| 10002 | * automotive OEM wanting to provide connectivity for applications critical to the usage of a |
| 10003 | * vehicle via a particular network. |
| 10004 | * |
| 10005 | * Calling this will overwrite the existing preference. |
| 10006 | * |
| 10007 | * @param preference {@link OemNetworkPreferences} The application network preference to be set. |
| 10008 | * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used |
| 10009 | * to communicate completion of setOemNetworkPreference(); |
| 10010 | */ |
| 10011 | @Override |
| 10012 | public void setOemNetworkPreference( |
| 10013 | @NonNull final OemNetworkPreferences preference, |
| 10014 | @Nullable final IOnCompleteListener listener) { |
| 10015 | |
James Mattis | b7ca034 | 2021-06-16 01:30:05 +0000 | [diff] [blame] | 10016 | Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null"); |
| 10017 | // Only bypass the permission/device checks if this is a valid test request. |
| 10018 | if (isValidTestOemNetworkPreference(preference)) { |
| 10019 | enforceManageTestNetworksPermission(); |
| 10020 | } else { |
| 10021 | enforceAutomotiveDevice(); |
| 10022 | enforceOemNetworkPreferencesPermission(); |
| 10023 | validateOemNetworkPreferences(preference); |
| 10024 | } |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10025 | |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 10026 | // TODO: Have a priority for each preference. |
| 10027 | if (!mProfileNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) { |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10028 | // Strictly speaking, mProfileNetworkPreferences should only be touched on the |
| 10029 | // handler thread. However it is an immutable object, so reading the reference is |
| 10030 | // safe - it's just possible the value is slightly outdated. For the final check, |
| 10031 | // see #handleSetOemPreference. But if this can be caught here it is a |
| 10032 | // lot easier to understand, so opportunistically check it. |
| 10033 | throwConcurrentPreferenceException(); |
| 10034 | } |
| 10035 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10036 | mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE, |
| 10037 | new Pair<>(preference, listener))); |
| 10038 | } |
| 10039 | |
James Mattis | b7ca034 | 2021-06-16 01:30:05 +0000 | [diff] [blame] | 10040 | /** |
| 10041 | * Check the validity of an OEM network preference to be used for testing purposes. |
| 10042 | * @param preference the preference to validate |
| 10043 | * @return true if this is a valid OEM network preference test request. |
| 10044 | */ |
| 10045 | private boolean isValidTestOemNetworkPreference( |
| 10046 | @NonNull final OemNetworkPreferences preference) { |
| 10047 | // Allow for clearing of an existing OemNetworkPreference used for testing. |
| 10048 | // This isn't called on the handler thread so it is possible that mOemNetworkPreferences |
| 10049 | // changes after this check is complete. This is an unlikely scenario as calling of this API |
| 10050 | // is controlled by the OEM therefore the added complexity is not worth adding given those |
| 10051 | // circumstances. That said, it is an edge case to be aware of hence this comment. |
| 10052 | final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0 |
| 10053 | && isTestOemNetworkPreference(mOemNetworkPreferences); |
| 10054 | return isTestOemNetworkPreference(preference) || isValidTestClearPref; |
| 10055 | } |
| 10056 | |
| 10057 | private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) { |
| 10058 | final Map<String, Integer> prefMap = preference.getNetworkPreferences(); |
| 10059 | return prefMap.size() == 1 |
| 10060 | && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST) |
| 10061 | || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY)); |
| 10062 | } |
| 10063 | |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10064 | private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) { |
| 10065 | for (@OemNetworkPreferences.OemNetworkPreference final int pref |
| 10066 | : preference.getNetworkPreferences().values()) { |
James Mattis | b7ca034 | 2021-06-16 01:30:05 +0000 | [diff] [blame] | 10067 | if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) { |
| 10068 | throw new IllegalArgumentException( |
| 10069 | OemNetworkPreferences.oemNetworkPreferenceToString(pref) |
| 10070 | + " is an invalid value."); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10071 | } |
| 10072 | } |
| 10073 | } |
| 10074 | |
| 10075 | private void handleSetOemNetworkPreference( |
| 10076 | @NonNull final OemNetworkPreferences preference, |
| 10077 | @Nullable final IOnCompleteListener listener) { |
| 10078 | Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null"); |
| 10079 | if (DBG) { |
| 10080 | log("set OEM network preferences :" + preference.toString()); |
| 10081 | } |
| 10082 | // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in |
| 10083 | // particular because it's not clear what preference should win in case both apply |
| 10084 | // to the same app. |
| 10085 | // The binder call has already checked this, but as mOemNetworkPreferences is only |
| 10086 | // touched on the handler thread, it's theoretically not impossible that it has changed |
| 10087 | // since. |
paulhu | 71ad4f1 | 2021-05-25 14:56:27 +0800 | [diff] [blame] | 10088 | // TODO: Have a priority for each preference. |
| 10089 | if (!mProfileNetworkPreferences.isEmpty() || !mMobileDataPreferredUids.isEmpty()) { |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10090 | logwtf("handleSetOemPreference, but per-profile network preferences not empty"); |
| 10091 | return; |
| 10092 | } |
| 10093 | |
| 10094 | mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference); |
| 10095 | final int uniquePreferenceCount = new ArraySet<>( |
| 10096 | preference.getNetworkPreferences().values()).size(); |
| 10097 | mSystemNetworkRequestCounter.transact( |
| 10098 | mDeps.getCallingUid(), uniquePreferenceCount, |
| 10099 | () -> { |
| 10100 | final ArraySet<NetworkRequestInfo> nris = |
| 10101 | new OemNetworkRequestFactory() |
| 10102 | .createNrisFromOemNetworkPreferences(preference); |
| 10103 | replaceDefaultNetworkRequestsForPreference(nris); |
| 10104 | }); |
| 10105 | mOemNetworkPreferences = preference; |
| 10106 | |
| 10107 | if (null != listener) { |
| 10108 | try { |
| 10109 | listener.onComplete(); |
| 10110 | } catch (RemoteException e) { |
| 10111 | loge("Can't send onComplete in handleSetOemNetworkPreference", e); |
| 10112 | } |
| 10113 | } |
| 10114 | } |
| 10115 | |
| 10116 | private void replaceDefaultNetworkRequestsForPreference( |
| 10117 | @NonNull final Set<NetworkRequestInfo> nris) { |
| 10118 | // Pass in a defensive copy as this collection will be updated on remove. |
| 10119 | handleRemoveNetworkRequests(new ArraySet<>(mDefaultNetworkRequests)); |
| 10120 | addPerAppDefaultNetworkRequests(nris); |
| 10121 | } |
| 10122 | |
| 10123 | private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) { |
| 10124 | ensureRunningOnConnectivityServiceThread(); |
| 10125 | mDefaultNetworkRequests.addAll(nris); |
| 10126 | final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate = |
| 10127 | getPerAppCallbackRequestsToUpdate(); |
| 10128 | final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris); |
| 10129 | mSystemNetworkRequestCounter.transact( |
| 10130 | mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(), |
| 10131 | () -> { |
| 10132 | nrisToRegister.addAll( |
| 10133 | createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate)); |
| 10134 | handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate); |
| 10135 | handleRegisterNetworkRequests(nrisToRegister); |
| 10136 | }); |
| 10137 | } |
| 10138 | |
| 10139 | /** |
| 10140 | * All current requests that are tracking the default network need to be assessed as to whether |
| 10141 | * or not the current set of per-application default requests will be changing their default |
| 10142 | * network. If so, those requests will need to be updated so that they will send callbacks for |
| 10143 | * default network changes at the appropriate time. Additionally, those requests tracking the |
| 10144 | * default that were previously updated by this flow will need to be reassessed. |
| 10145 | * @return the nris which will need to be updated. |
| 10146 | */ |
| 10147 | private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() { |
| 10148 | final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>(); |
| 10149 | // Get the distinct nris to check since for multilayer requests, it is possible to have the |
| 10150 | // same nri in the map's values for each of its NetworkRequest objects. |
| 10151 | final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values()); |
| 10152 | for (final NetworkRequestInfo nri : nris) { |
| 10153 | // Include this nri if it is currently being tracked. |
| 10154 | if (isPerAppTrackedNri(nri)) { |
| 10155 | defaultCallbackRequests.add(nri); |
| 10156 | continue; |
| 10157 | } |
| 10158 | // We only track callbacks for requests tracking the default. |
| 10159 | if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) { |
| 10160 | continue; |
| 10161 | } |
| 10162 | // Include this nri if it will be tracked by the new per-app default requests. |
| 10163 | final boolean isNriGoingToBeTracked = |
| 10164 | getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest; |
| 10165 | if (isNriGoingToBeTracked) { |
| 10166 | defaultCallbackRequests.add(nri); |
| 10167 | } |
| 10168 | } |
| 10169 | return defaultCallbackRequests; |
| 10170 | } |
| 10171 | |
| 10172 | /** |
| 10173 | * Create nris for those network requests that are currently tracking the default network that |
| 10174 | * are being controlled by a per-application default. |
| 10175 | * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the |
| 10176 | * foundation when creating the nri. Important items include the calling uid's original |
| 10177 | * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These |
| 10178 | * requests are assumed to have already been validated as needing to be updated. |
| 10179 | * @return the Set of nris to use when registering network requests. |
| 10180 | */ |
| 10181 | private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister( |
| 10182 | @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) { |
| 10183 | final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>(); |
| 10184 | for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) { |
| 10185 | final NetworkRequestInfo trackingNri = |
| 10186 | getDefaultRequestTrackingUid(callbackRequest.mAsUid); |
| 10187 | |
| 10188 | // If this nri is not being tracked, the change it back to an untracked nri. |
| 10189 | if (trackingNri == mDefaultRequest) { |
| 10190 | callbackRequestsToRegister.add(new NetworkRequestInfo( |
| 10191 | callbackRequest, |
| 10192 | Collections.singletonList(callbackRequest.getNetworkRequestForCallback()))); |
| 10193 | continue; |
| 10194 | } |
| 10195 | |
| 10196 | final NetworkRequest request = callbackRequest.mRequests.get(0); |
| 10197 | callbackRequestsToRegister.add(new NetworkRequestInfo( |
| 10198 | callbackRequest, |
| 10199 | copyNetworkRequestsForUid( |
| 10200 | trackingNri.mRequests, callbackRequest.mAsUid, |
| 10201 | callbackRequest.mUid, request.getRequestorPackageName()))); |
| 10202 | } |
| 10203 | return callbackRequestsToRegister; |
| 10204 | } |
| 10205 | |
| 10206 | private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests, |
| 10207 | @NonNull final Set<UidRange> uids) { |
| 10208 | for (final NetworkRequest req : requests) { |
| 10209 | req.networkCapabilities.setUids(UidRange.toIntRanges(uids)); |
| 10210 | } |
| 10211 | } |
| 10212 | |
| 10213 | /** |
| 10214 | * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}. |
| 10215 | */ |
| 10216 | @VisibleForTesting |
| 10217 | final class OemNetworkRequestFactory { |
| 10218 | ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences( |
| 10219 | @NonNull final OemNetworkPreferences preference) { |
| 10220 | final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(); |
| 10221 | final SparseArray<Set<Integer>> uids = |
| 10222 | createUidsFromOemNetworkPreferences(preference); |
| 10223 | for (int i = 0; i < uids.size(); i++) { |
| 10224 | final int key = uids.keyAt(i); |
| 10225 | final Set<Integer> value = uids.valueAt(i); |
| 10226 | final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value); |
| 10227 | // No need to add an nri without any requests. |
| 10228 | if (0 == nri.mRequests.size()) { |
| 10229 | continue; |
| 10230 | } |
| 10231 | nris.add(nri); |
| 10232 | } |
| 10233 | |
| 10234 | return nris; |
| 10235 | } |
| 10236 | |
| 10237 | private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences( |
| 10238 | @NonNull final OemNetworkPreferences preference) { |
Lorenzo Colitti | 659a0e1 | 2021-06-14 06:32:56 +0000 | [diff] [blame] | 10239 | final SparseArray<Set<Integer>> prefToUids = new SparseArray<>(); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10240 | final PackageManager pm = mContext.getPackageManager(); |
| 10241 | final List<UserHandle> users = |
| 10242 | mContext.getSystemService(UserManager.class).getUserHandles(true); |
| 10243 | if (null == users || users.size() == 0) { |
| 10244 | if (VDBG || DDBG) { |
| 10245 | log("No users currently available for setting the OEM network preference."); |
| 10246 | } |
Lorenzo Colitti | 659a0e1 | 2021-06-14 06:32:56 +0000 | [diff] [blame] | 10247 | return prefToUids; |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10248 | } |
| 10249 | for (final Map.Entry<String, Integer> entry : |
| 10250 | preference.getNetworkPreferences().entrySet()) { |
| 10251 | @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue(); |
Lorenzo Colitti | 659a0e1 | 2021-06-14 06:32:56 +0000 | [diff] [blame] | 10252 | // Add the rules for all users as this policy is device wide. |
| 10253 | for (final UserHandle user : users) { |
| 10254 | try { |
| 10255 | final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid; |
| 10256 | if (!prefToUids.contains(pref)) { |
| 10257 | prefToUids.put(pref, new ArraySet<>()); |
| 10258 | } |
| 10259 | prefToUids.get(pref).add(uid); |
| 10260 | } catch (PackageManager.NameNotFoundException e) { |
| 10261 | // Although this may seem like an error scenario, it is ok that uninstalled |
| 10262 | // packages are sent on a network preference as the system will watch for |
| 10263 | // package installations associated with this network preference and update |
| 10264 | // accordingly. This is done to minimize race conditions on app install. |
| 10265 | continue; |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10266 | } |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10267 | } |
| 10268 | } |
Lorenzo Colitti | 659a0e1 | 2021-06-14 06:32:56 +0000 | [diff] [blame] | 10269 | return prefToUids; |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10270 | } |
| 10271 | |
| 10272 | private NetworkRequestInfo createNriFromOemNetworkPreferences( |
| 10273 | @OemNetworkPreferences.OemNetworkPreference final int preference, |
| 10274 | @NonNull final Set<Integer> uids) { |
| 10275 | final List<NetworkRequest> requests = new ArrayList<>(); |
| 10276 | // Requests will ultimately be evaluated by order of insertion therefore it matters. |
| 10277 | switch (preference) { |
| 10278 | case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID: |
| 10279 | requests.add(createUnmeteredNetworkRequest()); |
| 10280 | requests.add(createOemPaidNetworkRequest()); |
| 10281 | requests.add(createDefaultInternetRequestForTransport( |
| 10282 | TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT)); |
| 10283 | break; |
| 10284 | case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK: |
| 10285 | requests.add(createUnmeteredNetworkRequest()); |
| 10286 | requests.add(createOemPaidNetworkRequest()); |
| 10287 | break; |
| 10288 | case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY: |
| 10289 | requests.add(createOemPaidNetworkRequest()); |
| 10290 | break; |
| 10291 | case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY: |
| 10292 | requests.add(createOemPrivateNetworkRequest()); |
| 10293 | break; |
James Mattis | b7ca034 | 2021-06-16 01:30:05 +0000 | [diff] [blame] | 10294 | case OEM_NETWORK_PREFERENCE_TEST: |
| 10295 | requests.add(createUnmeteredNetworkRequest()); |
| 10296 | requests.add(createTestNetworkRequest()); |
| 10297 | requests.add(createDefaultRequest()); |
| 10298 | break; |
| 10299 | case OEM_NETWORK_PREFERENCE_TEST_ONLY: |
| 10300 | requests.add(createTestNetworkRequest()); |
| 10301 | break; |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10302 | default: |
| 10303 | // This should never happen. |
| 10304 | throw new IllegalArgumentException("createNriFromOemNetworkPreferences()" |
| 10305 | + " called with invalid preference of " + preference); |
| 10306 | } |
| 10307 | |
James Mattis | b7ca034 | 2021-06-16 01:30:05 +0000 | [diff] [blame] | 10308 | final ArraySet<UidRange> ranges = new ArraySet<>(); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10309 | for (final int uid : uids) { |
| 10310 | ranges.add(new UidRange(uid, uid)); |
| 10311 | } |
| 10312 | setNetworkRequestUids(requests, ranges); |
paulhu | c219877 | 2021-05-26 15:19:20 +0800 | [diff] [blame] | 10313 | return new NetworkRequestInfo( |
| 10314 | Process.myUid(), requests, DEFAULT_NETWORK_PRIORITY_OEM); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10315 | } |
| 10316 | |
| 10317 | private NetworkRequest createUnmeteredNetworkRequest() { |
| 10318 | final NetworkCapabilities netcap = createDefaultPerAppNetCap() |
| 10319 | .addCapability(NET_CAPABILITY_NOT_METERED) |
| 10320 | .addCapability(NET_CAPABILITY_VALIDATED); |
| 10321 | return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap); |
| 10322 | } |
| 10323 | |
| 10324 | private NetworkRequest createOemPaidNetworkRequest() { |
| 10325 | // NET_CAPABILITY_OEM_PAID is a restricted capability. |
| 10326 | final NetworkCapabilities netcap = createDefaultPerAppNetCap() |
| 10327 | .addCapability(NET_CAPABILITY_OEM_PAID) |
| 10328 | .removeCapability(NET_CAPABILITY_NOT_RESTRICTED); |
| 10329 | return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap); |
| 10330 | } |
| 10331 | |
| 10332 | private NetworkRequest createOemPrivateNetworkRequest() { |
| 10333 | // NET_CAPABILITY_OEM_PRIVATE is a restricted capability. |
| 10334 | final NetworkCapabilities netcap = createDefaultPerAppNetCap() |
| 10335 | .addCapability(NET_CAPABILITY_OEM_PRIVATE) |
| 10336 | .removeCapability(NET_CAPABILITY_NOT_RESTRICTED); |
| 10337 | return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap); |
| 10338 | } |
| 10339 | |
| 10340 | private NetworkCapabilities createDefaultPerAppNetCap() { |
James Mattis | b7ca034 | 2021-06-16 01:30:05 +0000 | [diff] [blame] | 10341 | final NetworkCapabilities netcap = new NetworkCapabilities(); |
| 10342 | netcap.addCapability(NET_CAPABILITY_INTERNET); |
| 10343 | netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName()); |
| 10344 | return netcap; |
| 10345 | } |
| 10346 | |
| 10347 | private NetworkRequest createTestNetworkRequest() { |
| 10348 | final NetworkCapabilities netcap = new NetworkCapabilities(); |
| 10349 | netcap.clearAll(); |
| 10350 | netcap.addTransportType(TRANSPORT_TEST); |
| 10351 | return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap); |
Remi NGUYEN VAN | 028cb1b | 2021-05-12 14:15:24 +0000 | [diff] [blame] | 10352 | } |
| 10353 | } |
| 10354 | } |