ConnectivityService.java revision 7ec93a1ee2d381fdcd3be271712e4179ddbf9829
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 17package com.android.server; 18 19import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE; 20import static android.net.ConnectivityManager.CONNECTIVITY_ACTION; 21import static android.net.ConnectivityManager.NETID_UNSET; 22import static android.net.ConnectivityManager.TYPE_NONE; 23import static android.net.ConnectivityManager.TYPE_VPN; 24import static android.net.ConnectivityManager.getNetworkTypeName; 25import static android.net.ConnectivityManager.isNetworkTypeValid; 26import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL; 27import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET; 28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED; 29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED; 30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED; 31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL; 32import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED; 33import static android.net.NetworkPolicyManager.RULE_REJECT_ALL; 34import static android.net.NetworkPolicyManager.RULE_REJECT_METERED; 35import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED; 36import static android.net.NetworkPolicyManager.RULE_UNKNOWN; 37 38import android.annotation.Nullable; 39import android.app.BroadcastOptions; 40import android.app.Notification; 41import android.app.NotificationManager; 42import android.app.PendingIntent; 43import android.content.BroadcastReceiver; 44import android.content.ContentResolver; 45import android.content.Context; 46import android.content.Intent; 47import android.content.IntentFilter; 48import android.content.pm.PackageManager; 49import android.content.res.Configuration; 50import android.content.res.Resources; 51import android.database.ContentObserver; 52import android.net.ConnectivityManager; 53import android.net.ConnectivityManager.PacketKeepalive; 54import android.net.IConnectivityManager; 55import android.net.INetworkManagementEventObserver; 56import android.net.INetworkPolicyListener; 57import android.net.INetworkPolicyManager; 58import android.net.INetworkStatsService; 59import android.net.LinkProperties; 60import android.net.LinkProperties.CompareResult; 61import android.net.Network; 62import android.net.NetworkAgent; 63import android.net.NetworkCapabilities; 64import android.net.NetworkConfig; 65import android.net.NetworkInfo; 66import android.net.NetworkInfo.DetailedState; 67import android.net.NetworkMisc; 68import android.net.NetworkQuotaInfo; 69import android.net.NetworkRequest; 70import android.net.NetworkState; 71import android.net.NetworkUtils; 72import android.net.Proxy; 73import android.net.ProxyInfo; 74import android.net.RouteInfo; 75import android.net.UidRange; 76import android.net.Uri; 77import android.net.metrics.DefaultNetworkEvent; 78import android.net.metrics.NetworkEvent; 79import android.os.Binder; 80import android.os.Build; 81import android.os.Bundle; 82import android.os.FileUtils; 83import android.os.Handler; 84import android.os.HandlerThread; 85import android.os.IBinder; 86import android.os.INetworkManagementService; 87import android.os.Looper; 88import android.os.Message; 89import android.os.Messenger; 90import android.os.ParcelFileDescriptor; 91import android.os.PowerManager; 92import android.os.Process; 93import android.os.RemoteException; 94import android.os.ResultReceiver; 95import android.os.SystemProperties; 96import android.os.UserHandle; 97import android.os.UserManager; 98import android.provider.Settings; 99import android.security.Credentials; 100import android.security.KeyStore; 101import android.telephony.TelephonyManager; 102import android.text.TextUtils; 103import android.util.ArraySet; 104import android.util.LocalLog; 105import android.util.LocalLog.ReadOnlyLocalLog; 106import android.util.Log; 107import android.util.Pair; 108import android.util.Slog; 109import android.util.SparseArray; 110import android.util.SparseBooleanArray; 111import android.util.SparseIntArray; 112import android.util.Xml; 113 114import com.android.internal.R; 115import com.android.internal.annotations.GuardedBy; 116import com.android.internal.annotations.VisibleForTesting; 117import com.android.internal.app.IBatteryStats; 118import com.android.internal.net.LegacyVpnInfo; 119import com.android.internal.net.NetworkStatsFactory; 120import com.android.internal.net.VpnConfig; 121import com.android.internal.net.VpnInfo; 122import com.android.internal.net.VpnProfile; 123import com.android.internal.util.AsyncChannel; 124import com.android.internal.util.IndentingPrintWriter; 125import com.android.internal.util.MessageUtils; 126import com.android.internal.util.XmlUtils; 127import com.android.server.am.BatteryStatsService; 128import com.android.server.connectivity.DataConnectionStats; 129import com.android.server.connectivity.KeepaliveTracker; 130import com.android.server.connectivity.Nat464Xlat; 131import com.android.server.connectivity.NetworkAgentInfo; 132import com.android.server.connectivity.NetworkDiagnostics; 133import com.android.server.connectivity.NetworkMonitor; 134import com.android.server.connectivity.PacManager; 135import com.android.server.connectivity.PermissionMonitor; 136import com.android.server.connectivity.Tethering; 137import com.android.server.connectivity.Vpn; 138import com.android.server.net.BaseNetworkObserver; 139import com.android.server.net.LockdownVpnTracker; 140 141import com.google.android.collect.Lists; 142 143import org.xmlpull.v1.XmlPullParser; 144import org.xmlpull.v1.XmlPullParserException; 145 146import java.io.File; 147import java.io.FileDescriptor; 148import java.io.FileNotFoundException; 149import java.io.FileReader; 150import java.io.IOException; 151import java.io.PrintWriter; 152import java.net.Inet4Address; 153import java.net.InetAddress; 154import java.net.UnknownHostException; 155import java.util.ArrayDeque; 156import java.util.ArrayList; 157import java.util.Arrays; 158import java.util.Collection; 159import java.util.HashMap; 160import java.util.HashSet; 161import java.util.List; 162import java.util.Map; 163import java.util.Objects; 164import java.util.SortedSet; 165import java.util.TreeSet; 166 167/** 168 * @hide 169 */ 170public class ConnectivityService extends IConnectivityManager.Stub 171 implements PendingIntent.OnFinished { 172 private static final String TAG = "ConnectivityService"; 173 174 private static final boolean DBG = true; 175 private static final boolean VDBG = false; 176 177 private static final boolean LOGD_RULES = false; 178 private static final boolean LOGD_BLOCKED_NETWORKINFO = true; 179 180 // TODO: create better separation between radio types and network types 181 182 // how long to wait before switching back to a radio's default network 183 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000; 184 // system property that can override the above value 185 private static final String NETWORK_RESTORE_DELAY_PROP_NAME = 186 "android.telephony.apn-restore"; 187 188 // How long to wait before putting up a "This network doesn't have an Internet connection, 189 // connect anyway?" dialog after the user selects a network that doesn't validate. 190 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000; 191 192 // How long to delay to removal of a pending intent based request. 193 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS 194 private final int mReleasePendingIntentDelayMs; 195 196 private Tethering mTethering; 197 198 private final PermissionMonitor mPermissionMonitor; 199 200 private KeyStore mKeyStore; 201 202 @GuardedBy("mVpns") 203 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>(); 204 205 private boolean mLockdownEnabled; 206 private LockdownVpnTracker mLockdownTracker; 207 208 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */ 209 private Object mRulesLock = new Object(); 210 /** Currently active network rules by UID. */ 211 @GuardedBy("mRulesLock") 212 private SparseIntArray mUidRules = new SparseIntArray(); 213 /** Set of ifaces that are costly. */ 214 @GuardedBy("mRulesLock") 215 private ArraySet<String> mMeteredIfaces = new ArraySet<>(); 216 /** Flag indicating if background data is restricted. */ 217 @GuardedBy("mRulesLock") 218 private boolean mRestrictBackground; 219 220 final private Context mContext; 221 private int mNetworkPreference; 222 // 0 is full bad, 100 is full good 223 private int mDefaultInetConditionPublished = 0; 224 225 private int mNumDnsEntries; 226 227 private boolean mTestMode; 228 private static ConnectivityService sServiceInstance; 229 230 private INetworkManagementService mNetd; 231 private INetworkStatsService mStatsService; 232 private INetworkPolicyManager mPolicyManager; 233 234 private String mCurrentTcpBufferSizes; 235 236 private static final int ENABLED = 1; 237 private static final int DISABLED = 0; 238 239 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames( 240 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class }); 241 242 private enum ReapUnvalidatedNetworks { 243 // Tear down networks that have no chance (e.g. even if validated) of becoming 244 // the highest scoring network satisfying a NetworkRequest. This should be passed when 245 // all networks have been rematched against all NetworkRequests. 246 REAP, 247 // Don't reap networks. This should be passed when some networks have not yet been 248 // rematched against all NetworkRequests. 249 DONT_REAP 250 }; 251 252 /** 253 * used internally to change our mobile data enabled flag 254 */ 255 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2; 256 257 /** 258 * used internally to clear a wakelock when transitioning 259 * from one net to another. Clear happens when we get a new 260 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens 261 * after a timeout if no network is found (typically 1 min). 262 */ 263 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8; 264 265 /** 266 * used internally to reload global proxy settings 267 */ 268 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9; 269 270 /** 271 * PAC manager has received new port. 272 */ 273 private static final int EVENT_PROXY_HAS_CHANGED = 16; 274 275 /** 276 * used internally when registering NetworkFactories 277 * obj = NetworkFactoryInfo 278 */ 279 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17; 280 281 /** 282 * used internally when registering NetworkAgents 283 * obj = Messenger 284 */ 285 private static final int EVENT_REGISTER_NETWORK_AGENT = 18; 286 287 /** 288 * used to add a network request 289 * includes a NetworkRequestInfo 290 */ 291 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19; 292 293 /** 294 * indicates a timeout period is over - check if we had a network yet or not 295 * and if not, call the timeout calback (but leave the request live until they 296 * cancel it. 297 * includes a NetworkRequestInfo 298 */ 299 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20; 300 301 /** 302 * used to add a network listener - no request 303 * includes a NetworkRequestInfo 304 */ 305 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21; 306 307 /** 308 * used to remove a network request, either a listener or a real request 309 * arg1 = UID of caller 310 * obj = NetworkRequest 311 */ 312 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22; 313 314 /** 315 * used internally when registering NetworkFactories 316 * obj = Messenger 317 */ 318 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23; 319 320 /** 321 * used internally to expire a wakelock when transitioning 322 * from one net to another. Expire happens when we fail to find 323 * a new network (typically after 1 minute) - 324 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found 325 * a replacement network. 326 */ 327 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24; 328 329 /** 330 * Used internally to indicate the system is ready. 331 */ 332 private static final int EVENT_SYSTEM_READY = 25; 333 334 /** 335 * used to add a network request with a pending intent 336 * obj = NetworkRequestInfo 337 */ 338 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26; 339 340 /** 341 * used to remove a pending intent and its associated network request. 342 * arg1 = UID of caller 343 * obj = PendingIntent 344 */ 345 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27; 346 347 /** 348 * used to specify whether a network should be used even if unvalidated. 349 * arg1 = whether to accept the network if it's unvalidated (1 or 0) 350 * arg2 = whether to remember this choice in the future (1 or 0) 351 * obj = network 352 */ 353 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28; 354 355 /** 356 * used to ask the user to confirm a connection to an unvalidated network. 357 * obj = network 358 */ 359 private static final int EVENT_PROMPT_UNVALIDATED = 29; 360 361 /** 362 * used internally to (re)configure mobile data always-on settings. 363 */ 364 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30; 365 366 /** 367 * used to add a network listener with a pending intent 368 * obj = NetworkRequestInfo 369 */ 370 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31; 371 372 /** Handler thread used for both of the handlers below. */ 373 @VisibleForTesting 374 protected final HandlerThread mHandlerThread; 375 /** Handler used for internal events. */ 376 final private InternalHandler mHandler; 377 /** Handler used for incoming {@link NetworkStateTracker} events. */ 378 final private NetworkStateTrackerHandler mTrackerHandler; 379 380 private boolean mSystemReady; 381 private Intent mInitialBroadcast; 382 383 private PowerManager.WakeLock mNetTransitionWakeLock; 384 private String mNetTransitionWakeLockCausedBy = ""; 385 private int mNetTransitionWakeLockSerialNumber; 386 private int mNetTransitionWakeLockTimeout; 387 private final PowerManager.WakeLock mPendingIntentWakeLock; 388 389 // used in DBG mode to track inet condition reports 390 private static final int INET_CONDITION_LOG_MAX_SIZE = 15; 391 private ArrayList mInetLog; 392 393 // track the current default http proxy - tell the world if we get a new one (real change) 394 private volatile ProxyInfo mDefaultProxy = null; 395 private Object mProxyLock = new Object(); 396 private boolean mDefaultProxyDisabled = false; 397 398 // track the global proxy. 399 private ProxyInfo mGlobalProxy = null; 400 401 private PacManager mPacManager = null; 402 403 final private SettingsObserver mSettingsObserver; 404 405 private UserManager mUserManager; 406 407 NetworkConfig[] mNetConfigs; 408 int mNetworksDefined; 409 410 // the set of network types that can only be enabled by system/sig apps 411 List mProtectedNetworks; 412 413 private DataConnectionStats mDataConnectionStats; 414 415 TelephonyManager mTelephonyManager; 416 417 private KeepaliveTracker mKeepaliveTracker; 418 419 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp 420 private final static int MIN_NET_ID = 100; // some reserved marks 421 private final static int MAX_NET_ID = 65535; 422 private int mNextNetId = MIN_NET_ID; 423 424 // sequence number of NetworkRequests 425 private int mNextNetworkRequestId = 1; 426 427 // NetworkRequest activity String log entries. 428 private static final int MAX_NETWORK_REQUEST_LOGS = 20; 429 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS); 430 431 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results 432 private static final int MAX_VALIDATION_LOGS = 10; 433 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs = 434 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS); 435 436 private void addValidationLogs(ReadOnlyLocalLog log, Network network) { 437 synchronized(mValidationLogs) { 438 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) { 439 mValidationLogs.removeLast(); 440 } 441 mValidationLogs.addFirst(new Pair(network, log)); 442 } 443 } 444 445 /** 446 * Implements support for the legacy "one network per network type" model. 447 * 448 * We used to have a static array of NetworkStateTrackers, one for each 449 * network type, but that doesn't work any more now that we can have, 450 * for example, more that one wifi network. This class stores all the 451 * NetworkAgentInfo objects that support a given type, but the legacy 452 * API will only see the first one. 453 * 454 * It serves two main purposes: 455 * 456 * 1. Provide information about "the network for a given type" (since this 457 * API only supports one). 458 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if 459 * the first network for a given type changes, or if the default network 460 * changes. 461 */ 462 private class LegacyTypeTracker { 463 464 private static final boolean DBG = true; 465 private static final boolean VDBG = false; 466 467 /** 468 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS). 469 * Each list holds references to all NetworkAgentInfos that are used to 470 * satisfy requests for that network type. 471 * 472 * This array is built out at startup such that an unsupported network 473 * doesn't get an ArrayList instance, making this a tristate: 474 * unsupported, supported but not active and active. 475 * 476 * The actual lists are populated when we scan the network types that 477 * are supported on this device. 478 */ 479 private ArrayList<NetworkAgentInfo> mTypeLists[]; 480 481 public LegacyTypeTracker() { 482 mTypeLists = (ArrayList<NetworkAgentInfo>[]) 483 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1]; 484 } 485 486 public void addSupportedType(int type) { 487 if (mTypeLists[type] != null) { 488 throw new IllegalStateException( 489 "legacy list for type " + type + "already initialized"); 490 } 491 mTypeLists[type] = new ArrayList<NetworkAgentInfo>(); 492 } 493 494 public boolean isTypeSupported(int type) { 495 return isNetworkTypeValid(type) && mTypeLists[type] != null; 496 } 497 498 public NetworkAgentInfo getNetworkForType(int type) { 499 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) { 500 return mTypeLists[type].get(0); 501 } else { 502 return null; 503 } 504 } 505 506 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type, 507 boolean isDefaultNetwork) { 508 if (DBG) { 509 log("Sending " + state + 510 " broadcast for type " + type + " " + nai.name() + 511 " isDefaultNetwork=" + isDefaultNetwork); 512 } 513 } 514 515 /** Adds the given network to the specified legacy type list. */ 516 public void add(int type, NetworkAgentInfo nai) { 517 if (!isTypeSupported(type)) { 518 return; // Invalid network type. 519 } 520 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type); 521 522 ArrayList<NetworkAgentInfo> list = mTypeLists[type]; 523 if (list.contains(nai)) { 524 return; 525 } 526 527 list.add(nai); 528 529 // Send a broadcast if this is the first network of its type or if it's the default. 530 final boolean isDefaultNetwork = isDefaultNetwork(nai); 531 if (list.size() == 1 || isDefaultNetwork) { 532 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork); 533 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type); 534 } 535 } 536 537 /** Removes the given network from the specified legacy type list. */ 538 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) { 539 ArrayList<NetworkAgentInfo> list = mTypeLists[type]; 540 if (list == null || list.isEmpty()) { 541 return; 542 } 543 544 final boolean wasFirstNetwork = list.get(0).equals(nai); 545 546 if (!list.remove(nai)) { 547 return; 548 } 549 550 final DetailedState state = DetailedState.DISCONNECTED; 551 552 if (wasFirstNetwork || wasDefault) { 553 maybeLogBroadcast(nai, state, type, wasDefault); 554 sendLegacyNetworkBroadcast(nai, state, type); 555 } 556 557 if (!list.isEmpty() && wasFirstNetwork) { 558 if (DBG) log("Other network available for type " + type + 559 ", sending connected broadcast"); 560 final NetworkAgentInfo replacement = list.get(0); 561 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement)); 562 sendLegacyNetworkBroadcast(replacement, state, type); 563 } 564 } 565 566 /** Removes the given network from all legacy type lists. */ 567 public void remove(NetworkAgentInfo nai, boolean wasDefault) { 568 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault); 569 for (int type = 0; type < mTypeLists.length; type++) { 570 remove(type, nai, wasDefault); 571 } 572 } 573 574 // send out another legacy broadcast - currently only used for suspend/unsuspend 575 // toggle 576 public void update(NetworkAgentInfo nai) { 577 final boolean isDefault = isDefaultNetwork(nai); 578 final DetailedState state = nai.networkInfo.getDetailedState(); 579 for (int type = 0; type < mTypeLists.length; type++) { 580 final ArrayList<NetworkAgentInfo> list = mTypeLists[type]; 581 final boolean contains = (list != null && list.contains(nai)); 582 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0)); 583 if (isFirst || (contains && isDefault)) { 584 maybeLogBroadcast(nai, state, type, isDefault); 585 sendLegacyNetworkBroadcast(nai, state, type); 586 } 587 } 588 } 589 590 private String naiToString(NetworkAgentInfo nai) { 591 String name = (nai != null) ? nai.name() : "null"; 592 String state = (nai.networkInfo != null) ? 593 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() : 594 "???/???"; 595 return name + " " + state; 596 } 597 598 public void dump(IndentingPrintWriter pw) { 599 pw.println("mLegacyTypeTracker:"); 600 pw.increaseIndent(); 601 pw.print("Supported types:"); 602 for (int type = 0; type < mTypeLists.length; type++) { 603 if (mTypeLists[type] != null) pw.print(" " + type); 604 } 605 pw.println(); 606 pw.println("Current state:"); 607 pw.increaseIndent(); 608 for (int type = 0; type < mTypeLists.length; type++) { 609 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue; 610 for (NetworkAgentInfo nai : mTypeLists[type]) { 611 pw.println(type + " " + naiToString(nai)); 612 } 613 } 614 pw.decreaseIndent(); 615 pw.decreaseIndent(); 616 pw.println(); 617 } 618 } 619 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(); 620 621 @VisibleForTesting 622 protected HandlerThread createHandlerThread() { 623 return new HandlerThread("ConnectivityServiceThread"); 624 } 625 626 public ConnectivityService(Context context, INetworkManagementService netManager, 627 INetworkStatsService statsService, INetworkPolicyManager policyManager) { 628 if (DBG) log("ConnectivityService starting up"); 629 630 mDefaultRequest = createInternetRequestForTransport(-1); 631 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, 632 new Binder(), NetworkRequestType.REQUEST); 633 mNetworkRequests.put(mDefaultRequest, defaultNRI); 634 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI); 635 636 mDefaultMobileDataRequest = createInternetRequestForTransport( 637 NetworkCapabilities.TRANSPORT_CELLULAR); 638 639 mHandlerThread = createHandlerThread(); 640 mHandlerThread.start(); 641 mHandler = new InternalHandler(mHandlerThread.getLooper()); 642 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper()); 643 644 // setup our unique device name 645 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) { 646 String id = Settings.Secure.getString(context.getContentResolver(), 647 Settings.Secure.ANDROID_ID); 648 if (id != null && id.length() > 0) { 649 String name = new String("android-").concat(id); 650 SystemProperties.set("net.hostname", name); 651 } 652 } 653 654 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(), 655 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000); 656 657 mContext = checkNotNull(context, "missing Context"); 658 mNetd = checkNotNull(netManager, "missing INetworkManagementService"); 659 mStatsService = checkNotNull(statsService, "missing INetworkStatsService"); 660 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager"); 661 mKeyStore = KeyStore.getInstance(); 662 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 663 664 try { 665 mPolicyManager.setConnectivityListener(mPolicyListener); 666 mRestrictBackground = mPolicyManager.getRestrictBackground(); 667 } catch (RemoteException e) { 668 // ouch, no rules updates means some processes may never get network 669 loge("unable to register INetworkPolicyListener" + e.toString()); 670 } 671 672 final PowerManager powerManager = (PowerManager) context.getSystemService( 673 Context.POWER_SERVICE); 674 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); 675 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger( 676 com.android.internal.R.integer.config_networkTransitionTimeout); 677 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); 678 679 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1]; 680 681 // TODO: What is the "correct" way to do determine if this is a wifi only device? 682 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false); 683 log("wifiOnly=" + wifiOnly); 684 String[] naStrings = context.getResources().getStringArray( 685 com.android.internal.R.array.networkAttributes); 686 for (String naString : naStrings) { 687 try { 688 NetworkConfig n = new NetworkConfig(naString); 689 if (VDBG) log("naString=" + naString + " config=" + n); 690 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) { 691 loge("Error in networkAttributes - ignoring attempt to define type " + 692 n.type); 693 continue; 694 } 695 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) { 696 log("networkAttributes - ignoring mobile as this dev is wifiOnly " + 697 n.type); 698 continue; 699 } 700 if (mNetConfigs[n.type] != null) { 701 loge("Error in networkAttributes - ignoring attempt to redefine type " + 702 n.type); 703 continue; 704 } 705 mLegacyTypeTracker.addSupportedType(n.type); 706 707 mNetConfigs[n.type] = n; 708 mNetworksDefined++; 709 } catch(Exception e) { 710 // ignore it - leave the entry null 711 } 712 } 713 714 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config. 715 if (mNetConfigs[TYPE_VPN] == null) { 716 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we 717 // don't need to add TYPE_VPN to mNetConfigs. 718 mLegacyTypeTracker.addSupportedType(TYPE_VPN); 719 mNetworksDefined++; // used only in the log() statement below. 720 } 721 722 if (VDBG) log("mNetworksDefined=" + mNetworksDefined); 723 724 mProtectedNetworks = new ArrayList<Integer>(); 725 int[] protectedNetworks = context.getResources().getIntArray( 726 com.android.internal.R.array.config_protectedNetworks); 727 for (int p : protectedNetworks) { 728 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) { 729 mProtectedNetworks.add(p); 730 } else { 731 if (DBG) loge("Ignoring protectedNetwork " + p); 732 } 733 } 734 735 mTestMode = SystemProperties.get("cm.test.mode").equals("true") 736 && SystemProperties.get("ro.build.type").equals("eng"); 737 738 mTethering = new Tethering(mContext, mNetd, statsService); 739 740 mPermissionMonitor = new PermissionMonitor(mContext, mNetd); 741 742 //set up the listener for user state for creating user VPNs 743 IntentFilter intentFilter = new IntentFilter(); 744 intentFilter.addAction(Intent.ACTION_USER_STARTED); 745 intentFilter.addAction(Intent.ACTION_USER_STOPPED); 746 intentFilter.addAction(Intent.ACTION_USER_ADDED); 747 intentFilter.addAction(Intent.ACTION_USER_REMOVED); 748 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED); 749 mContext.registerReceiverAsUser( 750 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null); 751 752 try { 753 mNetd.registerObserver(mTethering); 754 mNetd.registerObserver(mDataActivityObserver); 755 } catch (RemoteException e) { 756 loge("Error registering observer :" + e); 757 } 758 759 if (DBG) { 760 mInetLog = new ArrayList(); 761 } 762 763 mSettingsObserver = new SettingsObserver(mContext, mHandler); 764 registerSettingsCallbacks(); 765 766 mDataConnectionStats = new DataConnectionStats(mContext); 767 mDataConnectionStats.startMonitoring(); 768 769 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED); 770 771 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE); 772 773 mKeepaliveTracker = new KeepaliveTracker(mHandler); 774 } 775 776 private NetworkRequest createInternetRequestForTransport(int transportType) { 777 NetworkCapabilities netCap = new NetworkCapabilities(); 778 netCap.addCapability(NET_CAPABILITY_INTERNET); 779 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED); 780 if (transportType > -1) { 781 netCap.addTransportType(transportType); 782 } 783 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId()); 784 } 785 786 private void handleMobileDataAlwaysOn() { 787 final boolean enable = (Settings.Global.getInt( 788 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1); 789 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null); 790 if (enable == isEnabled) { 791 return; // Nothing to do. 792 } 793 794 if (enable) { 795 handleRegisterNetworkRequest(new NetworkRequestInfo( 796 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST)); 797 } else { 798 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID); 799 } 800 } 801 802 private void registerSettingsCallbacks() { 803 // Watch for global HTTP proxy changes. 804 mSettingsObserver.observe( 805 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY), 806 EVENT_APPLY_GLOBAL_HTTP_PROXY); 807 808 // Watch for whether or not to keep mobile data always on. 809 mSettingsObserver.observe( 810 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON), 811 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON); 812 } 813 814 private synchronized int nextNetworkRequestId() { 815 return mNextNetworkRequestId++; 816 } 817 818 @VisibleForTesting 819 protected int reserveNetId() { 820 synchronized (mNetworkForNetId) { 821 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) { 822 int netId = mNextNetId; 823 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID; 824 // Make sure NetID unused. http://b/16815182 825 if (!mNetIdInUse.get(netId)) { 826 mNetIdInUse.put(netId, true); 827 return netId; 828 } 829 } 830 } 831 throw new IllegalStateException("No free netIds"); 832 } 833 834 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) { 835 if (mLegacyTypeTracker.isTypeSupported(networkType)) { 836 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 837 final NetworkState state; 838 if (nai != null) { 839 state = nai.getNetworkState(); 840 state.networkInfo.setType(networkType); 841 } else { 842 final NetworkInfo info = new NetworkInfo(networkType, 0, 843 getNetworkTypeName(networkType), ""); 844 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null); 845 info.setIsAvailable(true); 846 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(), 847 null, null, null); 848 } 849 filterNetworkStateForUid(state, uid, ignoreBlocked); 850 return state; 851 } else { 852 return NetworkState.EMPTY; 853 } 854 } 855 856 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) { 857 if (network == null) { 858 return null; 859 } 860 synchronized (mNetworkForNetId) { 861 return mNetworkForNetId.get(network.netId); 862 } 863 } 864 865 private Network[] getVpnUnderlyingNetworks(int uid) { 866 if (!mLockdownEnabled) { 867 int user = UserHandle.getUserId(uid); 868 synchronized (mVpns) { 869 Vpn vpn = mVpns.get(user); 870 if (vpn != null && vpn.appliesToUid(uid)) { 871 return vpn.getUnderlyingNetworks(); 872 } 873 } 874 } 875 return null; 876 } 877 878 private NetworkState getUnfilteredActiveNetworkState(int uid) { 879 NetworkAgentInfo nai = getDefaultNetwork(); 880 881 final Network[] networks = getVpnUnderlyingNetworks(uid); 882 if (networks != null) { 883 // getUnderlyingNetworks() returns: 884 // null => there was no VPN, or the VPN didn't specify anything, so we use the default. 885 // empty array => the VPN explicitly said "no default network". 886 // non-empty array => the VPN specified one or more default networks; we use the 887 // first one. 888 if (networks.length > 0) { 889 nai = getNetworkAgentInfoForNetwork(networks[0]); 890 } else { 891 nai = null; 892 } 893 } 894 895 if (nai != null) { 896 return nai.getNetworkState(); 897 } else { 898 return NetworkState.EMPTY; 899 } 900 } 901 902 /** 903 * Check if UID should be blocked from using the network with the given LinkProperties. 904 */ 905 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid, 906 boolean ignoreBlocked) { 907 // Networks aren't blocked when ignoring blocked status 908 if (ignoreBlocked) return false; 909 // Networks are never blocked for system services 910 if (uid < Process.FIRST_APPLICATION_UID) return false; 911 912 final boolean networkMetered; 913 final int uidRules; 914 915 final String iface = (lp == null ? "" : lp.getInterfaceName()); 916 synchronized (mRulesLock) { 917 networkMetered = mMeteredIfaces.contains(iface); 918 uidRules = mUidRules.get(uid, RULE_UNKNOWN); 919 } 920 921 switch (uidRules) { 922 case RULE_ALLOW_ALL: 923 case RULE_ALLOW_METERED: 924 case RULE_TEMPORARY_ALLOW_METERED: 925 return false; 926 case RULE_REJECT_METERED: 927 return networkMetered; 928 case RULE_REJECT_ALL: 929 return true; 930 case RULE_UNKNOWN: 931 default: 932 // When background data is restricted device-wide, the default 933 // behavior for apps should be like RULE_REJECT_METERED 934 return mRestrictBackground ? networkMetered : false; 935 } 936 } 937 938 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) { 939 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return; 940 boolean removed = false; 941 boolean added = false; 942 synchronized (mBlockedAppUids) { 943 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) { 944 added = true; 945 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) { 946 removed = true; 947 } 948 } 949 if (added) log("Returning blocked NetworkInfo to uid=" + uid); 950 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid); 951 } 952 953 /** 954 * Apply any relevant filters to {@link NetworkState} for the given UID. For 955 * example, this may mark the network as {@link DetailedState#BLOCKED} based 956 * on {@link #isNetworkWithLinkPropertiesBlocked}, or 957 * {@link NetworkInfo#isMetered()} based on network policies. 958 */ 959 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) { 960 if (state == null || state.networkInfo == null || state.linkProperties == null) return; 961 962 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) { 963 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null); 964 } 965 if (mLockdownTracker != null) { 966 mLockdownTracker.augmentNetworkInfo(state.networkInfo); 967 } 968 969 // TODO: apply metered state closer to NetworkAgentInfo 970 final long token = Binder.clearCallingIdentity(); 971 try { 972 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state)); 973 } catch (RemoteException e) { 974 } finally { 975 Binder.restoreCallingIdentity(token); 976 } 977 } 978 979 /** 980 * Return NetworkInfo for the active (i.e., connected) network interface. 981 * It is assumed that at most one network is active at a time. If more 982 * than one is active, it is indeterminate which will be returned. 983 * @return the info for the active network, or {@code null} if none is 984 * active 985 */ 986 @Override 987 public NetworkInfo getActiveNetworkInfo() { 988 enforceAccessPermission(); 989 final int uid = Binder.getCallingUid(); 990 final NetworkState state = getUnfilteredActiveNetworkState(uid); 991 filterNetworkStateForUid(state, uid, false); 992 maybeLogBlockedNetworkInfo(state.networkInfo, uid); 993 return state.networkInfo; 994 } 995 996 @Override 997 public Network getActiveNetwork() { 998 enforceAccessPermission(); 999 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false); 1000 } 1001 1002 @Override 1003 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) { 1004 enforceConnectivityInternalPermission(); 1005 return getActiveNetworkForUidInternal(uid, ignoreBlocked); 1006 } 1007 1008 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) { 1009 final int user = UserHandle.getUserId(uid); 1010 int vpnNetId = NETID_UNSET; 1011 synchronized (mVpns) { 1012 final Vpn vpn = mVpns.get(user); 1013 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId(); 1014 } 1015 NetworkAgentInfo nai; 1016 if (vpnNetId != NETID_UNSET) { 1017 synchronized (mNetworkForNetId) { 1018 nai = mNetworkForNetId.get(vpnNetId); 1019 } 1020 if (nai != null) return nai.network; 1021 } 1022 nai = getDefaultNetwork(); 1023 if (nai != null 1024 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) { 1025 nai = null; 1026 } 1027 return nai != null ? nai.network : null; 1028 } 1029 1030 public NetworkInfo getActiveNetworkInfoUnfiltered() { 1031 enforceAccessPermission(); 1032 final int uid = Binder.getCallingUid(); 1033 NetworkState state = getUnfilteredActiveNetworkState(uid); 1034 return state.networkInfo; 1035 } 1036 1037 @Override 1038 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) { 1039 enforceConnectivityInternalPermission(); 1040 final NetworkState state = getUnfilteredActiveNetworkState(uid); 1041 filterNetworkStateForUid(state, uid, ignoreBlocked); 1042 return state.networkInfo; 1043 } 1044 1045 @Override 1046 public NetworkInfo getNetworkInfo(int networkType) { 1047 enforceAccessPermission(); 1048 final int uid = Binder.getCallingUid(); 1049 if (getVpnUnderlyingNetworks(uid) != null) { 1050 // A VPN is active, so we may need to return one of its underlying networks. This 1051 // information is not available in LegacyTypeTracker, so we have to get it from 1052 // getUnfilteredActiveNetworkState. 1053 final NetworkState state = getUnfilteredActiveNetworkState(uid); 1054 if (state.networkInfo != null && state.networkInfo.getType() == networkType) { 1055 filterNetworkStateForUid(state, uid, false); 1056 return state.networkInfo; 1057 } 1058 } 1059 final NetworkState state = getFilteredNetworkState(networkType, uid, false); 1060 return state.networkInfo; 1061 } 1062 1063 @Override 1064 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) { 1065 enforceAccessPermission(); 1066 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 1067 if (nai != null) { 1068 final NetworkState state = nai.getNetworkState(); 1069 filterNetworkStateForUid(state, uid, ignoreBlocked); 1070 return state.networkInfo; 1071 } else { 1072 return null; 1073 } 1074 } 1075 1076 @Override 1077 public NetworkInfo[] getAllNetworkInfo() { 1078 enforceAccessPermission(); 1079 final ArrayList<NetworkInfo> result = Lists.newArrayList(); 1080 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE; 1081 networkType++) { 1082 NetworkInfo info = getNetworkInfo(networkType); 1083 if (info != null) { 1084 result.add(info); 1085 } 1086 } 1087 return result.toArray(new NetworkInfo[result.size()]); 1088 } 1089 1090 @Override 1091 public Network getNetworkForType(int networkType) { 1092 enforceAccessPermission(); 1093 final int uid = Binder.getCallingUid(); 1094 NetworkState state = getFilteredNetworkState(networkType, uid, false); 1095 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) { 1096 return state.network; 1097 } 1098 return null; 1099 } 1100 1101 @Override 1102 public Network[] getAllNetworks() { 1103 enforceAccessPermission(); 1104 synchronized (mNetworkForNetId) { 1105 final Network[] result = new Network[mNetworkForNetId.size()]; 1106 for (int i = 0; i < mNetworkForNetId.size(); i++) { 1107 result[i] = mNetworkForNetId.valueAt(i).network; 1108 } 1109 return result; 1110 } 1111 } 1112 1113 @Override 1114 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) { 1115 // The basic principle is: if an app's traffic could possibly go over a 1116 // network, without the app doing anything multinetwork-specific, 1117 // (hence, by "default"), then include that network's capabilities in 1118 // the array. 1119 // 1120 // In the normal case, app traffic only goes over the system's default 1121 // network connection, so that's the only network returned. 1122 // 1123 // With a VPN in force, some app traffic may go into the VPN, and thus 1124 // over whatever underlying networks the VPN specifies, while other app 1125 // traffic may go over the system default network (e.g.: a split-tunnel 1126 // VPN, or an app disallowed by the VPN), so the set of networks 1127 // returned includes the VPN's underlying networks and the system 1128 // default. 1129 enforceAccessPermission(); 1130 1131 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>(); 1132 1133 NetworkAgentInfo nai = getDefaultNetwork(); 1134 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai); 1135 if (nc != null) { 1136 result.put(nai.network, nc); 1137 } 1138 1139 if (!mLockdownEnabled) { 1140 synchronized (mVpns) { 1141 Vpn vpn = mVpns.get(userId); 1142 if (vpn != null) { 1143 Network[] networks = vpn.getUnderlyingNetworks(); 1144 if (networks != null) { 1145 for (Network network : networks) { 1146 nai = getNetworkAgentInfoForNetwork(network); 1147 nc = getNetworkCapabilitiesInternal(nai); 1148 if (nc != null) { 1149 result.put(network, nc); 1150 } 1151 } 1152 } 1153 } 1154 } 1155 } 1156 1157 NetworkCapabilities[] out = new NetworkCapabilities[result.size()]; 1158 out = result.values().toArray(out); 1159 return out; 1160 } 1161 1162 @Override 1163 public boolean isNetworkSupported(int networkType) { 1164 enforceAccessPermission(); 1165 return mLegacyTypeTracker.isTypeSupported(networkType); 1166 } 1167 1168 /** 1169 * Return LinkProperties for the active (i.e., connected) default 1170 * network interface. It is assumed that at most one default network 1171 * is active at a time. If more than one is active, it is indeterminate 1172 * which will be returned. 1173 * @return the ip properties for the active network, or {@code null} if 1174 * none is active 1175 */ 1176 @Override 1177 public LinkProperties getActiveLinkProperties() { 1178 enforceAccessPermission(); 1179 final int uid = Binder.getCallingUid(); 1180 NetworkState state = getUnfilteredActiveNetworkState(uid); 1181 return state.linkProperties; 1182 } 1183 1184 @Override 1185 public LinkProperties getLinkPropertiesForType(int networkType) { 1186 enforceAccessPermission(); 1187 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 1188 if (nai != null) { 1189 synchronized (nai) { 1190 return new LinkProperties(nai.linkProperties); 1191 } 1192 } 1193 return null; 1194 } 1195 1196 // TODO - this should be ALL networks 1197 @Override 1198 public LinkProperties getLinkProperties(Network network) { 1199 enforceAccessPermission(); 1200 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 1201 if (nai != null) { 1202 synchronized (nai) { 1203 return new LinkProperties(nai.linkProperties); 1204 } 1205 } 1206 return null; 1207 } 1208 1209 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) { 1210 if (nai != null) { 1211 synchronized (nai) { 1212 if (nai.networkCapabilities != null) { 1213 return new NetworkCapabilities(nai.networkCapabilities); 1214 } 1215 } 1216 } 1217 return null; 1218 } 1219 1220 @Override 1221 public NetworkCapabilities getNetworkCapabilities(Network network) { 1222 enforceAccessPermission(); 1223 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network)); 1224 } 1225 1226 @Override 1227 public NetworkState[] getAllNetworkState() { 1228 // Require internal since we're handing out IMSI details 1229 enforceConnectivityInternalPermission(); 1230 1231 final ArrayList<NetworkState> result = Lists.newArrayList(); 1232 for (Network network : getAllNetworks()) { 1233 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 1234 if (nai != null) { 1235 result.add(nai.getNetworkState()); 1236 } 1237 } 1238 return result.toArray(new NetworkState[result.size()]); 1239 } 1240 1241 @Override 1242 public NetworkQuotaInfo getActiveNetworkQuotaInfo() { 1243 enforceAccessPermission(); 1244 final int uid = Binder.getCallingUid(); 1245 final long token = Binder.clearCallingIdentity(); 1246 try { 1247 final NetworkState state = getUnfilteredActiveNetworkState(uid); 1248 if (state.networkInfo != null) { 1249 try { 1250 return mPolicyManager.getNetworkQuotaInfo(state); 1251 } catch (RemoteException e) { 1252 } 1253 } 1254 return null; 1255 } finally { 1256 Binder.restoreCallingIdentity(token); 1257 } 1258 } 1259 1260 @Override 1261 public boolean isActiveNetworkMetered() { 1262 enforceAccessPermission(); 1263 1264 final NetworkInfo info = getActiveNetworkInfo(); 1265 return (info != null) ? info.isMetered() : false; 1266 } 1267 1268 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() { 1269 @Override 1270 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) { 1271 int deviceType = Integer.parseInt(label); 1272 sendDataActivityBroadcast(deviceType, active, tsNanos); 1273 } 1274 }; 1275 1276 /** 1277 * Ensure that a network route exists to deliver traffic to the specified 1278 * host via the specified network interface. 1279 * @param networkType the type of the network over which traffic to the 1280 * specified host is to be routed 1281 * @param hostAddress the IP address of the host to which the route is 1282 * desired 1283 * @return {@code true} on success, {@code false} on failure 1284 */ 1285 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) { 1286 enforceChangePermission(); 1287 if (mProtectedNetworks.contains(networkType)) { 1288 enforceConnectivityInternalPermission(); 1289 } 1290 1291 InetAddress addr; 1292 try { 1293 addr = InetAddress.getByAddress(hostAddress); 1294 } catch (UnknownHostException e) { 1295 if (DBG) log("requestRouteToHostAddress got " + e.toString()); 1296 return false; 1297 } 1298 1299 if (!ConnectivityManager.isNetworkTypeValid(networkType)) { 1300 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType); 1301 return false; 1302 } 1303 1304 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 1305 if (nai == null) { 1306 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) { 1307 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType); 1308 } else { 1309 if (DBG) log("requestRouteToHostAddress on down network: " + networkType); 1310 } 1311 return false; 1312 } 1313 1314 DetailedState netState; 1315 synchronized (nai) { 1316 netState = nai.networkInfo.getDetailedState(); 1317 } 1318 1319 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) { 1320 if (VDBG) { 1321 log("requestRouteToHostAddress on down network " 1322 + "(" + networkType + ") - dropped" 1323 + " netState=" + netState); 1324 } 1325 return false; 1326 } 1327 1328 final int uid = Binder.getCallingUid(); 1329 final long token = Binder.clearCallingIdentity(); 1330 try { 1331 LinkProperties lp; 1332 int netId; 1333 synchronized (nai) { 1334 lp = nai.linkProperties; 1335 netId = nai.network.netId; 1336 } 1337 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid); 1338 if (DBG) log("requestRouteToHostAddress ok=" + ok); 1339 return ok; 1340 } finally { 1341 Binder.restoreCallingIdentity(token); 1342 } 1343 } 1344 1345 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) { 1346 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr); 1347 if (bestRoute == null) { 1348 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName()); 1349 } else { 1350 String iface = bestRoute.getInterface(); 1351 if (bestRoute.getGateway().equals(addr)) { 1352 // if there is no better route, add the implied hostroute for our gateway 1353 bestRoute = RouteInfo.makeHostRoute(addr, iface); 1354 } else { 1355 // if we will connect to this through another route, add a direct route 1356 // to it's gateway 1357 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface); 1358 } 1359 } 1360 if (DBG) log("Adding legacy route " + bestRoute + 1361 " for UID/PID " + uid + "/" + Binder.getCallingPid()); 1362 try { 1363 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid); 1364 } catch (Exception e) { 1365 // never crash - catch them all 1366 if (DBG) loge("Exception trying to add a route: " + e); 1367 return false; 1368 } 1369 return true; 1370 } 1371 1372 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() { 1373 @Override 1374 public void onUidRulesChanged(int uid, int uidRules) { 1375 // caller is NPMS, since we only register with them 1376 if (LOGD_RULES) { 1377 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")"); 1378 } 1379 1380 synchronized (mRulesLock) { 1381 // skip update when we've already applied rules 1382 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL); 1383 if (oldRules == uidRules) return; 1384 1385 mUidRules.put(uid, uidRules); 1386 } 1387 1388 // TODO: notify UID when it has requested targeted updates 1389 } 1390 1391 @Override 1392 public void onMeteredIfacesChanged(String[] meteredIfaces) { 1393 // caller is NPMS, since we only register with them 1394 if (LOGD_RULES) { 1395 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")"); 1396 } 1397 1398 synchronized (mRulesLock) { 1399 mMeteredIfaces.clear(); 1400 for (String iface : meteredIfaces) { 1401 mMeteredIfaces.add(iface); 1402 } 1403 } 1404 } 1405 1406 @Override 1407 public void onRestrictBackgroundChanged(boolean restrictBackground) { 1408 // caller is NPMS, since we only register with them 1409 if (LOGD_RULES) { 1410 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")"); 1411 } 1412 1413 synchronized (mRulesLock) { 1414 mRestrictBackground = restrictBackground; 1415 } 1416 1417 if (restrictBackground) { 1418 log("onRestrictBackgroundChanged(true): disabling tethering"); 1419 mTethering.untetherAll(); 1420 } 1421 } 1422 1423 @Override 1424 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) { 1425 if (LOGD_RULES) { 1426 // caller is NPMS, since we only register with them 1427 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted=" 1428 + whitelisted + ")"); 1429 } 1430 } 1431 }; 1432 1433 /** 1434 * Require that the caller is either in the same user or has appropriate permission to interact 1435 * across users. 1436 * 1437 * @param userId Target user for whatever operation the current IPC is supposed to perform. 1438 */ 1439 private void enforceCrossUserPermission(int userId) { 1440 if (userId == UserHandle.getCallingUserId()) { 1441 // Not a cross-user call. 1442 return; 1443 } 1444 mContext.enforceCallingOrSelfPermission( 1445 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 1446 "ConnectivityService"); 1447 } 1448 1449 private void enforceInternetPermission() { 1450 mContext.enforceCallingOrSelfPermission( 1451 android.Manifest.permission.INTERNET, 1452 "ConnectivityService"); 1453 } 1454 1455 private void enforceAccessPermission() { 1456 mContext.enforceCallingOrSelfPermission( 1457 android.Manifest.permission.ACCESS_NETWORK_STATE, 1458 "ConnectivityService"); 1459 } 1460 1461 private void enforceChangePermission() { 1462 ConnectivityManager.enforceChangePermission(mContext); 1463 } 1464 1465 private void enforceTetherAccessPermission() { 1466 mContext.enforceCallingOrSelfPermission( 1467 android.Manifest.permission.ACCESS_NETWORK_STATE, 1468 "ConnectivityService"); 1469 } 1470 1471 private void enforceConnectivityInternalPermission() { 1472 mContext.enforceCallingOrSelfPermission( 1473 android.Manifest.permission.CONNECTIVITY_INTERNAL, 1474 "ConnectivityService"); 1475 } 1476 1477 private void enforceKeepalivePermission() { 1478 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService"); 1479 } 1480 1481 public void sendConnectedBroadcast(NetworkInfo info) { 1482 enforceConnectivityInternalPermission(); 1483 sendGeneralBroadcast(info, CONNECTIVITY_ACTION); 1484 } 1485 1486 private void sendInetConditionBroadcast(NetworkInfo info) { 1487 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION); 1488 } 1489 1490 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) { 1491 if (mLockdownTracker != null) { 1492 info = new NetworkInfo(info); 1493 mLockdownTracker.augmentNetworkInfo(info); 1494 } 1495 1496 Intent intent = new Intent(bcastType); 1497 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info)); 1498 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 1499 if (info.isFailover()) { 1500 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 1501 info.setFailover(false); 1502 } 1503 if (info.getReason() != null) { 1504 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 1505 } 1506 if (info.getExtraInfo() != null) { 1507 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, 1508 info.getExtraInfo()); 1509 } 1510 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished); 1511 return intent; 1512 } 1513 1514 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) { 1515 sendStickyBroadcast(makeGeneralIntent(info, bcastType)); 1516 } 1517 1518 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) { 1519 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE); 1520 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType); 1521 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active); 1522 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos); 1523 final long ident = Binder.clearCallingIdentity(); 1524 try { 1525 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL, 1526 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null); 1527 } finally { 1528 Binder.restoreCallingIdentity(ident); 1529 } 1530 } 1531 1532 private void sendStickyBroadcast(Intent intent) { 1533 synchronized(this) { 1534 if (!mSystemReady) { 1535 mInitialBroadcast = new Intent(intent); 1536 } 1537 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1538 if (VDBG) { 1539 log("sendStickyBroadcast: action=" + intent.getAction()); 1540 } 1541 1542 Bundle options = null; 1543 final long ident = Binder.clearCallingIdentity(); 1544 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { 1545 final NetworkInfo ni = intent.getParcelableExtra( 1546 ConnectivityManager.EXTRA_NETWORK_INFO); 1547 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) { 1548 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL); 1549 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 1550 } else { 1551 BroadcastOptions opts = BroadcastOptions.makeBasic(); 1552 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M); 1553 options = opts.toBundle(); 1554 } 1555 final IBatteryStats bs = BatteryStatsService.getService(); 1556 try { 1557 bs.noteConnectivityChanged(intent.getIntExtra( 1558 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE), 1559 ni != null ? ni.getState().toString() : "?"); 1560 } catch (RemoteException e) { 1561 } 1562 } 1563 try { 1564 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options); 1565 } finally { 1566 Binder.restoreCallingIdentity(ident); 1567 } 1568 } 1569 } 1570 1571 void systemReady() { 1572 loadGlobalProxy(); 1573 1574 synchronized(this) { 1575 mSystemReady = true; 1576 if (mInitialBroadcast != null) { 1577 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL); 1578 mInitialBroadcast = null; 1579 } 1580 } 1581 // load the global proxy at startup 1582 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY)); 1583 1584 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait 1585 // for user to unlock device too. 1586 updateLockdownVpn(); 1587 1588 // Configure whether mobile data is always on. 1589 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON)); 1590 1591 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY)); 1592 1593 mPermissionMonitor.startMonitoring(); 1594 } 1595 1596 /** 1597 * Setup data activity tracking for the given network. 1598 * 1599 * Every {@code setupDataActivityTracking} should be paired with a 1600 * {@link #removeDataActivityTracking} for cleanup. 1601 */ 1602 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) { 1603 final String iface = networkAgent.linkProperties.getInterfaceName(); 1604 1605 final int timeout; 1606 int type = ConnectivityManager.TYPE_NONE; 1607 1608 if (networkAgent.networkCapabilities.hasTransport( 1609 NetworkCapabilities.TRANSPORT_CELLULAR)) { 1610 timeout = Settings.Global.getInt(mContext.getContentResolver(), 1611 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE, 1612 10); 1613 type = ConnectivityManager.TYPE_MOBILE; 1614 } else if (networkAgent.networkCapabilities.hasTransport( 1615 NetworkCapabilities.TRANSPORT_WIFI)) { 1616 timeout = Settings.Global.getInt(mContext.getContentResolver(), 1617 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI, 1618 15); 1619 type = ConnectivityManager.TYPE_WIFI; 1620 } else { 1621 // do not track any other networks 1622 timeout = 0; 1623 } 1624 1625 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) { 1626 try { 1627 mNetd.addIdleTimer(iface, timeout, type); 1628 } catch (Exception e) { 1629 // You shall not crash! 1630 loge("Exception in setupDataActivityTracking " + e); 1631 } 1632 } 1633 } 1634 1635 /** 1636 * Remove data activity tracking when network disconnects. 1637 */ 1638 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) { 1639 final String iface = networkAgent.linkProperties.getInterfaceName(); 1640 final NetworkCapabilities caps = networkAgent.networkCapabilities; 1641 1642 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || 1643 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) { 1644 try { 1645 // the call fails silently if no idletimer setup for this interface 1646 mNetd.removeIdleTimer(iface); 1647 } catch (Exception e) { 1648 loge("Exception in removeDataActivityTracking " + e); 1649 } 1650 } 1651 } 1652 1653 /** 1654 * Reads the network specific MTU size from reources. 1655 * and set it on it's iface. 1656 */ 1657 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) { 1658 final String iface = newLp.getInterfaceName(); 1659 final int mtu = newLp.getMtu(); 1660 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) { 1661 if (VDBG) log("identical MTU - not setting"); 1662 return; 1663 } 1664 1665 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) { 1666 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface); 1667 return; 1668 } 1669 1670 // Cannot set MTU without interface name 1671 if (TextUtils.isEmpty(iface)) { 1672 loge("Setting MTU size with null iface."); 1673 return; 1674 } 1675 1676 try { 1677 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu); 1678 mNetd.setMtu(iface, mtu); 1679 } catch (Exception e) { 1680 Slog.e(TAG, "exception in setMtu()" + e); 1681 } 1682 } 1683 1684 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208"; 1685 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd"; 1686 1687 // Overridden for testing purposes to avoid writing to SystemProperties. 1688 @VisibleForTesting 1689 protected int getDefaultTcpRwnd() { 1690 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0); 1691 } 1692 1693 private void updateTcpBufferSizes(NetworkAgentInfo nai) { 1694 if (isDefaultNetwork(nai) == false) { 1695 return; 1696 } 1697 1698 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes(); 1699 String[] values = null; 1700 if (tcpBufferSizes != null) { 1701 values = tcpBufferSizes.split(","); 1702 } 1703 1704 if (values == null || values.length != 6) { 1705 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults"); 1706 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES; 1707 values = tcpBufferSizes.split(","); 1708 } 1709 1710 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return; 1711 1712 try { 1713 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes); 1714 1715 final String prefix = "/sys/kernel/ipv4/tcp_"; 1716 FileUtils.stringToFile(prefix + "rmem_min", values[0]); 1717 FileUtils.stringToFile(prefix + "rmem_def", values[1]); 1718 FileUtils.stringToFile(prefix + "rmem_max", values[2]); 1719 FileUtils.stringToFile(prefix + "wmem_min", values[3]); 1720 FileUtils.stringToFile(prefix + "wmem_def", values[4]); 1721 FileUtils.stringToFile(prefix + "wmem_max", values[5]); 1722 mCurrentTcpBufferSizes = tcpBufferSizes; 1723 } catch (IOException e) { 1724 loge("Can't set TCP buffer sizes:" + e); 1725 } 1726 1727 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(), 1728 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd()); 1729 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd"; 1730 if (rwndValue != 0) { 1731 SystemProperties.set(sysctlKey, rwndValue.toString()); 1732 } 1733 } 1734 1735 private void flushVmDnsCache() { 1736 /* 1737 * Tell the VMs to toss their DNS caches 1738 */ 1739 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE); 1740 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 1741 /* 1742 * Connectivity events can happen before boot has completed ... 1743 */ 1744 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1745 final long ident = Binder.clearCallingIdentity(); 1746 try { 1747 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 1748 } finally { 1749 Binder.restoreCallingIdentity(ident); 1750 } 1751 } 1752 1753 @Override 1754 public int getRestoreDefaultNetworkDelay(int networkType) { 1755 String restoreDefaultNetworkDelayStr = SystemProperties.get( 1756 NETWORK_RESTORE_DELAY_PROP_NAME); 1757 if(restoreDefaultNetworkDelayStr != null && 1758 restoreDefaultNetworkDelayStr.length() != 0) { 1759 try { 1760 return Integer.parseInt(restoreDefaultNetworkDelayStr); 1761 } catch (NumberFormatException e) { 1762 } 1763 } 1764 // if the system property isn't set, use the value for the apn type 1765 int ret = RESTORE_DEFAULT_NETWORK_DELAY; 1766 1767 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) && 1768 (mNetConfigs[networkType] != null)) { 1769 ret = mNetConfigs[networkType].restoreTime; 1770 } 1771 return ret; 1772 } 1773 1774 private boolean argsContain(String[] args, String target) { 1775 for (String arg : args) { 1776 if (arg.equals(target)) return true; 1777 } 1778 return false; 1779 } 1780 1781 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) { 1782 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>(); 1783 final long DIAG_TIME_MS = 5000; 1784 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 1785 // Start gathering diagnostic information. 1786 netDiags.add(new NetworkDiagnostics( 1787 nai.network, 1788 new LinkProperties(nai.linkProperties), // Must be a copy. 1789 DIAG_TIME_MS)); 1790 } 1791 1792 for (NetworkDiagnostics netDiag : netDiags) { 1793 pw.println(); 1794 netDiag.waitForMeasurements(); 1795 netDiag.dump(pw); 1796 } 1797 } 1798 1799 @Override 1800 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) { 1801 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); 1802 if (mContext.checkCallingOrSelfPermission( 1803 android.Manifest.permission.DUMP) 1804 != PackageManager.PERMISSION_GRANTED) { 1805 pw.println("Permission Denial: can't dump ConnectivityService " + 1806 "from from pid=" + Binder.getCallingPid() + ", uid=" + 1807 Binder.getCallingUid()); 1808 return; 1809 } 1810 1811 if (argsContain(args, "--diag")) { 1812 dumpNetworkDiagnostics(pw); 1813 return; 1814 } 1815 1816 pw.print("NetworkFactories for:"); 1817 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 1818 pw.print(" " + nfi.name); 1819 } 1820 pw.println(); 1821 pw.println(); 1822 1823 final NetworkAgentInfo defaultNai = getDefaultNetwork(); 1824 pw.print("Active default network: "); 1825 if (defaultNai == null) { 1826 pw.println("none"); 1827 } else { 1828 pw.println(defaultNai.network.netId); 1829 } 1830 pw.println(); 1831 1832 pw.println("Current Networks:"); 1833 pw.increaseIndent(); 1834 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 1835 pw.println(nai.toString()); 1836 pw.increaseIndent(); 1837 pw.println("Requests:"); 1838 pw.increaseIndent(); 1839 for (int i = 0; i < nai.networkRequests.size(); i++) { 1840 pw.println(nai.networkRequests.valueAt(i).toString()); 1841 } 1842 pw.decreaseIndent(); 1843 pw.println("Lingered:"); 1844 pw.increaseIndent(); 1845 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString()); 1846 pw.decreaseIndent(); 1847 pw.decreaseIndent(); 1848 } 1849 pw.decreaseIndent(); 1850 pw.println(); 1851 1852 pw.println("Metered Interfaces:"); 1853 pw.increaseIndent(); 1854 for (String value : mMeteredIfaces) { 1855 pw.println(value); 1856 } 1857 pw.decreaseIndent(); 1858 pw.println(); 1859 1860 pw.print("Restrict background: "); 1861 pw.println(mRestrictBackground); 1862 pw.println(); 1863 1864 pw.println("Network Requests:"); 1865 pw.increaseIndent(); 1866 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 1867 pw.println(nri.toString()); 1868 } 1869 pw.println(); 1870 pw.decreaseIndent(); 1871 1872 mLegacyTypeTracker.dump(pw); 1873 1874 synchronized (this) { 1875 pw.print("mNetTransitionWakeLock: currently " + 1876 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held"); 1877 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) { 1878 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy); 1879 } else { 1880 pw.println(", last requested never"); 1881 } 1882 } 1883 1884 pw.println(); 1885 mTethering.dump(fd, pw, args); 1886 1887 pw.println(); 1888 mKeepaliveTracker.dump(pw); 1889 1890 pw.println(); 1891 1892 if (mInetLog != null && mInetLog.size() > 0) { 1893 pw.println(); 1894 pw.println("Inet condition reports:"); 1895 pw.increaseIndent(); 1896 for(int i = 0; i < mInetLog.size(); i++) { 1897 pw.println(mInetLog.get(i)); 1898 } 1899 pw.decreaseIndent(); 1900 } 1901 1902 if (argsContain(args, "--short") == false) { 1903 pw.println(); 1904 synchronized (mValidationLogs) { 1905 pw.println("mValidationLogs (most recent first):"); 1906 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) { 1907 pw.println(p.first); 1908 pw.increaseIndent(); 1909 p.second.dump(fd, pw, args); 1910 pw.decreaseIndent(); 1911 } 1912 } 1913 1914 pw.println(); 1915 pw.println("mNetworkRequestInfoLogs (most recent first):"); 1916 pw.increaseIndent(); 1917 mNetworkRequestInfoLogs.reverseDump(fd, pw, args); 1918 pw.decreaseIndent(); 1919 } 1920 } 1921 1922 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) { 1923 if (nai.network == null) return false; 1924 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network); 1925 if (officialNai != null && officialNai.equals(nai)) return true; 1926 if (officialNai != null || VDBG) { 1927 final String msg = sMagicDecoderRing.get(what, Integer.toString(what)); 1928 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai + 1929 " - " + nai); 1930 } 1931 return false; 1932 } 1933 1934 private boolean isRequest(NetworkRequest request) { 1935 return mNetworkRequests.get(request).isRequest(); 1936 } 1937 1938 // must be stateless - things change under us. 1939 private class NetworkStateTrackerHandler extends Handler { 1940 public NetworkStateTrackerHandler(Looper looper) { 1941 super(looper); 1942 } 1943 1944 private boolean maybeHandleAsyncChannelMessage(Message msg) { 1945 switch (msg.what) { 1946 default: 1947 return false; 1948 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: { 1949 handleAsyncChannelHalfConnect(msg); 1950 break; 1951 } 1952 case AsyncChannel.CMD_CHANNEL_DISCONNECT: { 1953 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 1954 if (nai != null) nai.asyncChannel.disconnect(); 1955 break; 1956 } 1957 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: { 1958 handleAsyncChannelDisconnected(msg); 1959 break; 1960 } 1961 } 1962 return true; 1963 } 1964 1965 private void maybeHandleNetworkAgentMessage(Message msg) { 1966 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 1967 if (nai == null) { 1968 if (VDBG) { 1969 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what)); 1970 log(String.format("%s from unknown NetworkAgent", what)); 1971 } 1972 return; 1973 } 1974 1975 switch (msg.what) { 1976 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: { 1977 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj; 1978 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) || 1979 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) { 1980 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability."); 1981 } 1982 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities( 1983 networkCapabilities)) { 1984 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: " 1985 + nai.networkCapabilities + " -> " + networkCapabilities); 1986 } 1987 updateCapabilities(nai, networkCapabilities); 1988 break; 1989 } 1990 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: { 1991 if (VDBG) { 1992 log("Update of LinkProperties for " + nai.name() + 1993 "; created=" + nai.created + 1994 "; everConnected=" + nai.everConnected); 1995 } 1996 LinkProperties oldLp = nai.linkProperties; 1997 synchronized (nai) { 1998 nai.linkProperties = (LinkProperties)msg.obj; 1999 } 2000 if (nai.everConnected) updateLinkProperties(nai, oldLp); 2001 break; 2002 } 2003 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: { 2004 NetworkInfo info = (NetworkInfo) msg.obj; 2005 updateNetworkInfo(nai, info); 2006 break; 2007 } 2008 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: { 2009 Integer score = (Integer) msg.obj; 2010 if (score != null) updateNetworkScore(nai, score.intValue()); 2011 break; 2012 } 2013 case NetworkAgent.EVENT_UID_RANGES_ADDED: { 2014 try { 2015 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj); 2016 } catch (Exception e) { 2017 // Never crash! 2018 loge("Exception in addVpnUidRanges: " + e); 2019 } 2020 break; 2021 } 2022 case NetworkAgent.EVENT_UID_RANGES_REMOVED: { 2023 try { 2024 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj); 2025 } catch (Exception e) { 2026 // Never crash! 2027 loge("Exception in removeVpnUidRanges: " + e); 2028 } 2029 break; 2030 } 2031 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: { 2032 if (nai.everConnected && !nai.networkMisc.explicitlySelected) { 2033 loge("ERROR: already-connected network explicitly selected."); 2034 } 2035 nai.networkMisc.explicitlySelected = true; 2036 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj; 2037 break; 2038 } 2039 case NetworkAgent.EVENT_PACKET_KEEPALIVE: { 2040 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg); 2041 break; 2042 } 2043 } 2044 } 2045 2046 private boolean maybeHandleNetworkMonitorMessage(Message msg) { 2047 switch (msg.what) { 2048 default: 2049 return false; 2050 case NetworkMonitor.EVENT_NETWORK_TESTED: { 2051 final NetworkAgentInfo nai; 2052 synchronized (mNetworkForNetId) { 2053 nai = mNetworkForNetId.get(msg.arg2); 2054 } 2055 if (nai != null) { 2056 final boolean valid = 2057 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID); 2058 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") + 2059 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj)); 2060 if (valid != nai.lastValidated) { 2061 final int oldScore = nai.getCurrentScore(); 2062 nai.lastValidated = valid; 2063 nai.everValidated |= valid; 2064 updateCapabilities(nai, nai.networkCapabilities); 2065 // If score has changed, rebroadcast to NetworkFactories. b/17726566 2066 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai); 2067 } 2068 updateInetCondition(nai); 2069 // Let the NetworkAgent know the state of its network 2070 Bundle redirectUrlBundle = new Bundle(); 2071 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj); 2072 nai.asyncChannel.sendMessage( 2073 NetworkAgent.CMD_REPORT_NETWORK_STATUS, 2074 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK), 2075 0, redirectUrlBundle); 2076 } 2077 break; 2078 } 2079 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: { 2080 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj; 2081 if (isLiveNetworkAgent(nai, msg.what)) { 2082 handleLingerComplete(nai); 2083 } 2084 break; 2085 } 2086 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: { 2087 final int netId = msg.arg2; 2088 final boolean visible = (msg.arg1 != 0); 2089 final NetworkAgentInfo nai; 2090 synchronized (mNetworkForNetId) { 2091 nai = mNetworkForNetId.get(netId); 2092 } 2093 // If captive portal status has changed, update capabilities. 2094 if (nai != null && (visible != nai.lastCaptivePortalDetected)) { 2095 nai.lastCaptivePortalDetected = visible; 2096 nai.everCaptivePortalDetected |= visible; 2097 updateCapabilities(nai, nai.networkCapabilities); 2098 } 2099 if (!visible) { 2100 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false); 2101 } else { 2102 if (nai == null) { 2103 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor"); 2104 break; 2105 } 2106 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN, 2107 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), 2108 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected); 2109 } 2110 break; 2111 } 2112 } 2113 return true; 2114 } 2115 2116 @Override 2117 public void handleMessage(Message msg) { 2118 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) { 2119 maybeHandleNetworkAgentMessage(msg); 2120 } 2121 } 2122 } 2123 2124 private void linger(NetworkAgentInfo nai) { 2125 nai.lingering = true; 2126 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER); 2127 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER); 2128 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING); 2129 } 2130 2131 // Cancel any lingering so the linger timeout doesn't teardown a network. 2132 // This should be called when a network begins satisfying a NetworkRequest. 2133 // Note: depending on what state the NetworkMonitor is in (e.g., 2134 // if it's awaiting captive portal login, or if validation failed), this 2135 // may trigger a re-evaluation of the network. 2136 private void unlinger(NetworkAgentInfo nai) { 2137 nai.networkLingered.clear(); 2138 if (!nai.lingering) return; 2139 nai.lingering = false; 2140 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER); 2141 if (VDBG) log("Canceling linger of " + nai.name()); 2142 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 2143 } 2144 2145 private void handleAsyncChannelHalfConnect(Message msg) { 2146 AsyncChannel ac = (AsyncChannel) msg.obj; 2147 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) { 2148 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 2149 if (VDBG) log("NetworkFactory connected"); 2150 // A network factory has connected. Send it all current NetworkRequests. 2151 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 2152 if (!nri.isRequest()) continue; 2153 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId); 2154 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, 2155 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request); 2156 } 2157 } else { 2158 loge("Error connecting NetworkFactory"); 2159 mNetworkFactoryInfos.remove(msg.obj); 2160 } 2161 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) { 2162 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 2163 if (VDBG) log("NetworkAgent connected"); 2164 // A network agent has requested a connection. Establish the connection. 2165 mNetworkAgentInfos.get(msg.replyTo).asyncChannel. 2166 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION); 2167 } else { 2168 loge("Error connecting NetworkAgent"); 2169 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo); 2170 if (nai != null) { 2171 final boolean wasDefault = isDefaultNetwork(nai); 2172 synchronized (mNetworkForNetId) { 2173 mNetworkForNetId.remove(nai.network.netId); 2174 mNetIdInUse.delete(nai.network.netId); 2175 } 2176 // Just in case. 2177 mLegacyTypeTracker.remove(nai, wasDefault); 2178 } 2179 } 2180 } 2181 } 2182 2183 private void handleAsyncChannelDisconnected(Message msg) { 2184 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 2185 if (nai != null) { 2186 if (DBG) { 2187 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size()); 2188 } 2189 // A network agent has disconnected. 2190 // TODO - if we move the logic to the network agent (have them disconnect 2191 // because they lost all their requests or because their score isn't good) 2192 // then they would disconnect organically, report their new state and then 2193 // disconnect the channel. 2194 if (nai.networkInfo.isConnected()) { 2195 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, 2196 null, null); 2197 } 2198 final boolean wasDefault = isDefaultNetwork(nai); 2199 if (wasDefault) { 2200 mDefaultInetConditionPublished = 0; 2201 } 2202 notifyIfacesChangedForNetworkStats(); 2203 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied 2204 // by other networks that are already connected. Perhaps that can be done by 2205 // sending all CALLBACK_LOST messages (for requests, not listens) at the end 2206 // of rematchAllNetworksAndRequests 2207 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST); 2208 mKeepaliveTracker.handleStopAllKeepalives(nai, 2209 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK); 2210 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED); 2211 mNetworkAgentInfos.remove(msg.replyTo); 2212 updateClat(null, nai.linkProperties, nai); 2213 synchronized (mNetworkForNetId) { 2214 // Remove the NetworkAgent, but don't mark the netId as 2215 // available until we've told netd to delete it below. 2216 mNetworkForNetId.remove(nai.network.netId); 2217 } 2218 // Remove all previously satisfied requests. 2219 for (int i = 0; i < nai.networkRequests.size(); i++) { 2220 NetworkRequest request = nai.networkRequests.valueAt(i); 2221 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId); 2222 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) { 2223 mNetworkForRequestId.remove(request.requestId); 2224 sendUpdatedScoreToFactories(request, 0); 2225 } 2226 } 2227 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 2228 removeDataActivityTracking(nai); 2229 notifyLockdownVpn(nai); 2230 requestNetworkTransitionWakelock(nai.name()); 2231 } 2232 mLegacyTypeTracker.remove(nai, wasDefault); 2233 rematchAllNetworksAndRequests(null, 0); 2234 if (wasDefault && getDefaultNetwork() == null) { 2235 // Log that we lost the default network and there is no replacement. 2236 logDefaultNetworkEvent(null, nai); 2237 } 2238 if (nai.created) { 2239 // Tell netd to clean up the configuration for this network 2240 // (routing rules, DNS, etc). 2241 // This may be slow as it requires a lot of netd shelling out to ip and 2242 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it 2243 // after we've rematched networks with requests which should make a potential 2244 // fallback network the default or requested a new network from the 2245 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily 2246 // long time. 2247 try { 2248 mNetd.removeNetwork(nai.network.netId); 2249 } catch (Exception e) { 2250 loge("Exception removing network: " + e); 2251 } 2252 } 2253 synchronized (mNetworkForNetId) { 2254 mNetIdInUse.delete(nai.network.netId); 2255 } 2256 } else { 2257 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo); 2258 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name); 2259 } 2260 } 2261 2262 // If this method proves to be too slow then we can maintain a separate 2263 // pendingIntent => NetworkRequestInfo map. 2264 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo. 2265 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) { 2266 Intent intent = pendingIntent.getIntent(); 2267 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) { 2268 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent; 2269 if (existingPendingIntent != null && 2270 existingPendingIntent.getIntent().filterEquals(intent)) { 2271 return entry.getValue(); 2272 } 2273 } 2274 return null; 2275 } 2276 2277 private void handleRegisterNetworkRequestWithIntent(Message msg) { 2278 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj); 2279 2280 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent); 2281 if (existingRequest != null) { // remove the existing request. 2282 if (DBG) log("Replacing " + existingRequest.request + " with " 2283 + nri.request + " because their intents matched."); 2284 handleReleaseNetworkRequest(existingRequest.request, getCallingUid()); 2285 } 2286 handleRegisterNetworkRequest(nri); 2287 } 2288 2289 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) { 2290 mNetworkRequests.put(nri.request, nri); 2291 mNetworkRequestInfoLogs.log("REGISTER " + nri); 2292 if (!nri.isRequest()) { 2293 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) { 2294 if (nri.request.networkCapabilities.hasSignalStrength() && 2295 network.satisfiesImmutableCapabilitiesOf(nri.request)) { 2296 updateSignalStrengthThresholds(network, "REGISTER", nri.request); 2297 } 2298 } 2299 } 2300 rematchAllNetworksAndRequests(null, 0); 2301 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) { 2302 sendUpdatedScoreToFactories(nri.request, 0); 2303 } 2304 } 2305 2306 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent, 2307 int callingUid) { 2308 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent); 2309 if (nri != null) { 2310 handleReleaseNetworkRequest(nri.request, callingUid); 2311 } 2312 } 2313 2314 // Is nai unneeded by all NetworkRequests (and should be disconnected)? 2315 // This is whether it is satisfying any NetworkRequests or were it to become validated, 2316 // would it have a chance of satisfying any NetworkRequests. 2317 private boolean unneeded(NetworkAgentInfo nai) { 2318 if (!nai.everConnected || nai.isVPN() || nai.lingering) return false; 2319 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 2320 // If this Network is already the highest scoring Network for a request, or if 2321 // there is hope for it to become one if it validated, then it is needed. 2322 if (nri.isRequest() && nai.satisfies(nri.request) && 2323 (nai.networkRequests.get(nri.request.requestId) != null || 2324 // Note that this catches two important cases: 2325 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi 2326 // is currently satisfying the request. This is desirable when 2327 // cellular ends up validating but WiFi does not. 2328 // 2. Unvalidated WiFi will not be reaped when validated cellular 2329 // is currently satisfying the request. This is desirable when 2330 // WiFi ends up validating and out scoring cellular. 2331 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() < 2332 nai.getCurrentScoreAsValidated())) { 2333 return false; 2334 } 2335 } 2336 return true; 2337 } 2338 2339 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) { 2340 NetworkRequestInfo nri = mNetworkRequests.get(request); 2341 if (nri != null) { 2342 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) { 2343 if (DBG) log("Attempt to release unowned NetworkRequest " + request); 2344 return; 2345 } 2346 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request); 2347 nri.unlinkDeathRecipient(); 2348 mNetworkRequests.remove(request); 2349 synchronized (mUidToNetworkRequestCount) { 2350 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0); 2351 if (requests < 1) { 2352 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " + 2353 nri.mUid); 2354 } else if (requests == 1) { 2355 mUidToNetworkRequestCount.removeAt( 2356 mUidToNetworkRequestCount.indexOfKey(nri.mUid)); 2357 } else { 2358 mUidToNetworkRequestCount.put(nri.mUid, requests - 1); 2359 } 2360 } 2361 mNetworkRequestInfoLogs.log("RELEASE " + nri); 2362 if (nri.isRequest()) { 2363 // Find all networks that are satisfying this request and remove the request 2364 // from their request lists. 2365 // TODO - it's my understanding that for a request there is only a single 2366 // network satisfying it, so this loop is wasteful 2367 boolean wasKept = false; 2368 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2369 if (nai.networkRequests.get(nri.request.requestId) != null) { 2370 nai.networkRequests.remove(nri.request.requestId); 2371 if (VDBG) { 2372 log(" Removing from current network " + nai.name() + 2373 ", leaving " + nai.networkRequests.size() + 2374 " requests."); 2375 } 2376 if (unneeded(nai)) { 2377 if (DBG) log("no live requests for " + nai.name() + "; disconnecting"); 2378 teardownUnneededNetwork(nai); 2379 } else { 2380 // suspect there should only be one pass through here 2381 // but if any were kept do the check below 2382 wasKept |= true; 2383 } 2384 } 2385 } 2386 2387 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId); 2388 if (nai != null) { 2389 mNetworkForRequestId.remove(nri.request.requestId); 2390 } 2391 // Maintain the illusion. When this request arrived, we might have pretended 2392 // that a network connected to serve it, even though the network was already 2393 // connected. Now that this request has gone away, we might have to pretend 2394 // that the network disconnected. LegacyTypeTracker will generate that 2395 // phantom disconnect for this type. 2396 if (nri.request.legacyType != TYPE_NONE && nai != null) { 2397 boolean doRemove = true; 2398 if (wasKept) { 2399 // check if any of the remaining requests for this network are for the 2400 // same legacy type - if so, don't remove the nai 2401 for (int i = 0; i < nai.networkRequests.size(); i++) { 2402 NetworkRequest otherRequest = nai.networkRequests.valueAt(i); 2403 if (otherRequest.legacyType == nri.request.legacyType && 2404 isRequest(otherRequest)) { 2405 if (DBG) log(" still have other legacy request - leaving"); 2406 doRemove = false; 2407 } 2408 } 2409 } 2410 2411 if (doRemove) { 2412 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false); 2413 } 2414 } 2415 2416 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 2417 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST, 2418 nri.request); 2419 } 2420 } else { 2421 // listens don't have a singular affectedNetwork. Check all networks to see 2422 // if this listen request applies and remove it. 2423 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2424 nai.networkRequests.remove(nri.request.requestId); 2425 if (nri.request.networkCapabilities.hasSignalStrength() && 2426 nai.satisfiesImmutableCapabilitiesOf(nri.request)) { 2427 updateSignalStrengthThresholds(nai, "RELEASE", nri.request); 2428 } 2429 } 2430 } 2431 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED); 2432 } 2433 } 2434 2435 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) { 2436 enforceConnectivityInternalPermission(); 2437 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED, 2438 accept ? 1 : 0, always ? 1: 0, network)); 2439 } 2440 2441 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) { 2442 if (DBG) log("handleSetAcceptUnvalidated network=" + network + 2443 " accept=" + accept + " always=" + always); 2444 2445 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 2446 if (nai == null) { 2447 // Nothing to do. 2448 return; 2449 } 2450 2451 if (nai.everValidated) { 2452 // The network validated while the dialog box was up. Take no action. 2453 return; 2454 } 2455 2456 if (!nai.networkMisc.explicitlySelected) { 2457 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network"); 2458 } 2459 2460 if (accept != nai.networkMisc.acceptUnvalidated) { 2461 int oldScore = nai.getCurrentScore(); 2462 nai.networkMisc.acceptUnvalidated = accept; 2463 rematchAllNetworksAndRequests(nai, oldScore); 2464 sendUpdatedScoreToFactories(nai); 2465 } 2466 2467 if (always) { 2468 nai.asyncChannel.sendMessage( 2469 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0); 2470 } 2471 2472 if (!accept) { 2473 // Tell the NetworkAgent to not automatically reconnect to the network. 2474 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT); 2475 // Teardown the nework. 2476 teardownUnneededNetwork(nai); 2477 } 2478 2479 } 2480 2481 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) { 2482 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network); 2483 mHandler.sendMessageDelayed( 2484 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network), 2485 PROMPT_UNVALIDATED_DELAY_MS); 2486 } 2487 2488 private void handlePromptUnvalidated(Network network) { 2489 if (VDBG) log("handlePromptUnvalidated " + network); 2490 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 2491 2492 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if 2493 // we haven't already been told to switch to it regardless of whether it validated or not. 2494 // Also don't prompt on captive portals because we're already prompting the user to sign in. 2495 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected || 2496 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) { 2497 return; 2498 } 2499 2500 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED); 2501 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null)); 2502 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 2503 intent.setClassName("com.android.settings", 2504 "com.android.settings.wifi.WifiNoInternetDialog"); 2505 2506 PendingIntent pendingIntent = PendingIntent.getActivityAsUser( 2507 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT); 2508 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET, 2509 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true); 2510 } 2511 2512 private class InternalHandler extends Handler { 2513 public InternalHandler(Looper looper) { 2514 super(looper); 2515 } 2516 2517 @Override 2518 public void handleMessage(Message msg) { 2519 switch (msg.what) { 2520 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK: 2521 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: { 2522 String causedBy = null; 2523 synchronized (ConnectivityService.this) { 2524 if (msg.arg1 == mNetTransitionWakeLockSerialNumber && 2525 mNetTransitionWakeLock.isHeld()) { 2526 mNetTransitionWakeLock.release(); 2527 causedBy = mNetTransitionWakeLockCausedBy; 2528 } else { 2529 break; 2530 } 2531 } 2532 if (VDBG) { 2533 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) { 2534 log("Failed to find a new network - expiring NetTransition Wakelock"); 2535 } else { 2536 log("NetTransition Wakelock (" + 2537 (causedBy == null ? "unknown" : causedBy) + 2538 " cleared because we found a replacement network"); 2539 } 2540 } 2541 break; 2542 } 2543 case EVENT_APPLY_GLOBAL_HTTP_PROXY: { 2544 handleDeprecatedGlobalHttpProxy(); 2545 break; 2546 } 2547 case EVENT_PROXY_HAS_CHANGED: { 2548 handleApplyDefaultProxy((ProxyInfo)msg.obj); 2549 break; 2550 } 2551 case EVENT_REGISTER_NETWORK_FACTORY: { 2552 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj); 2553 break; 2554 } 2555 case EVENT_UNREGISTER_NETWORK_FACTORY: { 2556 handleUnregisterNetworkFactory((Messenger)msg.obj); 2557 break; 2558 } 2559 case EVENT_REGISTER_NETWORK_AGENT: { 2560 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj); 2561 break; 2562 } 2563 case EVENT_REGISTER_NETWORK_REQUEST: 2564 case EVENT_REGISTER_NETWORK_LISTENER: { 2565 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj); 2566 break; 2567 } 2568 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: 2569 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: { 2570 handleRegisterNetworkRequestWithIntent(msg); 2571 break; 2572 } 2573 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: { 2574 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1); 2575 break; 2576 } 2577 case EVENT_RELEASE_NETWORK_REQUEST: { 2578 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1); 2579 break; 2580 } 2581 case EVENT_SET_ACCEPT_UNVALIDATED: { 2582 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0); 2583 break; 2584 } 2585 case EVENT_PROMPT_UNVALIDATED: { 2586 handlePromptUnvalidated((Network) msg.obj); 2587 break; 2588 } 2589 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: { 2590 handleMobileDataAlwaysOn(); 2591 break; 2592 } 2593 // Sent by KeepaliveTracker to process an app request on the state machine thread. 2594 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: { 2595 mKeepaliveTracker.handleStartKeepalive(msg); 2596 break; 2597 } 2598 // Sent by KeepaliveTracker to process an app request on the state machine thread. 2599 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: { 2600 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj); 2601 int slot = msg.arg1; 2602 int reason = msg.arg2; 2603 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason); 2604 break; 2605 } 2606 case EVENT_SYSTEM_READY: { 2607 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2608 nai.networkMonitor.systemReady = true; 2609 } 2610 break; 2611 } 2612 } 2613 } 2614 } 2615 2616 // javadoc from interface 2617 public int tether(String iface) { 2618 ConnectivityManager.enforceTetherChangePermission(mContext); 2619 if (isTetheringSupported()) { 2620 final int status = mTethering.tether(iface); 2621 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) { 2622 try { 2623 mPolicyManager.onTetheringChanged(iface, true); 2624 } catch (RemoteException e) { 2625 } 2626 } 2627 return status; 2628 } else { 2629 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2630 } 2631 } 2632 2633 // javadoc from interface 2634 public int untether(String iface) { 2635 ConnectivityManager.enforceTetherChangePermission(mContext); 2636 2637 if (isTetheringSupported()) { 2638 final int status = mTethering.untether(iface); 2639 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) { 2640 try { 2641 mPolicyManager.onTetheringChanged(iface, false); 2642 } catch (RemoteException e) { 2643 } 2644 } 2645 return status; 2646 } else { 2647 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2648 } 2649 } 2650 2651 // javadoc from interface 2652 public int getLastTetherError(String iface) { 2653 enforceTetherAccessPermission(); 2654 2655 if (isTetheringSupported()) { 2656 return mTethering.getLastTetherError(iface); 2657 } else { 2658 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2659 } 2660 } 2661 2662 // TODO - proper iface API for selection by property, inspection, etc 2663 public String[] getTetherableUsbRegexs() { 2664 enforceTetherAccessPermission(); 2665 if (isTetheringSupported()) { 2666 return mTethering.getTetherableUsbRegexs(); 2667 } else { 2668 return new String[0]; 2669 } 2670 } 2671 2672 public String[] getTetherableWifiRegexs() { 2673 enforceTetherAccessPermission(); 2674 if (isTetheringSupported()) { 2675 return mTethering.getTetherableWifiRegexs(); 2676 } else { 2677 return new String[0]; 2678 } 2679 } 2680 2681 public String[] getTetherableBluetoothRegexs() { 2682 enforceTetherAccessPermission(); 2683 if (isTetheringSupported()) { 2684 return mTethering.getTetherableBluetoothRegexs(); 2685 } else { 2686 return new String[0]; 2687 } 2688 } 2689 2690 public int setUsbTethering(boolean enable) { 2691 ConnectivityManager.enforceTetherChangePermission(mContext); 2692 if (isTetheringSupported()) { 2693 return mTethering.setUsbTethering(enable); 2694 } else { 2695 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2696 } 2697 } 2698 2699 // TODO - move iface listing, queries, etc to new module 2700 // javadoc from interface 2701 public String[] getTetherableIfaces() { 2702 enforceTetherAccessPermission(); 2703 return mTethering.getTetherableIfaces(); 2704 } 2705 2706 public String[] getTetheredIfaces() { 2707 enforceTetherAccessPermission(); 2708 return mTethering.getTetheredIfaces(); 2709 } 2710 2711 public String[] getTetheringErroredIfaces() { 2712 enforceTetherAccessPermission(); 2713 return mTethering.getErroredIfaces(); 2714 } 2715 2716 public String[] getTetheredDhcpRanges() { 2717 enforceConnectivityInternalPermission(); 2718 return mTethering.getTetheredDhcpRanges(); 2719 } 2720 2721 // if ro.tether.denied = true we default to no tethering 2722 // gservices could set the secure setting to 1 though to enable it on a build where it 2723 // had previously been turned off. 2724 @Override 2725 public boolean isTetheringSupported() { 2726 enforceTetherAccessPermission(); 2727 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 2728 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(), 2729 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0) 2730 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING); 2731 return tetherEnabledInSettings && mUserManager.isAdminUser() && 2732 ((mTethering.getTetherableUsbRegexs().length != 0 || 2733 mTethering.getTetherableWifiRegexs().length != 0 || 2734 mTethering.getTetherableBluetoothRegexs().length != 0) && 2735 mTethering.getUpstreamIfaceTypes().length != 0); 2736 } 2737 2738 @Override 2739 public void startTethering(int type, ResultReceiver receiver, 2740 boolean showProvisioningUi) { 2741 ConnectivityManager.enforceTetherChangePermission(mContext); 2742 if (!isTetheringSupported()) { 2743 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null); 2744 return; 2745 } 2746 mTethering.startTethering(type, receiver, showProvisioningUi); 2747 } 2748 2749 @Override 2750 public void stopTethering(int type) { 2751 ConnectivityManager.enforceTetherChangePermission(mContext); 2752 mTethering.stopTethering(type); 2753 } 2754 2755 // Called when we lose the default network and have no replacement yet. 2756 // This will automatically be cleared after X seconds or a new default network 2757 // becomes CONNECTED, whichever happens first. The timer is started by the 2758 // first caller and not restarted by subsequent callers. 2759 private void requestNetworkTransitionWakelock(String forWhom) { 2760 int serialNum = 0; 2761 synchronized (this) { 2762 if (mNetTransitionWakeLock.isHeld()) return; 2763 serialNum = ++mNetTransitionWakeLockSerialNumber; 2764 mNetTransitionWakeLock.acquire(); 2765 mNetTransitionWakeLockCausedBy = forWhom; 2766 } 2767 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2768 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0), 2769 mNetTransitionWakeLockTimeout); 2770 return; 2771 } 2772 2773 // 100 percent is full good, 0 is full bad. 2774 public void reportInetCondition(int networkType, int percentage) { 2775 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 2776 if (nai == null) return; 2777 reportNetworkConnectivity(nai.network, percentage > 50); 2778 } 2779 2780 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) { 2781 enforceAccessPermission(); 2782 enforceInternetPermission(); 2783 2784 NetworkAgentInfo nai; 2785 if (network == null) { 2786 nai = getDefaultNetwork(); 2787 } else { 2788 nai = getNetworkAgentInfoForNetwork(network); 2789 } 2790 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING || 2791 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) { 2792 return; 2793 } 2794 // Revalidate if the app report does not match our current validated state. 2795 if (hasConnectivity == nai.lastValidated) return; 2796 final int uid = Binder.getCallingUid(); 2797 if (DBG) { 2798 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity + 2799 ") by " + uid); 2800 } 2801 synchronized (nai) { 2802 // Validating a network that has not yet connected could result in a call to 2803 // rematchNetworkAndRequests() which is not meant to work on such networks. 2804 if (!nai.everConnected) return; 2805 2806 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return; 2807 2808 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid); 2809 } 2810 } 2811 2812 private ProxyInfo getDefaultProxy() { 2813 // this information is already available as a world read/writable jvm property 2814 // so this API change wouldn't have a benifit. It also breaks the passing 2815 // of proxy info to all the JVMs. 2816 // enforceAccessPermission(); 2817 synchronized (mProxyLock) { 2818 ProxyInfo ret = mGlobalProxy; 2819 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy; 2820 return ret; 2821 } 2822 } 2823 2824 public ProxyInfo getProxyForNetwork(Network network) { 2825 if (network == null) return getDefaultProxy(); 2826 final ProxyInfo globalProxy = getGlobalProxy(); 2827 if (globalProxy != null) return globalProxy; 2828 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null; 2829 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which 2830 // caller may not have. 2831 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 2832 if (nai == null) return null; 2833 synchronized (nai) { 2834 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy(); 2835 if (proxyInfo == null) return null; 2836 return new ProxyInfo(proxyInfo); 2837 } 2838 } 2839 2840 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present 2841 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific 2842 // proxy is null then there is no proxy in place). 2843 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) { 2844 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 2845 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) { 2846 proxy = null; 2847 } 2848 return proxy; 2849 } 2850 2851 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it 2852 // better for determining if a new proxy broadcast is necessary: 2853 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to 2854 // avoid unnecessary broadcasts. 2855 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL 2856 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler) 2857 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but 2858 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port 2859 // all set. 2860 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) { 2861 a = canonicalizeProxyInfo(a); 2862 b = canonicalizeProxyInfo(b); 2863 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check 2864 // hosts even when PAC URLs are present to account for the legacy PAC resolver. 2865 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost())); 2866 } 2867 2868 public void setGlobalProxy(ProxyInfo proxyProperties) { 2869 enforceConnectivityInternalPermission(); 2870 2871 synchronized (mProxyLock) { 2872 if (proxyProperties == mGlobalProxy) return; 2873 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return; 2874 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return; 2875 2876 String host = ""; 2877 int port = 0; 2878 String exclList = ""; 2879 String pacFileUrl = ""; 2880 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) || 2881 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) { 2882 if (!proxyProperties.isValid()) { 2883 if (DBG) 2884 log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 2885 return; 2886 } 2887 mGlobalProxy = new ProxyInfo(proxyProperties); 2888 host = mGlobalProxy.getHost(); 2889 port = mGlobalProxy.getPort(); 2890 exclList = mGlobalProxy.getExclusionListAsString(); 2891 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) { 2892 pacFileUrl = proxyProperties.getPacFileUrl().toString(); 2893 } 2894 } else { 2895 mGlobalProxy = null; 2896 } 2897 ContentResolver res = mContext.getContentResolver(); 2898 final long token = Binder.clearCallingIdentity(); 2899 try { 2900 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host); 2901 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port); 2902 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 2903 exclList); 2904 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl); 2905 } finally { 2906 Binder.restoreCallingIdentity(token); 2907 } 2908 2909 if (mGlobalProxy == null) { 2910 proxyProperties = mDefaultProxy; 2911 } 2912 sendProxyBroadcast(proxyProperties); 2913 } 2914 } 2915 2916 private void loadGlobalProxy() { 2917 ContentResolver res = mContext.getContentResolver(); 2918 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST); 2919 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0); 2920 String exclList = Settings.Global.getString(res, 2921 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST); 2922 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC); 2923 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) { 2924 ProxyInfo proxyProperties; 2925 if (!TextUtils.isEmpty(pacFileUrl)) { 2926 proxyProperties = new ProxyInfo(pacFileUrl); 2927 } else { 2928 proxyProperties = new ProxyInfo(host, port, exclList); 2929 } 2930 if (!proxyProperties.isValid()) { 2931 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 2932 return; 2933 } 2934 2935 synchronized (mProxyLock) { 2936 mGlobalProxy = proxyProperties; 2937 } 2938 } 2939 } 2940 2941 public ProxyInfo getGlobalProxy() { 2942 // this information is already available as a world read/writable jvm property 2943 // so this API change wouldn't have a benifit. It also breaks the passing 2944 // of proxy info to all the JVMs. 2945 // enforceAccessPermission(); 2946 synchronized (mProxyLock) { 2947 return mGlobalProxy; 2948 } 2949 } 2950 2951 private void handleApplyDefaultProxy(ProxyInfo proxy) { 2952 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 2953 && Uri.EMPTY.equals(proxy.getPacFileUrl())) { 2954 proxy = null; 2955 } 2956 synchronized (mProxyLock) { 2957 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return; 2958 if (mDefaultProxy == proxy) return; // catches repeated nulls 2959 if (proxy != null && !proxy.isValid()) { 2960 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString()); 2961 return; 2962 } 2963 2964 // This call could be coming from the PacManager, containing the port of the local 2965 // proxy. If this new proxy matches the global proxy then copy this proxy to the 2966 // global (to get the correct local port), and send a broadcast. 2967 // TODO: Switch PacManager to have its own message to send back rather than 2968 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy. 2969 if ((mGlobalProxy != null) && (proxy != null) 2970 && (!Uri.EMPTY.equals(proxy.getPacFileUrl())) 2971 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) { 2972 mGlobalProxy = proxy; 2973 sendProxyBroadcast(mGlobalProxy); 2974 return; 2975 } 2976 mDefaultProxy = proxy; 2977 2978 if (mGlobalProxy != null) return; 2979 if (!mDefaultProxyDisabled) { 2980 sendProxyBroadcast(proxy); 2981 } 2982 } 2983 } 2984 2985 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy. 2986 // This method gets called when any network changes proxy, but the broadcast only ever contains 2987 // the default proxy (even if it hasn't changed). 2988 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network 2989 // world where an app might be bound to a non-default network. 2990 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) { 2991 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy(); 2992 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy(); 2993 2994 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) { 2995 sendProxyBroadcast(getDefaultProxy()); 2996 } 2997 } 2998 2999 private void handleDeprecatedGlobalHttpProxy() { 3000 String proxy = Settings.Global.getString(mContext.getContentResolver(), 3001 Settings.Global.HTTP_PROXY); 3002 if (!TextUtils.isEmpty(proxy)) { 3003 String data[] = proxy.split(":"); 3004 if (data.length == 0) { 3005 return; 3006 } 3007 3008 String proxyHost = data[0]; 3009 int proxyPort = 8080; 3010 if (data.length > 1) { 3011 try { 3012 proxyPort = Integer.parseInt(data[1]); 3013 } catch (NumberFormatException e) { 3014 return; 3015 } 3016 } 3017 ProxyInfo p = new ProxyInfo(data[0], proxyPort, ""); 3018 setGlobalProxy(p); 3019 } 3020 } 3021 3022 private void sendProxyBroadcast(ProxyInfo proxy) { 3023 if (proxy == null) proxy = new ProxyInfo("", 0, ""); 3024 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return; 3025 if (DBG) log("sending Proxy Broadcast for " + proxy); 3026 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); 3027 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 3028 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3029 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy); 3030 final long ident = Binder.clearCallingIdentity(); 3031 try { 3032 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 3033 } finally { 3034 Binder.restoreCallingIdentity(ident); 3035 } 3036 } 3037 3038 private static class SettingsObserver extends ContentObserver { 3039 final private HashMap<Uri, Integer> mUriEventMap; 3040 final private Context mContext; 3041 final private Handler mHandler; 3042 3043 SettingsObserver(Context context, Handler handler) { 3044 super(null); 3045 mUriEventMap = new HashMap<Uri, Integer>(); 3046 mContext = context; 3047 mHandler = handler; 3048 } 3049 3050 void observe(Uri uri, int what) { 3051 mUriEventMap.put(uri, what); 3052 final ContentResolver resolver = mContext.getContentResolver(); 3053 resolver.registerContentObserver(uri, false, this); 3054 } 3055 3056 @Override 3057 public void onChange(boolean selfChange) { 3058 Slog.wtf(TAG, "Should never be reached."); 3059 } 3060 3061 @Override 3062 public void onChange(boolean selfChange, Uri uri) { 3063 final Integer what = mUriEventMap.get(uri); 3064 if (what != null) { 3065 mHandler.obtainMessage(what.intValue()).sendToTarget(); 3066 } else { 3067 loge("No matching event to send for URI=" + uri); 3068 } 3069 } 3070 } 3071 3072 private static void log(String s) { 3073 Slog.d(TAG, s); 3074 } 3075 3076 private static void loge(String s) { 3077 Slog.e(TAG, s); 3078 } 3079 3080 private static <T> T checkNotNull(T value, String message) { 3081 if (value == null) { 3082 throw new NullPointerException(message); 3083 } 3084 return value; 3085 } 3086 3087 /** 3088 * Prepare for a VPN application. 3089 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId}, 3090 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required. 3091 * 3092 * @param oldPackage Package name of the application which currently controls VPN, which will 3093 * be replaced. If there is no such application, this should should either be 3094 * {@code null} or {@link VpnConfig.LEGACY_VPN}. 3095 * @param newPackage Package name of the application which should gain control of VPN, or 3096 * {@code null} to disable. 3097 * @param userId User for whom to prepare the new VPN. 3098 * 3099 * @hide 3100 */ 3101 @Override 3102 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage, 3103 int userId) { 3104 enforceCrossUserPermission(userId); 3105 throwIfLockdownEnabled(); 3106 3107 synchronized(mVpns) { 3108 Vpn vpn = mVpns.get(userId); 3109 if (vpn != null) { 3110 return vpn.prepare(oldPackage, newPackage); 3111 } else { 3112 return false; 3113 } 3114 } 3115 } 3116 3117 /** 3118 * Set whether the VPN package has the ability to launch VPNs without user intervention. 3119 * This method is used by system-privileged apps. 3120 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId}, 3121 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required. 3122 * 3123 * @param packageName The package for which authorization state should change. 3124 * @param userId User for whom {@code packageName} is installed. 3125 * @param authorized {@code true} if this app should be able to start a VPN connection without 3126 * explicit user approval, {@code false} if not. 3127 * 3128 * @hide 3129 */ 3130 @Override 3131 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) { 3132 enforceCrossUserPermission(userId); 3133 3134 synchronized(mVpns) { 3135 Vpn vpn = mVpns.get(userId); 3136 if (vpn != null) { 3137 vpn.setPackageAuthorization(packageName, authorized); 3138 } 3139 } 3140 } 3141 3142 /** 3143 * Configure a TUN interface and return its file descriptor. Parameters 3144 * are encoded and opaque to this class. This method is used by VpnBuilder 3145 * and not available in ConnectivityManager. Permissions are checked in 3146 * Vpn class. 3147 * @hide 3148 */ 3149 @Override 3150 public ParcelFileDescriptor establishVpn(VpnConfig config) { 3151 throwIfLockdownEnabled(); 3152 int user = UserHandle.getUserId(Binder.getCallingUid()); 3153 synchronized(mVpns) { 3154 return mVpns.get(user).establish(config); 3155 } 3156 } 3157 3158 /** 3159 * Start legacy VPN, controlling native daemons as needed. Creates a 3160 * secondary thread to perform connection work, returning quickly. 3161 */ 3162 @Override 3163 public void startLegacyVpn(VpnProfile profile) { 3164 throwIfLockdownEnabled(); 3165 final LinkProperties egress = getActiveLinkProperties(); 3166 if (egress == null) { 3167 throw new IllegalStateException("Missing active network connection"); 3168 } 3169 int user = UserHandle.getUserId(Binder.getCallingUid()); 3170 synchronized(mVpns) { 3171 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress); 3172 } 3173 } 3174 3175 /** 3176 * Return the information of the ongoing legacy VPN. This method is used 3177 * by VpnSettings and not available in ConnectivityManager. Permissions 3178 * are checked in Vpn class. 3179 */ 3180 @Override 3181 public LegacyVpnInfo getLegacyVpnInfo(int userId) { 3182 enforceCrossUserPermission(userId); 3183 if (mLockdownEnabled) { 3184 return null; 3185 } 3186 3187 synchronized(mVpns) { 3188 return mVpns.get(userId).getLegacyVpnInfo(); 3189 } 3190 } 3191 3192 /** 3193 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService 3194 * and not available in ConnectivityManager. 3195 */ 3196 @Override 3197 public VpnInfo[] getAllVpnInfo() { 3198 enforceConnectivityInternalPermission(); 3199 if (mLockdownEnabled) { 3200 return new VpnInfo[0]; 3201 } 3202 3203 synchronized(mVpns) { 3204 List<VpnInfo> infoList = new ArrayList<>(); 3205 for (int i = 0; i < mVpns.size(); i++) { 3206 VpnInfo info = createVpnInfo(mVpns.valueAt(i)); 3207 if (info != null) { 3208 infoList.add(info); 3209 } 3210 } 3211 return infoList.toArray(new VpnInfo[infoList.size()]); 3212 } 3213 } 3214 3215 /** 3216 * @return VPN information for accounting, or null if we can't retrieve all required 3217 * information, e.g primary underlying iface. 3218 */ 3219 @Nullable 3220 private VpnInfo createVpnInfo(Vpn vpn) { 3221 VpnInfo info = vpn.getVpnInfo(); 3222 if (info == null) { 3223 return null; 3224 } 3225 Network[] underlyingNetworks = vpn.getUnderlyingNetworks(); 3226 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret 3227 // the underlyingNetworks list. 3228 if (underlyingNetworks == null) { 3229 NetworkAgentInfo defaultNetwork = getDefaultNetwork(); 3230 if (defaultNetwork != null && defaultNetwork.linkProperties != null) { 3231 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName(); 3232 } 3233 } else if (underlyingNetworks.length > 0) { 3234 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]); 3235 if (linkProperties != null) { 3236 info.primaryUnderlyingIface = linkProperties.getInterfaceName(); 3237 } 3238 } 3239 return info.primaryUnderlyingIface == null ? null : info; 3240 } 3241 3242 /** 3243 * Returns the information of the ongoing VPN for {@code userId}. This method is used by 3244 * VpnDialogs and not available in ConnectivityManager. 3245 * Permissions are checked in Vpn class. 3246 * @hide 3247 */ 3248 @Override 3249 public VpnConfig getVpnConfig(int userId) { 3250 enforceCrossUserPermission(userId); 3251 synchronized(mVpns) { 3252 Vpn vpn = mVpns.get(userId); 3253 if (vpn != null) { 3254 return vpn.getVpnConfig(); 3255 } else { 3256 return null; 3257 } 3258 } 3259 } 3260 3261 @Override 3262 public boolean updateLockdownVpn() { 3263 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 3264 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM"); 3265 return false; 3266 } 3267 3268 // Tear down existing lockdown if profile was removed 3269 mLockdownEnabled = LockdownVpnTracker.isEnabled(); 3270 if (mLockdownEnabled) { 3271 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN)); 3272 final VpnProfile profile = VpnProfile.decode( 3273 profileName, mKeyStore.get(Credentials.VPN + profileName)); 3274 if (profile == null) { 3275 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName); 3276 setLockdownTracker(null); 3277 return true; 3278 } 3279 int user = UserHandle.getUserId(Binder.getCallingUid()); 3280 synchronized(mVpns) { 3281 Vpn vpn = mVpns.get(user); 3282 if (vpn == null) { 3283 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown"); 3284 return false; 3285 } 3286 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile)); 3287 } 3288 } else { 3289 setLockdownTracker(null); 3290 } 3291 3292 return true; 3293 } 3294 3295 /** 3296 * Internally set new {@link LockdownVpnTracker}, shutting down any existing 3297 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown. 3298 */ 3299 private void setLockdownTracker(LockdownVpnTracker tracker) { 3300 // Shutdown any existing tracker 3301 final LockdownVpnTracker existing = mLockdownTracker; 3302 mLockdownTracker = null; 3303 if (existing != null) { 3304 existing.shutdown(); 3305 } 3306 3307 try { 3308 if (tracker != null) { 3309 mNetd.setFirewallEnabled(true); 3310 mNetd.setFirewallInterfaceRule("lo", true); 3311 mLockdownTracker = tracker; 3312 mLockdownTracker.init(); 3313 } else { 3314 mNetd.setFirewallEnabled(false); 3315 } 3316 } catch (RemoteException e) { 3317 // ignored; NMS lives inside system_server 3318 } 3319 } 3320 3321 private void throwIfLockdownEnabled() { 3322 if (mLockdownEnabled) { 3323 throw new IllegalStateException("Unavailable in lockdown mode"); 3324 } 3325 } 3326 3327 /** 3328 * Sets up or tears down the always-on VPN for user {@param user} as appropriate. 3329 * 3330 * @return {@code false} in case of errors; {@code true} otherwise. 3331 */ 3332 private boolean updateAlwaysOnVpn(int user) { 3333 final String lockdownPackage = getAlwaysOnVpnPackage(user); 3334 if (lockdownPackage == null) { 3335 return true; 3336 } 3337 3338 // Create an intent to start the VPN service declared in the app's manifest. 3339 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE); 3340 serviceIntent.setPackage(lockdownPackage); 3341 3342 try { 3343 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null; 3344 } catch (RuntimeException e) { 3345 return false; 3346 } 3347 } 3348 3349 @Override 3350 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) { 3351 enforceConnectivityInternalPermission(); 3352 enforceCrossUserPermission(userId); 3353 3354 // Can't set always-on VPN if legacy VPN is already in lockdown mode. 3355 if (LockdownVpnTracker.isEnabled()) { 3356 return false; 3357 } 3358 3359 // If the current VPN package is the same as the new one, this is a no-op 3360 final String oldPackage = getAlwaysOnVpnPackage(userId); 3361 if (TextUtils.equals(oldPackage, packageName)) { 3362 return true; 3363 } 3364 3365 synchronized (mVpns) { 3366 Vpn vpn = mVpns.get(userId); 3367 if (vpn == null) { 3368 Slog.w(TAG, "User " + userId + " has no Vpn configuration"); 3369 return false; 3370 } 3371 if (!vpn.setAlwaysOnPackage(packageName)) { 3372 return false; 3373 } 3374 if (!updateAlwaysOnVpn(userId)) { 3375 vpn.setAlwaysOnPackage(null); 3376 return false; 3377 } 3378 } 3379 return true; 3380 } 3381 3382 @Override 3383 public String getAlwaysOnVpnPackage(int userId) { 3384 enforceConnectivityInternalPermission(); 3385 enforceCrossUserPermission(userId); 3386 3387 synchronized (mVpns) { 3388 Vpn vpn = mVpns.get(userId); 3389 if (vpn == null) { 3390 Slog.w(TAG, "User " + userId + " has no Vpn configuration"); 3391 return null; 3392 } 3393 return vpn.getAlwaysOnPackage(); 3394 } 3395 } 3396 3397 @Override 3398 public int checkMobileProvisioning(int suggestedTimeOutMs) { 3399 // TODO: Remove? Any reason to trigger a provisioning check? 3400 return -1; 3401 } 3402 3403 private static final String NOTIFICATION_ID = "CaptivePortal.Notification"; 3404 private static enum NotificationType { SIGN_IN, NO_INTERNET; }; 3405 3406 private void setProvNotificationVisible(boolean visible, int networkType, String action) { 3407 Intent intent = new Intent(action); 3408 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); 3409 // Concatenate the range of types onto the range of NetIDs. 3410 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE); 3411 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN, 3412 networkType, null, pendingIntent, false); 3413 } 3414 3415 /** 3416 * Show or hide network provisioning notifications. 3417 * 3418 * We use notifications for two purposes: to notify that a network requires sign in 3419 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access 3420 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a 3421 * particular network we can display the notification type that was most recently requested. 3422 * So for example if a captive portal fails to reply within a few seconds of connecting, we 3423 * might first display NO_INTERNET, and then when the captive portal check completes, display 3424 * SIGN_IN. 3425 * 3426 * @param id an identifier that uniquely identifies this notification. This must match 3427 * between show and hide calls. We use the NetID value but for legacy callers 3428 * we concatenate the range of types with the range of NetIDs. 3429 */ 3430 private void setProvNotificationVisibleIntent(boolean visible, int id, 3431 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent, 3432 boolean highPriority) { 3433 if (VDBG || (DBG && visible)) { 3434 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible 3435 + " networkType=" + getNetworkTypeName(networkType) 3436 + " extraInfo=" + extraInfo + " highPriority=" + highPriority); 3437 } 3438 3439 Resources r = Resources.getSystem(); 3440 NotificationManager notificationManager = (NotificationManager) mContext 3441 .getSystemService(Context.NOTIFICATION_SERVICE); 3442 3443 if (visible) { 3444 CharSequence title; 3445 CharSequence details; 3446 int icon; 3447 if (notifyType == NotificationType.NO_INTERNET && 3448 networkType == ConnectivityManager.TYPE_WIFI) { 3449 title = r.getString(R.string.wifi_no_internet, 0); 3450 details = r.getString(R.string.wifi_no_internet_detailed); 3451 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon. 3452 } else if (notifyType == NotificationType.SIGN_IN) { 3453 switch (networkType) { 3454 case ConnectivityManager.TYPE_WIFI: 3455 title = r.getString(R.string.wifi_available_sign_in, 0); 3456 details = r.getString(R.string.network_available_sign_in_detailed, 3457 extraInfo); 3458 icon = R.drawable.stat_notify_wifi_in_range; 3459 break; 3460 case ConnectivityManager.TYPE_MOBILE: 3461 case ConnectivityManager.TYPE_MOBILE_HIPRI: 3462 title = r.getString(R.string.network_available_sign_in, 0); 3463 // TODO: Change this to pull from NetworkInfo once a printable 3464 // name has been added to it 3465 details = mTelephonyManager.getNetworkOperatorName(); 3466 icon = R.drawable.stat_notify_rssi_in_range; 3467 break; 3468 default: 3469 title = r.getString(R.string.network_available_sign_in, 0); 3470 details = r.getString(R.string.network_available_sign_in_detailed, 3471 extraInfo); 3472 icon = R.drawable.stat_notify_rssi_in_range; 3473 break; 3474 } 3475 } else { 3476 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type " 3477 + getNetworkTypeName(networkType)); 3478 return; 3479 } 3480 3481 Notification notification = new Notification.Builder(mContext) 3482 .setWhen(0) 3483 .setSmallIcon(icon) 3484 .setAutoCancel(true) 3485 .setTicker(title) 3486 .setColor(mContext.getColor( 3487 com.android.internal.R.color.system_notification_accent_color)) 3488 .setContentTitle(title) 3489 .setContentText(details) 3490 .setContentIntent(intent) 3491 .setLocalOnly(true) 3492 .setPriority(highPriority ? 3493 Notification.PRIORITY_HIGH : 3494 Notification.PRIORITY_DEFAULT) 3495 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0) 3496 .setOnlyAlertOnce(true) 3497 .build(); 3498 3499 try { 3500 notificationManager.notify(NOTIFICATION_ID, id, notification); 3501 } catch (NullPointerException npe) { 3502 loge("setNotificationVisible: visible notificationManager npe=" + npe); 3503 npe.printStackTrace(); 3504 } 3505 } else { 3506 try { 3507 notificationManager.cancel(NOTIFICATION_ID, id); 3508 } catch (NullPointerException npe) { 3509 loge("setNotificationVisible: cancel notificationManager npe=" + npe); 3510 npe.printStackTrace(); 3511 } 3512 } 3513 } 3514 3515 /** Location to an updatable file listing carrier provisioning urls. 3516 * An example: 3517 * 3518 * <?xml version="1.0" encoding="utf-8"?> 3519 * <provisioningUrls> 3520 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl> 3521 * </provisioningUrls> 3522 */ 3523 private static final String PROVISIONING_URL_PATH = 3524 "/data/misc/radio/provisioning_urls.xml"; 3525 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH); 3526 3527 /** XML tag for root element. */ 3528 private static final String TAG_PROVISIONING_URLS = "provisioningUrls"; 3529 /** XML tag for individual url */ 3530 private static final String TAG_PROVISIONING_URL = "provisioningUrl"; 3531 /** XML attribute for mcc */ 3532 private static final String ATTR_MCC = "mcc"; 3533 /** XML attribute for mnc */ 3534 private static final String ATTR_MNC = "mnc"; 3535 3536 private String getProvisioningUrlBaseFromFile() { 3537 FileReader fileReader = null; 3538 XmlPullParser parser = null; 3539 Configuration config = mContext.getResources().getConfiguration(); 3540 3541 try { 3542 fileReader = new FileReader(mProvisioningUrlFile); 3543 parser = Xml.newPullParser(); 3544 parser.setInput(fileReader); 3545 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS); 3546 3547 while (true) { 3548 XmlUtils.nextElement(parser); 3549 3550 String element = parser.getName(); 3551 if (element == null) break; 3552 3553 if (element.equals(TAG_PROVISIONING_URL)) { 3554 String mcc = parser.getAttributeValue(null, ATTR_MCC); 3555 try { 3556 if (mcc != null && Integer.parseInt(mcc) == config.mcc) { 3557 String mnc = parser.getAttributeValue(null, ATTR_MNC); 3558 if (mnc != null && Integer.parseInt(mnc) == config.mnc) { 3559 parser.next(); 3560 if (parser.getEventType() == XmlPullParser.TEXT) { 3561 return parser.getText(); 3562 } 3563 } 3564 } 3565 } catch (NumberFormatException e) { 3566 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e); 3567 } 3568 } 3569 } 3570 return null; 3571 } catch (FileNotFoundException e) { 3572 loge("Carrier Provisioning Urls file not found"); 3573 } catch (XmlPullParserException e) { 3574 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e); 3575 } catch (IOException e) { 3576 loge("I/O exception reading Carrier Provisioning Urls file: " + e); 3577 } finally { 3578 if (fileReader != null) { 3579 try { 3580 fileReader.close(); 3581 } catch (IOException e) {} 3582 } 3583 } 3584 return null; 3585 } 3586 3587 @Override 3588 public String getMobileProvisioningUrl() { 3589 enforceConnectivityInternalPermission(); 3590 String url = getProvisioningUrlBaseFromFile(); 3591 if (TextUtils.isEmpty(url)) { 3592 url = mContext.getResources().getString(R.string.mobile_provisioning_url); 3593 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url); 3594 } else { 3595 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url); 3596 } 3597 // populate the iccid, imei and phone number in the provisioning url. 3598 if (!TextUtils.isEmpty(url)) { 3599 String phoneNumber = mTelephonyManager.getLine1Number(); 3600 if (TextUtils.isEmpty(phoneNumber)) { 3601 phoneNumber = "0000000000"; 3602 } 3603 url = String.format(url, 3604 mTelephonyManager.getSimSerialNumber() /* ICCID */, 3605 mTelephonyManager.getDeviceId() /* IMEI */, 3606 phoneNumber /* Phone numer */); 3607 } 3608 3609 return url; 3610 } 3611 3612 @Override 3613 public void setProvisioningNotificationVisible(boolean visible, int networkType, 3614 String action) { 3615 enforceConnectivityInternalPermission(); 3616 final long ident = Binder.clearCallingIdentity(); 3617 try { 3618 setProvNotificationVisible(visible, networkType, action); 3619 } finally { 3620 Binder.restoreCallingIdentity(ident); 3621 } 3622 } 3623 3624 @Override 3625 public void setAirplaneMode(boolean enable) { 3626 enforceConnectivityInternalPermission(); 3627 final long ident = Binder.clearCallingIdentity(); 3628 try { 3629 final ContentResolver cr = mContext.getContentResolver(); 3630 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 3631 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 3632 intent.putExtra("state", enable); 3633 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 3634 } finally { 3635 Binder.restoreCallingIdentity(ident); 3636 } 3637 } 3638 3639 private void onUserStart(int userId) { 3640 synchronized(mVpns) { 3641 Vpn userVpn = mVpns.get(userId); 3642 if (userVpn != null) { 3643 loge("Starting user already has a VPN"); 3644 return; 3645 } 3646 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); 3647 mVpns.put(userId, userVpn); 3648 } 3649 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) { 3650 updateLockdownVpn(); 3651 } else { 3652 updateAlwaysOnVpn(userId); 3653 } 3654 } 3655 3656 private void onUserStop(int userId) { 3657 synchronized(mVpns) { 3658 Vpn userVpn = mVpns.get(userId); 3659 if (userVpn == null) { 3660 loge("Stopped user has no VPN"); 3661 return; 3662 } 3663 mVpns.delete(userId); 3664 } 3665 } 3666 3667 private void onUserAdded(int userId) { 3668 synchronized(mVpns) { 3669 final int vpnsSize = mVpns.size(); 3670 for (int i = 0; i < vpnsSize; i++) { 3671 Vpn vpn = mVpns.valueAt(i); 3672 vpn.onUserAdded(userId); 3673 } 3674 } 3675 } 3676 3677 private void onUserRemoved(int userId) { 3678 synchronized(mVpns) { 3679 final int vpnsSize = mVpns.size(); 3680 for (int i = 0; i < vpnsSize; i++) { 3681 Vpn vpn = mVpns.valueAt(i); 3682 vpn.onUserRemoved(userId); 3683 } 3684 } 3685 } 3686 3687 private void onUserUnlocked(int userId) { 3688 // User present may be sent because of an unlock, which might mean an unlocked keystore. 3689 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) { 3690 updateLockdownVpn(); 3691 } else { 3692 updateAlwaysOnVpn(userId); 3693 } 3694 } 3695 3696 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() { 3697 @Override 3698 public void onReceive(Context context, Intent intent) { 3699 final String action = intent.getAction(); 3700 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 3701 if (userId == UserHandle.USER_NULL) return; 3702 3703 if (Intent.ACTION_USER_STARTED.equals(action)) { 3704 onUserStart(userId); 3705 } else if (Intent.ACTION_USER_STOPPED.equals(action)) { 3706 onUserStop(userId); 3707 } else if (Intent.ACTION_USER_ADDED.equals(action)) { 3708 onUserAdded(userId); 3709 } else if (Intent.ACTION_USER_REMOVED.equals(action)) { 3710 onUserRemoved(userId); 3711 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) { 3712 onUserUnlocked(userId); 3713 } 3714 } 3715 }; 3716 3717 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = 3718 new HashMap<Messenger, NetworkFactoryInfo>(); 3719 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = 3720 new HashMap<NetworkRequest, NetworkRequestInfo>(); 3721 3722 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100; 3723 // Map from UID to number of NetworkRequests that UID has filed. 3724 @GuardedBy("mUidToNetworkRequestCount") 3725 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray(); 3726 3727 private static class NetworkFactoryInfo { 3728 public final String name; 3729 public final Messenger messenger; 3730 public final AsyncChannel asyncChannel; 3731 3732 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) { 3733 this.name = name; 3734 this.messenger = messenger; 3735 this.asyncChannel = asyncChannel; 3736 } 3737 } 3738 3739 /** 3740 * A NetworkRequest as registered by an application can be one of three 3741 * types: 3742 * 3743 * - "listen", for which the framework will issue callbacks about any 3744 * and all networks that match the specified NetworkCapabilities, 3745 * 3746 * - "request", capable of causing a specific network to be created 3747 * first (e.g. a telephony DUN request), the framework will issue 3748 * callbacks about the single, highest scoring current network 3749 * (if any) that matches the specified NetworkCapabilities, or 3750 * 3751 * - "track the default network", a hybrid of the two designed such 3752 * that the framework will issue callbacks for the single, highest 3753 * scoring current network (if any) that matches the capabilities of 3754 * the default Internet request (mDefaultRequest), but which cannot 3755 * cause the framework to either create or retain the existence of 3756 * any specific network. 3757 * 3758 */ 3759 private static enum NetworkRequestType { 3760 LISTEN, 3761 TRACK_DEFAULT, 3762 REQUEST 3763 }; 3764 3765 /** 3766 * Tracks info about the requester. 3767 * Also used to notice when the calling process dies so we can self-expire 3768 */ 3769 private class NetworkRequestInfo implements IBinder.DeathRecipient { 3770 final NetworkRequest request; 3771 final PendingIntent mPendingIntent; 3772 boolean mPendingIntentSent; 3773 private final IBinder mBinder; 3774 final int mPid; 3775 final int mUid; 3776 final Messenger messenger; 3777 private final NetworkRequestType mType; 3778 3779 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) { 3780 request = r; 3781 mPendingIntent = pi; 3782 messenger = null; 3783 mBinder = null; 3784 mPid = getCallingPid(); 3785 mUid = getCallingUid(); 3786 mType = type; 3787 enforceRequestCountLimit(); 3788 } 3789 3790 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) { 3791 super(); 3792 messenger = m; 3793 request = r; 3794 mBinder = binder; 3795 mPid = getCallingPid(); 3796 mUid = getCallingUid(); 3797 mType = type; 3798 mPendingIntent = null; 3799 enforceRequestCountLimit(); 3800 3801 try { 3802 mBinder.linkToDeath(this, 0); 3803 } catch (RemoteException e) { 3804 binderDied(); 3805 } 3806 } 3807 3808 private void enforceRequestCountLimit() { 3809 synchronized (mUidToNetworkRequestCount) { 3810 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1; 3811 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) { 3812 throw new IllegalArgumentException("Too many NetworkRequests filed"); 3813 } 3814 mUidToNetworkRequestCount.put(mUid, networkRequests); 3815 } 3816 } 3817 3818 private String typeString() { 3819 switch (mType) { 3820 case LISTEN: return "Listen"; 3821 case REQUEST: return "Request"; 3822 case TRACK_DEFAULT: return "Track default"; 3823 default: 3824 return "unknown type"; 3825 } 3826 } 3827 3828 void unlinkDeathRecipient() { 3829 if (mBinder != null) { 3830 mBinder.unlinkToDeath(this, 0); 3831 } 3832 } 3833 3834 public void binderDied() { 3835 log("ConnectivityService NetworkRequestInfo binderDied(" + 3836 request + ", " + mBinder + ")"); 3837 releaseNetworkRequest(request); 3838 } 3839 3840 /** 3841 * Returns true iff. the contained NetworkRequest is one that: 3842 * 3843 * - should be associated with at most one satisfying network 3844 * at a time; 3845 * 3846 * - should cause a network to be kept up if it is the only network 3847 * which can satisfy the NetworkReqeust. 3848 * 3849 * For full detail of how isRequest() is used for pairing Networks with 3850 * NetworkRequests read rematchNetworkAndRequests(). 3851 * 3852 * TODO: Rename to something more properly descriptive. 3853 */ 3854 public boolean isRequest() { 3855 return (mType == NetworkRequestType.TRACK_DEFAULT) || 3856 (mType == NetworkRequestType.REQUEST); 3857 } 3858 3859 public String toString() { 3860 return typeString() + 3861 " from uid/pid:" + mUid + "/" + mPid + 3862 " for " + request + 3863 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent); 3864 } 3865 } 3866 3867 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) { 3868 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability(); 3869 if (badCapability != null) { 3870 throw new IllegalArgumentException("Cannot request network with " + badCapability); 3871 } 3872 } 3873 3874 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) { 3875 final SortedSet<Integer> thresholds = new TreeSet(); 3876 synchronized (nai) { 3877 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 3878 if (nri.request.networkCapabilities.hasSignalStrength() && 3879 nai.satisfiesImmutableCapabilitiesOf(nri.request)) { 3880 thresholds.add(nri.request.networkCapabilities.getSignalStrength()); 3881 } 3882 } 3883 } 3884 return new ArrayList<Integer>(thresholds); 3885 } 3886 3887 private void updateSignalStrengthThresholds( 3888 NetworkAgentInfo nai, String reason, NetworkRequest request) { 3889 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai); 3890 Bundle thresholds = new Bundle(); 3891 thresholds.putIntegerArrayList("thresholds", thresholdsArray); 3892 3893 if (VDBG || (DBG && !"CONNECT".equals(reason))) { 3894 String detail; 3895 if (request != null && request.networkCapabilities.hasSignalStrength()) { 3896 detail = reason + " " + request.networkCapabilities.getSignalStrength(); 3897 } else { 3898 detail = reason; 3899 } 3900 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s", 3901 detail, Arrays.toString(thresholdsArray.toArray()), nai.name())); 3902 } 3903 3904 nai.asyncChannel.sendMessage( 3905 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS, 3906 0, 0, thresholds); 3907 } 3908 3909 @Override 3910 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities, 3911 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) { 3912 final NetworkRequestType type = (networkCapabilities == null) 3913 ? NetworkRequestType.TRACK_DEFAULT 3914 : NetworkRequestType.REQUEST; 3915 // If the requested networkCapabilities is null, take them instead from 3916 // the default network request. This allows callers to keep track of 3917 // the system default network. 3918 if (type == NetworkRequestType.TRACK_DEFAULT) { 3919 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities); 3920 enforceAccessPermission(); 3921 } else { 3922 networkCapabilities = new NetworkCapabilities(networkCapabilities); 3923 enforceNetworkRequestPermissions(networkCapabilities); 3924 } 3925 enforceMeteredApnPolicy(networkCapabilities); 3926 ensureRequestableCapabilities(networkCapabilities); 3927 3928 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) { 3929 throw new IllegalArgumentException("Bad timeout specified"); 3930 } 3931 3932 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER 3933 .equals(networkCapabilities.getNetworkSpecifier())) { 3934 throw new IllegalArgumentException("Invalid network specifier - must not be '" 3935 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'"); 3936 } 3937 3938 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType, 3939 nextNetworkRequestId()); 3940 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type); 3941 if (DBG) log("requestNetwork for " + nri); 3942 3943 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri)); 3944 if (timeoutMs > 0) { 3945 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST, 3946 nri), timeoutMs); 3947 } 3948 return networkRequest; 3949 } 3950 3951 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) { 3952 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) { 3953 enforceConnectivityInternalPermission(); 3954 } else { 3955 enforceChangePermission(); 3956 } 3957 } 3958 3959 @Override 3960 public boolean requestBandwidthUpdate(Network network) { 3961 enforceAccessPermission(); 3962 NetworkAgentInfo nai = null; 3963 if (network == null) { 3964 return false; 3965 } 3966 synchronized (mNetworkForNetId) { 3967 nai = mNetworkForNetId.get(network.netId); 3968 } 3969 if (nai != null) { 3970 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE); 3971 return true; 3972 } 3973 return false; 3974 } 3975 3976 3977 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) { 3978 // if UID is restricted, don't allow them to bring up metered APNs 3979 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) { 3980 final int uidRules; 3981 final int uid = Binder.getCallingUid(); 3982 synchronized(mRulesLock) { 3983 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL); 3984 } 3985 if (uidRules != RULE_ALLOW_ALL) { 3986 // we could silently fail or we can filter the available nets to only give 3987 // them those they have access to. Chose the more useful 3988 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED); 3989 } 3990 } 3991 } 3992 3993 @Override 3994 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities, 3995 PendingIntent operation) { 3996 checkNotNull(operation, "PendingIntent cannot be null."); 3997 networkCapabilities = new NetworkCapabilities(networkCapabilities); 3998 enforceNetworkRequestPermissions(networkCapabilities); 3999 enforceMeteredApnPolicy(networkCapabilities); 4000 ensureRequestableCapabilities(networkCapabilities); 4001 4002 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE, 4003 nextNetworkRequestId()); 4004 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation, 4005 NetworkRequestType.REQUEST); 4006 if (DBG) log("pendingRequest for " + nri); 4007 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT, 4008 nri)); 4009 return networkRequest; 4010 } 4011 4012 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) { 4013 mHandler.sendMessageDelayed( 4014 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, 4015 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs); 4016 } 4017 4018 @Override 4019 public void releasePendingNetworkRequest(PendingIntent operation) { 4020 checkNotNull(operation, "PendingIntent cannot be null."); 4021 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, 4022 getCallingUid(), 0, operation)); 4023 } 4024 4025 // In order to implement the compatibility measure for pre-M apps that call 4026 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly, 4027 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork. 4028 // This ensures it has permission to do so. 4029 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) { 4030 if (nc == null) { 4031 return false; 4032 } 4033 int[] transportTypes = nc.getTransportTypes(); 4034 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) { 4035 return false; 4036 } 4037 try { 4038 mContext.enforceCallingOrSelfPermission( 4039 android.Manifest.permission.ACCESS_WIFI_STATE, 4040 "ConnectivityService"); 4041 } catch (SecurityException e) { 4042 return false; 4043 } 4044 return true; 4045 } 4046 4047 @Override 4048 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities, 4049 Messenger messenger, IBinder binder) { 4050 if (!hasWifiNetworkListenPermission(networkCapabilities)) { 4051 enforceAccessPermission(); 4052 } 4053 4054 NetworkRequest networkRequest = new NetworkRequest( 4055 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId()); 4056 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, 4057 NetworkRequestType.LISTEN); 4058 if (VDBG) log("listenForNetwork for " + nri); 4059 4060 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 4061 return networkRequest; 4062 } 4063 4064 @Override 4065 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities, 4066 PendingIntent operation) { 4067 checkNotNull(operation, "PendingIntent cannot be null."); 4068 if (!hasWifiNetworkListenPermission(networkCapabilities)) { 4069 enforceAccessPermission(); 4070 } 4071 4072 NetworkRequest networkRequest = new NetworkRequest( 4073 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId()); 4074 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation, 4075 NetworkRequestType.LISTEN); 4076 if (VDBG) log("pendingListenForNetwork for " + nri); 4077 4078 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 4079 } 4080 4081 @Override 4082 public void releaseNetworkRequest(NetworkRequest networkRequest) { 4083 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 4084 0, networkRequest)); 4085 } 4086 4087 @Override 4088 public void registerNetworkFactory(Messenger messenger, String name) { 4089 enforceConnectivityInternalPermission(); 4090 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel()); 4091 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi)); 4092 } 4093 4094 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) { 4095 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name); 4096 mNetworkFactoryInfos.put(nfi.messenger, nfi); 4097 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger); 4098 } 4099 4100 @Override 4101 public void unregisterNetworkFactory(Messenger messenger) { 4102 enforceConnectivityInternalPermission(); 4103 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger)); 4104 } 4105 4106 private void handleUnregisterNetworkFactory(Messenger messenger) { 4107 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger); 4108 if (nfi == null) { 4109 loge("Failed to find Messenger in unregisterNetworkFactory"); 4110 return; 4111 } 4112 if (DBG) log("unregisterNetworkFactory for " + nfi.name); 4113 } 4114 4115 /** 4116 * NetworkAgentInfo supporting a request by requestId. 4117 * These have already been vetted (their Capabilities satisfy the request) 4118 * and the are the highest scored network available. 4119 * the are keyed off the Requests requestId. 4120 */ 4121 // TODO: Yikes, this is accessed on multiple threads: add synchronization. 4122 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = 4123 new SparseArray<NetworkAgentInfo>(); 4124 4125 // NOTE: Accessed on multiple threads, must be synchronized on itself. 4126 @GuardedBy("mNetworkForNetId") 4127 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = 4128 new SparseArray<NetworkAgentInfo>(); 4129 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId. 4130 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so 4131 // there may not be a strict 1:1 correlation between the two. 4132 @GuardedBy("mNetworkForNetId") 4133 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray(); 4134 4135 // NetworkAgentInfo keyed off its connecting messenger 4136 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays 4137 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump(). 4138 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = 4139 new HashMap<Messenger, NetworkAgentInfo>(); 4140 4141 @GuardedBy("mBlockedAppUids") 4142 private final HashSet<Integer> mBlockedAppUids = new HashSet(); 4143 4144 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated. 4145 private final NetworkRequest mDefaultRequest; 4146 4147 // Request used to optionally keep mobile data active even when higher 4148 // priority networks like Wi-Fi are active. 4149 private final NetworkRequest mDefaultMobileDataRequest; 4150 4151 private NetworkAgentInfo getDefaultNetwork() { 4152 return mNetworkForRequestId.get(mDefaultRequest.requestId); 4153 } 4154 4155 private boolean isDefaultNetwork(NetworkAgentInfo nai) { 4156 return nai == getDefaultNetwork(); 4157 } 4158 4159 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo, 4160 LinkProperties linkProperties, NetworkCapabilities networkCapabilities, 4161 int currentScore, NetworkMisc networkMisc) { 4162 enforceConnectivityInternalPermission(); 4163 4164 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network 4165 // satisfies mDefaultRequest. 4166 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), 4167 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties( 4168 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore, 4169 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this); 4170 synchronized (this) { 4171 nai.networkMonitor.systemReady = mSystemReady; 4172 } 4173 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network); 4174 if (DBG) log("registerNetworkAgent " + nai); 4175 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai)); 4176 return nai.network.netId; 4177 } 4178 4179 private void handleRegisterNetworkAgent(NetworkAgentInfo na) { 4180 if (VDBG) log("Got NetworkAgent Messenger"); 4181 mNetworkAgentInfos.put(na.messenger, na); 4182 synchronized (mNetworkForNetId) { 4183 mNetworkForNetId.put(na.network.netId, na); 4184 } 4185 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger); 4186 NetworkInfo networkInfo = na.networkInfo; 4187 na.networkInfo = null; 4188 updateNetworkInfo(na, networkInfo); 4189 } 4190 4191 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) { 4192 LinkProperties newLp = networkAgent.linkProperties; 4193 int netId = networkAgent.network.netId; 4194 4195 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before 4196 // we do anything else, make sure its LinkProperties are accurate. 4197 if (networkAgent.clatd != null) { 4198 networkAgent.clatd.fixupLinkProperties(oldLp); 4199 } 4200 4201 updateInterfaces(newLp, oldLp, netId); 4202 updateMtu(newLp, oldLp); 4203 // TODO - figure out what to do for clat 4204// for (LinkProperties lp : newLp.getStackedLinks()) { 4205// updateMtu(lp, null); 4206// } 4207 updateTcpBufferSizes(networkAgent); 4208 4209 updateRoutes(newLp, oldLp, netId); 4210 updateDnses(newLp, oldLp, netId); 4211 4212 updateClat(newLp, oldLp, networkAgent); 4213 if (isDefaultNetwork(networkAgent)) { 4214 handleApplyDefaultProxy(newLp.getHttpProxy()); 4215 } else { 4216 updateProxy(newLp, oldLp, networkAgent); 4217 } 4218 // TODO - move this check to cover the whole function 4219 if (!Objects.equals(newLp, oldLp)) { 4220 notifyIfacesChangedForNetworkStats(); 4221 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED); 4222 } 4223 4224 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent); 4225 } 4226 4227 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) { 4228 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted(); 4229 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai); 4230 4231 if (!wasRunningClat && shouldRunClat) { 4232 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai); 4233 nai.clatd.start(); 4234 } else if (wasRunningClat && !shouldRunClat) { 4235 nai.clatd.stop(); 4236 } 4237 } 4238 4239 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) { 4240 CompareResult<String> interfaceDiff = new CompareResult<String>(); 4241 if (oldLp != null) { 4242 interfaceDiff = oldLp.compareAllInterfaceNames(newLp); 4243 } else if (newLp != null) { 4244 interfaceDiff.added = newLp.getAllInterfaceNames(); 4245 } 4246 for (String iface : interfaceDiff.added) { 4247 try { 4248 if (DBG) log("Adding iface " + iface + " to network " + netId); 4249 mNetd.addInterfaceToNetwork(iface, netId); 4250 } catch (Exception e) { 4251 loge("Exception adding interface: " + e); 4252 } 4253 } 4254 for (String iface : interfaceDiff.removed) { 4255 try { 4256 if (DBG) log("Removing iface " + iface + " from network " + netId); 4257 mNetd.removeInterfaceFromNetwork(iface, netId); 4258 } catch (Exception e) { 4259 loge("Exception removing interface: " + e); 4260 } 4261 } 4262 } 4263 4264 /** 4265 * Have netd update routes from oldLp to newLp. 4266 * @return true if routes changed between oldLp and newLp 4267 */ 4268 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) { 4269 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 4270 if (oldLp != null) { 4271 routeDiff = oldLp.compareAllRoutes(newLp); 4272 } else if (newLp != null) { 4273 routeDiff.added = newLp.getAllRoutes(); 4274 } 4275 4276 // add routes before removing old in case it helps with continuous connectivity 4277 4278 // do this twice, adding non-nexthop routes first, then routes they are dependent on 4279 for (RouteInfo route : routeDiff.added) { 4280 if (route.hasGateway()) continue; 4281 if (VDBG) log("Adding Route [" + route + "] to network " + netId); 4282 try { 4283 mNetd.addRoute(netId, route); 4284 } catch (Exception e) { 4285 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) { 4286 loge("Exception in addRoute for non-gateway: " + e); 4287 } 4288 } 4289 } 4290 for (RouteInfo route : routeDiff.added) { 4291 if (route.hasGateway() == false) continue; 4292 if (VDBG) log("Adding Route [" + route + "] to network " + netId); 4293 try { 4294 mNetd.addRoute(netId, route); 4295 } catch (Exception e) { 4296 if ((route.getGateway() instanceof Inet4Address) || VDBG) { 4297 loge("Exception in addRoute for gateway: " + e); 4298 } 4299 } 4300 } 4301 4302 for (RouteInfo route : routeDiff.removed) { 4303 if (VDBG) log("Removing Route [" + route + "] from network " + netId); 4304 try { 4305 mNetd.removeRoute(netId, route); 4306 } catch (Exception e) { 4307 loge("Exception in removeRoute: " + e); 4308 } 4309 } 4310 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty(); 4311 } 4312 4313 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) { 4314 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) { 4315 return; // no updating necessary 4316 } 4317 4318 Collection<InetAddress> dnses = newLp.getDnsServers(); 4319 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses); 4320 try { 4321 mNetd.setDnsConfigurationForNetwork( 4322 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains()); 4323 } catch (Exception e) { 4324 loge("Exception in setDnsConfigurationForNetwork: " + e); 4325 } 4326 final NetworkAgentInfo defaultNai = getDefaultNetwork(); 4327 if (defaultNai != null && defaultNai.network.netId == netId) { 4328 setDefaultDnsSystemProperties(dnses); 4329 } 4330 flushVmDnsCache(); 4331 } 4332 4333 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) { 4334 int last = 0; 4335 for (InetAddress dns : dnses) { 4336 ++last; 4337 String key = "net.dns" + last; 4338 String value = dns.getHostAddress(); 4339 SystemProperties.set(key, value); 4340 } 4341 for (int i = last + 1; i <= mNumDnsEntries; ++i) { 4342 String key = "net.dns" + i; 4343 SystemProperties.set(key, ""); 4344 } 4345 mNumDnsEntries = last; 4346 } 4347 4348 /** 4349 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities} 4350 * augmented with any stateful capabilities implied from {@code networkAgent} 4351 * (e.g., validated status and captive portal status). 4352 * 4353 * @param nai the network having its capabilities updated. 4354 * @param networkCapabilities the new network capabilities. 4355 */ 4356 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) { 4357 // Don't modify caller's NetworkCapabilities. 4358 networkCapabilities = new NetworkCapabilities(networkCapabilities); 4359 if (nai.lastValidated) { 4360 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED); 4361 } else { 4362 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED); 4363 } 4364 if (nai.lastCaptivePortalDetected) { 4365 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL); 4366 } else { 4367 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL); 4368 } 4369 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) { 4370 final int oldScore = nai.getCurrentScore(); 4371 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) != 4372 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) { 4373 try { 4374 mNetd.setNetworkPermission(nai.network.netId, 4375 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ? 4376 null : NetworkManagementService.PERMISSION_SYSTEM); 4377 } catch (RemoteException e) { 4378 loge("Exception in setNetworkPermission: " + e); 4379 } 4380 } 4381 synchronized (nai) { 4382 nai.networkCapabilities = networkCapabilities; 4383 } 4384 rematchAllNetworksAndRequests(nai, oldScore); 4385 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED); 4386 } 4387 } 4388 4389 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) { 4390 for (int i = 0; i < nai.networkRequests.size(); i++) { 4391 NetworkRequest nr = nai.networkRequests.valueAt(i); 4392 // Don't send listening requests to factories. b/17393458 4393 if (!isRequest(nr)) continue; 4394 sendUpdatedScoreToFactories(nr, nai.getCurrentScore()); 4395 } 4396 } 4397 4398 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) { 4399 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString()); 4400 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 4401 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0, 4402 networkRequest); 4403 } 4404 } 4405 4406 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent, 4407 int notificationType) { 4408 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) { 4409 Intent intent = new Intent(); 4410 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network); 4411 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request); 4412 nri.mPendingIntentSent = true; 4413 sendIntent(nri.mPendingIntent, intent); 4414 } 4415 // else not handled 4416 } 4417 4418 private void sendIntent(PendingIntent pendingIntent, Intent intent) { 4419 mPendingIntentWakeLock.acquire(); 4420 try { 4421 if (DBG) log("Sending " + pendingIntent); 4422 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */); 4423 } catch (PendingIntent.CanceledException e) { 4424 if (DBG) log(pendingIntent + " was not sent, it had been canceled."); 4425 mPendingIntentWakeLock.release(); 4426 releasePendingNetworkRequest(pendingIntent); 4427 } 4428 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished() 4429 } 4430 4431 @Override 4432 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, 4433 String resultData, Bundle resultExtras) { 4434 if (DBG) log("Finished sending " + pendingIntent); 4435 mPendingIntentWakeLock.release(); 4436 // Release with a delay so the receiving client has an opportunity to put in its 4437 // own request. 4438 releasePendingNetworkRequestWithDelay(pendingIntent); 4439 } 4440 4441 private void callCallbackForRequest(NetworkRequestInfo nri, 4442 NetworkAgentInfo networkAgent, int notificationType) { 4443 if (nri.messenger == null) return; // Default request has no msgr 4444 Bundle bundle = new Bundle(); 4445 bundle.putParcelable(NetworkRequest.class.getSimpleName(), 4446 new NetworkRequest(nri.request)); 4447 Message msg = Message.obtain(); 4448 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL && 4449 notificationType != ConnectivityManager.CALLBACK_RELEASED) { 4450 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network); 4451 } 4452 switch (notificationType) { 4453 case ConnectivityManager.CALLBACK_LOSING: { 4454 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor 4455 break; 4456 } 4457 case ConnectivityManager.CALLBACK_CAP_CHANGED: { 4458 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(), 4459 new NetworkCapabilities(networkAgent.networkCapabilities)); 4460 break; 4461 } 4462 case ConnectivityManager.CALLBACK_IP_CHANGED: { 4463 bundle.putParcelable(LinkProperties.class.getSimpleName(), 4464 new LinkProperties(networkAgent.linkProperties)); 4465 break; 4466 } 4467 } 4468 msg.what = notificationType; 4469 msg.setData(bundle); 4470 try { 4471 if (VDBG) { 4472 log("sending notification " + notifyTypeToName(notificationType) + 4473 " for " + nri.request); 4474 } 4475 nri.messenger.send(msg); 4476 } catch (RemoteException e) { 4477 // may occur naturally in the race of binder death. 4478 loge("RemoteException caught trying to send a callback msg for " + nri.request); 4479 } 4480 } 4481 4482 private void teardownUnneededNetwork(NetworkAgentInfo nai) { 4483 for (int i = 0; i < nai.networkRequests.size(); i++) { 4484 NetworkRequest nr = nai.networkRequests.valueAt(i); 4485 // Ignore listening requests. 4486 if (!isRequest(nr)) continue; 4487 loge("Dead network still had at least " + nr); 4488 break; 4489 } 4490 nai.asyncChannel.disconnect(); 4491 } 4492 4493 private void handleLingerComplete(NetworkAgentInfo oldNetwork) { 4494 if (oldNetwork == null) { 4495 loge("Unknown NetworkAgentInfo in handleLingerComplete"); 4496 return; 4497 } 4498 if (DBG) log("handleLingerComplete for " + oldNetwork.name()); 4499 teardownUnneededNetwork(oldNetwork); 4500 } 4501 4502 private void makeDefault(NetworkAgentInfo newNetwork, NetworkAgentInfo prevNetwork) { 4503 if (DBG) log("Switching to new default network: " + newNetwork); 4504 setupDataActivityTracking(newNetwork); 4505 try { 4506 mNetd.setDefaultNetId(newNetwork.network.netId); 4507 } catch (Exception e) { 4508 loge("Exception setting default network :" + e); 4509 } 4510 notifyLockdownVpn(newNetwork); 4511 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy()); 4512 updateTcpBufferSizes(newNetwork); 4513 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers()); 4514 logDefaultNetworkEvent(newNetwork, prevNetwork); 4515 } 4516 4517 // Handles a network appearing or improving its score. 4518 // 4519 // - Evaluates all current NetworkRequests that can be 4520 // satisfied by newNetwork, and reassigns to newNetwork 4521 // any such requests for which newNetwork is the best. 4522 // 4523 // - Lingers any validated Networks that as a result are no longer 4524 // needed. A network is needed if it is the best network for 4525 // one or more NetworkRequests, or if it is a VPN. 4526 // 4527 // - Tears down newNetwork if it just became validated 4528 // but turns out to be unneeded. 4529 // 4530 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated 4531 // networks that have no chance (i.e. even if validated) 4532 // of becoming the highest scoring network. 4533 // 4534 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy, 4535 // it does not remove NetworkRequests that other Networks could better satisfy. 4536 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}. 4537 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests} 4538 // as it performs better by a factor of the number of Networks. 4539 // 4540 // @param newNetwork is the network to be matched against NetworkRequests. 4541 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be 4542 // performed to tear down unvalidated networks that have no chance (i.e. even if 4543 // validated) of becoming the highest scoring network. 4544 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, 4545 ReapUnvalidatedNetworks reapUnvalidatedNetworks) { 4546 if (!newNetwork.everConnected) return; 4547 boolean keep = newNetwork.isVPN(); 4548 boolean isNewDefault = false; 4549 NetworkAgentInfo oldDefaultNetwork = null; 4550 if (VDBG) log("rematching " + newNetwork.name()); 4551 // Find and migrate to this Network any NetworkRequests for 4552 // which this network is now the best. 4553 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>(); 4554 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>(); 4555 if (VDBG) log(" network has: " + newNetwork.networkCapabilities); 4556 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 4557 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId); 4558 final boolean satisfies = newNetwork.satisfies(nri.request); 4559 if (newNetwork == currentNetwork && satisfies) { 4560 if (VDBG) { 4561 log("Network " + newNetwork.name() + " was already satisfying" + 4562 " request " + nri.request.requestId + ". No change."); 4563 } 4564 keep = true; 4565 continue; 4566 } 4567 4568 // check if it satisfies the NetworkCapabilities 4569 if (VDBG) log(" checking if request is satisfied: " + nri.request); 4570 if (satisfies) { 4571 if (!nri.isRequest()) { 4572 // This is not a request, it's a callback listener. 4573 // Add it to newNetwork regardless of score. 4574 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri); 4575 continue; 4576 } 4577 4578 // next check if it's better than any current network we're using for 4579 // this request 4580 if (VDBG) { 4581 log("currentScore = " + 4582 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) + 4583 ", newScore = " + newNetwork.getCurrentScore()); 4584 } 4585 if (currentNetwork == null || 4586 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) { 4587 if (VDBG) log("rematch for " + newNetwork.name()); 4588 if (currentNetwork != null) { 4589 if (VDBG) log(" accepting network in place of " + currentNetwork.name()); 4590 currentNetwork.networkRequests.remove(nri.request.requestId); 4591 currentNetwork.networkLingered.add(nri.request); 4592 affectedNetworks.add(currentNetwork); 4593 } else { 4594 if (VDBG) log(" accepting network in place of null"); 4595 } 4596 unlinger(newNetwork); 4597 mNetworkForRequestId.put(nri.request.requestId, newNetwork); 4598 if (!newNetwork.addRequest(nri.request)) { 4599 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request); 4600 } 4601 addedRequests.add(nri); 4602 keep = true; 4603 // Tell NetworkFactories about the new score, so they can stop 4604 // trying to connect if they know they cannot match it. 4605 // TODO - this could get expensive if we have alot of requests for this 4606 // network. Think about if there is a way to reduce this. Push 4607 // netid->request mapping to each factory? 4608 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore()); 4609 if (mDefaultRequest.requestId == nri.request.requestId) { 4610 isNewDefault = true; 4611 oldDefaultNetwork = currentNetwork; 4612 } 4613 } 4614 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) { 4615 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri", 4616 // mark it as no longer satisfying "nri". Because networks are processed by 4617 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will 4618 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher 4619 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri". 4620 // This means this code doesn't have to handle the case where "currentNetwork" no 4621 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork". 4622 if (DBG) { 4623 log("Network " + newNetwork.name() + " stopped satisfying" + 4624 " request " + nri.request.requestId); 4625 } 4626 newNetwork.networkRequests.remove(nri.request.requestId); 4627 if (currentNetwork == newNetwork) { 4628 mNetworkForRequestId.remove(nri.request.requestId); 4629 sendUpdatedScoreToFactories(nri.request, 0); 4630 } else { 4631 if (nri.isRequest()) { 4632 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " + 4633 newNetwork.name() + 4634 " without updating mNetworkForRequestId or factories!"); 4635 } 4636 } 4637 // TODO: technically, sending CALLBACK_LOST here is 4638 // incorrect if nri is a request (not a listen) and there 4639 // is a replacement network currently connected that can 4640 // satisfy it. However, the only capability that can both 4641 // a) be requested and b) change is NET_CAPABILITY_TRUSTED, 4642 // so this code is only incorrect for a network that loses 4643 // the TRUSTED capability, which is a rare case. 4644 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST); 4645 } 4646 } 4647 // Linger any networks that are no longer needed. 4648 for (NetworkAgentInfo nai : affectedNetworks) { 4649 if (nai.lingering) { 4650 // Already lingered. Nothing to do. This can only happen if "nai" is in 4651 // "affectedNetworks" twice. The reasoning being that to get added to 4652 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest 4653 // (i.e. not lingered) so it could have only been lingered by this loop. 4654 // unneeded(nai) will be false and we'll call unlinger() below which would 4655 // be bad, so handle it here. 4656 } else if (unneeded(nai)) { 4657 linger(nai); 4658 } else { 4659 // Clear nai.networkLingered we might have added above. 4660 unlinger(nai); 4661 } 4662 } 4663 if (isNewDefault) { 4664 // Notify system services that this network is up. 4665 makeDefault(newNetwork, oldDefaultNetwork); 4666 synchronized (ConnectivityService.this) { 4667 // have a new default network, release the transition wakelock in 4668 // a second if it's held. The second pause is to allow apps 4669 // to reconnect over the new network 4670 if (mNetTransitionWakeLock.isHeld()) { 4671 mHandler.sendMessageDelayed(mHandler.obtainMessage( 4672 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 4673 mNetTransitionWakeLockSerialNumber, 0), 4674 1000); 4675 } 4676 } 4677 } 4678 4679 // do this after the default net is switched, but 4680 // before LegacyTypeTracker sends legacy broadcasts 4681 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri); 4682 4683 if (isNewDefault) { 4684 // Maintain the illusion: since the legacy API only 4685 // understands one network at a time, we must pretend 4686 // that the current default network disconnected before 4687 // the new one connected. 4688 if (oldDefaultNetwork != null) { 4689 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(), 4690 oldDefaultNetwork, true); 4691 } 4692 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0; 4693 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork); 4694 notifyLockdownVpn(newNetwork); 4695 } 4696 4697 if (keep) { 4698 // Notify battery stats service about this network, both the normal 4699 // interface and any stacked links. 4700 // TODO: Avoid redoing this; this must only be done once when a network comes online. 4701 try { 4702 final IBatteryStats bs = BatteryStatsService.getService(); 4703 final int type = newNetwork.networkInfo.getType(); 4704 4705 final String baseIface = newNetwork.linkProperties.getInterfaceName(); 4706 bs.noteNetworkInterfaceType(baseIface, type); 4707 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) { 4708 final String stackedIface = stacked.getInterfaceName(); 4709 bs.noteNetworkInterfaceType(stackedIface, type); 4710 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface); 4711 } 4712 } catch (RemoteException ignored) { 4713 } 4714 4715 // This has to happen after the notifyNetworkCallbacks as that tickles each 4716 // ConnectivityManager instance so that legacy requests correctly bind dns 4717 // requests to this network. The legacy users are listening for this bcast 4718 // and will generally do a dns request so they can ensureRouteToHost and if 4719 // they do that before the callbacks happen they'll use the default network. 4720 // 4721 // TODO: Is there still a race here? We send the broadcast 4722 // after sending the callback, but if the app can receive the 4723 // broadcast before the callback, it might still break. 4724 // 4725 // This *does* introduce a race where if the user uses the new api 4726 // (notification callbacks) and then uses the old api (getNetworkInfo(type)) 4727 // they may get old info. Reverse this after the old startUsing api is removed. 4728 // This is on top of the multiple intent sequencing referenced in the todo above. 4729 for (int i = 0; i < newNetwork.networkRequests.size(); i++) { 4730 NetworkRequest nr = newNetwork.networkRequests.valueAt(i); 4731 if (nr.legacyType != TYPE_NONE && isRequest(nr)) { 4732 // legacy type tracker filters out repeat adds 4733 mLegacyTypeTracker.add(nr.legacyType, newNetwork); 4734 } 4735 } 4736 4737 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above, 4738 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest 4739 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the 4740 // newNetwork to the tracker explicitly (it's a no-op if it has already been added). 4741 if (newNetwork.isVPN()) { 4742 mLegacyTypeTracker.add(TYPE_VPN, newNetwork); 4743 } 4744 } 4745 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) { 4746 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 4747 if (unneeded(nai)) { 4748 if (DBG) log("Reaping " + nai.name()); 4749 teardownUnneededNetwork(nai); 4750 } 4751 } 4752 } 4753 } 4754 4755 /** 4756 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks 4757 * being disconnected. 4758 * @param changed If only one Network's score or capabilities have been modified since the last 4759 * time this function was called, pass this Network in this argument, otherwise pass 4760 * null. 4761 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not 4762 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via 4763 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if 4764 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a 4765 * network's score. 4766 */ 4767 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) { 4768 // TODO: This may get slow. The "changed" parameter is provided for future optimization 4769 // to avoid the slowness. It is not simply enough to process just "changed", for 4770 // example in the case where "changed"'s score decreases and another network should begin 4771 // satifying a NetworkRequest that "changed" currently satisfies. 4772 4773 // Optimization: Only reprocess "changed" if its score improved. This is safe because it 4774 // can only add more NetworkRequests satisfied by "changed", and this is exactly what 4775 // rematchNetworkAndRequests() handles. 4776 if (changed != null && oldScore < changed.getCurrentScore()) { 4777 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP); 4778 } else { 4779 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray( 4780 new NetworkAgentInfo[mNetworkAgentInfos.size()]); 4781 // Rematch higher scoring networks first to prevent requests first matching a lower 4782 // scoring network and then a higher scoring network, which could produce multiple 4783 // callbacks and inadvertently unlinger networks. 4784 Arrays.sort(nais); 4785 for (NetworkAgentInfo nai : nais) { 4786 rematchNetworkAndRequests(nai, 4787 // Only reap the last time through the loop. Reaping before all rematching 4788 // is complete could incorrectly teardown a network that hasn't yet been 4789 // rematched. 4790 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP 4791 : ReapUnvalidatedNetworks.REAP); 4792 } 4793 } 4794 } 4795 4796 private void updateInetCondition(NetworkAgentInfo nai) { 4797 // Don't bother updating until we've graduated to validated at least once. 4798 if (!nai.everValidated) return; 4799 // For now only update icons for default connection. 4800 // TODO: Update WiFi and cellular icons separately. b/17237507 4801 if (!isDefaultNetwork(nai)) return; 4802 4803 int newInetCondition = nai.lastValidated ? 100 : 0; 4804 // Don't repeat publish. 4805 if (newInetCondition == mDefaultInetConditionPublished) return; 4806 4807 mDefaultInetConditionPublished = newInetCondition; 4808 sendInetConditionBroadcast(nai.networkInfo); 4809 } 4810 4811 private void notifyLockdownVpn(NetworkAgentInfo nai) { 4812 if (mLockdownTracker != null) { 4813 if (nai != null && nai.isVPN()) { 4814 mLockdownTracker.onVpnStateChanged(nai.networkInfo); 4815 } else { 4816 mLockdownTracker.onNetworkInfoChanged(); 4817 } 4818 } 4819 } 4820 4821 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) { 4822 NetworkInfo.State state = newInfo.getState(); 4823 NetworkInfo oldInfo = null; 4824 final int oldScore = networkAgent.getCurrentScore(); 4825 synchronized (networkAgent) { 4826 oldInfo = networkAgent.networkInfo; 4827 networkAgent.networkInfo = newInfo; 4828 } 4829 notifyLockdownVpn(networkAgent); 4830 4831 if (oldInfo != null && oldInfo.getState() == state) { 4832 if (oldInfo.isRoaming() != newInfo.isRoaming()) { 4833 if (VDBG) log("roaming status changed, notifying NetworkStatsService"); 4834 notifyIfacesChangedForNetworkStats(); 4835 } else if (VDBG) log("ignoring duplicate network state non-change"); 4836 // In either case, no further work should be needed. 4837 return; 4838 } 4839 if (DBG) { 4840 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " + 4841 (oldInfo == null ? "null" : oldInfo.getState()) + 4842 " to " + state); 4843 } 4844 4845 if (!networkAgent.created 4846 && (state == NetworkInfo.State.CONNECTED 4847 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) { 4848 try { 4849 // This should never fail. Specifying an already in use NetID will cause failure. 4850 if (networkAgent.isVPN()) { 4851 mNetd.createVirtualNetwork(networkAgent.network.netId, 4852 !networkAgent.linkProperties.getDnsServers().isEmpty(), 4853 (networkAgent.networkMisc == null || 4854 !networkAgent.networkMisc.allowBypass)); 4855 } else { 4856 mNetd.createPhysicalNetwork(networkAgent.network.netId, 4857 networkAgent.networkCapabilities.hasCapability( 4858 NET_CAPABILITY_NOT_RESTRICTED) ? 4859 null : NetworkManagementService.PERMISSION_SYSTEM); 4860 } 4861 } catch (Exception e) { 4862 loge("Error creating network " + networkAgent.network.netId + ": " 4863 + e.getMessage()); 4864 return; 4865 } 4866 networkAgent.created = true; 4867 } 4868 4869 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) { 4870 networkAgent.everConnected = true; 4871 4872 updateLinkProperties(networkAgent, null); 4873 notifyIfacesChangedForNetworkStats(); 4874 4875 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 4876 scheduleUnvalidatedPrompt(networkAgent); 4877 4878 if (networkAgent.isVPN()) { 4879 // Temporarily disable the default proxy (not global). 4880 synchronized (mProxyLock) { 4881 if (!mDefaultProxyDisabled) { 4882 mDefaultProxyDisabled = true; 4883 if (mGlobalProxy == null && mDefaultProxy != null) { 4884 sendProxyBroadcast(null); 4885 } 4886 } 4887 } 4888 // TODO: support proxy per network. 4889 } 4890 4891 // Whether a particular NetworkRequest listen should cause signal strength thresholds to 4892 // be communicated to a particular NetworkAgent depends only on the network's immutable, 4893 // capabilities, so it only needs to be done once on initial connect, not every time the 4894 // network's capabilities change. Note that we do this before rematching the network, 4895 // so we could decide to tear it down immediately afterwards. That's fine though - on 4896 // disconnection NetworkAgents should stop any signal strength monitoring they have been 4897 // doing. 4898 updateSignalStrengthThresholds(networkAgent, "CONNECT", null); 4899 4900 // Consider network even though it is not yet validated. 4901 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP); 4902 4903 // This has to happen after matching the requests, because callbacks are just requests. 4904 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK); 4905 } else if (state == NetworkInfo.State.DISCONNECTED) { 4906 networkAgent.asyncChannel.disconnect(); 4907 if (networkAgent.isVPN()) { 4908 synchronized (mProxyLock) { 4909 if (mDefaultProxyDisabled) { 4910 mDefaultProxyDisabled = false; 4911 if (mGlobalProxy == null && mDefaultProxy != null) { 4912 sendProxyBroadcast(mDefaultProxy); 4913 } 4914 } 4915 } 4916 } 4917 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) || 4918 state == NetworkInfo.State.SUSPENDED) { 4919 // going into or coming out of SUSPEND: rescore and notify 4920 if (networkAgent.getCurrentScore() != oldScore) { 4921 rematchAllNetworksAndRequests(networkAgent, oldScore); 4922 } 4923 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ? 4924 ConnectivityManager.CALLBACK_SUSPENDED : 4925 ConnectivityManager.CALLBACK_RESUMED)); 4926 mLegacyTypeTracker.update(networkAgent); 4927 } 4928 } 4929 4930 private void updateNetworkScore(NetworkAgentInfo nai, int score) { 4931 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score); 4932 if (score < 0) { 4933 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score + 4934 "). Bumping score to min of 0"); 4935 score = 0; 4936 } 4937 4938 final int oldScore = nai.getCurrentScore(); 4939 nai.setCurrentScore(score); 4940 4941 rematchAllNetworksAndRequests(nai, oldScore); 4942 4943 sendUpdatedScoreToFactories(nai); 4944 } 4945 4946 // notify only this one new request of the current state 4947 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) { 4948 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE; 4949 // TODO - read state from monitor to decide what to send. 4950// if (nai.networkMonitor.isLingering()) { 4951// notifyType = NetworkCallbacks.LOSING; 4952// } else if (nai.networkMonitor.isEvaluating()) { 4953// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType); 4954// } 4955 if (nri.mPendingIntent == null) { 4956 callCallbackForRequest(nri, nai, notifyType); 4957 } else { 4958 sendPendingIntentForRequest(nri, nai, notifyType); 4959 } 4960 } 4961 4962 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) { 4963 // The NetworkInfo we actually send out has no bearing on the real 4964 // state of affairs. For example, if the default connection is mobile, 4965 // and a request for HIPRI has just gone away, we need to pretend that 4966 // HIPRI has just disconnected. So we need to set the type to HIPRI and 4967 // the state to DISCONNECTED, even though the network is of type MOBILE 4968 // and is still connected. 4969 NetworkInfo info = new NetworkInfo(nai.networkInfo); 4970 info.setType(type); 4971 if (state != DetailedState.DISCONNECTED) { 4972 info.setDetailedState(state, null, info.getExtraInfo()); 4973 sendConnectedBroadcast(info); 4974 } else { 4975 info.setDetailedState(state, info.getReason(), info.getExtraInfo()); 4976 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 4977 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 4978 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 4979 if (info.isFailover()) { 4980 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 4981 nai.networkInfo.setFailover(false); 4982 } 4983 if (info.getReason() != null) { 4984 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 4985 } 4986 if (info.getExtraInfo() != null) { 4987 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo()); 4988 } 4989 NetworkAgentInfo newDefaultAgent = null; 4990 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 4991 newDefaultAgent = getDefaultNetwork(); 4992 if (newDefaultAgent != null) { 4993 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, 4994 newDefaultAgent.networkInfo); 4995 } else { 4996 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 4997 } 4998 } 4999 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, 5000 mDefaultInetConditionPublished); 5001 sendStickyBroadcast(intent); 5002 if (newDefaultAgent != null) { 5003 sendConnectedBroadcast(newDefaultAgent.networkInfo); 5004 } 5005 } 5006 } 5007 5008 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) { 5009 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name()); 5010 for (int i = 0; i < networkAgent.networkRequests.size(); i++) { 5011 NetworkRequest nr = networkAgent.networkRequests.valueAt(i); 5012 NetworkRequestInfo nri = mNetworkRequests.get(nr); 5013 if (VDBG) log(" sending notification for " + nr); 5014 if (nri.mPendingIntent == null) { 5015 callCallbackForRequest(nri, networkAgent, notifyType); 5016 } else { 5017 sendPendingIntentForRequest(nri, networkAgent, notifyType); 5018 } 5019 } 5020 } 5021 5022 private String notifyTypeToName(int notifyType) { 5023 switch (notifyType) { 5024 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK"; 5025 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE"; 5026 case ConnectivityManager.CALLBACK_LOSING: return "LOSING"; 5027 case ConnectivityManager.CALLBACK_LOST: return "LOST"; 5028 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE"; 5029 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED"; 5030 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED"; 5031 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED"; 5032 } 5033 return "UNKNOWN"; 5034 } 5035 5036 /** 5037 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the 5038 * properties tracked by NetworkStatsService on an active iface has changed. 5039 */ 5040 private void notifyIfacesChangedForNetworkStats() { 5041 try { 5042 mStatsService.forceUpdateIfaces(); 5043 } catch (Exception ignored) { 5044 } 5045 } 5046 5047 @Override 5048 public boolean addVpnAddress(String address, int prefixLength) { 5049 throwIfLockdownEnabled(); 5050 int user = UserHandle.getUserId(Binder.getCallingUid()); 5051 synchronized (mVpns) { 5052 return mVpns.get(user).addAddress(address, prefixLength); 5053 } 5054 } 5055 5056 @Override 5057 public boolean removeVpnAddress(String address, int prefixLength) { 5058 throwIfLockdownEnabled(); 5059 int user = UserHandle.getUserId(Binder.getCallingUid()); 5060 synchronized (mVpns) { 5061 return mVpns.get(user).removeAddress(address, prefixLength); 5062 } 5063 } 5064 5065 @Override 5066 public boolean setUnderlyingNetworksForVpn(Network[] networks) { 5067 throwIfLockdownEnabled(); 5068 int user = UserHandle.getUserId(Binder.getCallingUid()); 5069 boolean success; 5070 synchronized (mVpns) { 5071 success = mVpns.get(user).setUnderlyingNetworks(networks); 5072 } 5073 if (success) { 5074 notifyIfacesChangedForNetworkStats(); 5075 } 5076 return success; 5077 } 5078 5079 @Override 5080 public String getCaptivePortalServerUrl() { 5081 return NetworkMonitor.getCaptivePortalServerUrl(mContext); 5082 } 5083 5084 @Override 5085 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger, 5086 IBinder binder, String srcAddr, int srcPort, String dstAddr) { 5087 enforceKeepalivePermission(); 5088 mKeepaliveTracker.startNattKeepalive( 5089 getNetworkAgentInfoForNetwork(network), 5090 intervalSeconds, messenger, binder, 5091 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT); 5092 } 5093 5094 @Override 5095 public void stopKeepalive(Network network, int slot) { 5096 mHandler.sendMessage(mHandler.obtainMessage( 5097 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network)); 5098 } 5099 5100 @Override 5101 public void factoryReset() { 5102 enforceConnectivityInternalPermission(); 5103 5104 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) { 5105 return; 5106 } 5107 5108 final int userId = UserHandle.getCallingUserId(); 5109 5110 // Turn airplane mode off 5111 setAirplaneMode(false); 5112 5113 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) { 5114 // Untether 5115 for (String tether : getTetheredIfaces()) { 5116 untether(tether); 5117 } 5118 } 5119 5120 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) { 5121 // Turn VPN off 5122 VpnConfig vpnConfig = getVpnConfig(userId); 5123 if (vpnConfig != null) { 5124 if (vpnConfig.legacy) { 5125 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId); 5126 } else { 5127 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections 5128 // in the future without user intervention. 5129 setVpnPackageAuthorization(vpnConfig.user, userId, false); 5130 5131 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId); 5132 } 5133 } 5134 } 5135 } 5136 5137 @VisibleForTesting 5138 public NetworkMonitor createNetworkMonitor(Context context, Handler handler, 5139 NetworkAgentInfo nai, NetworkRequest defaultRequest) { 5140 return new NetworkMonitor(context, handler, nai, defaultRequest); 5141 } 5142 5143 private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) { 5144 int newNetid = NETID_UNSET; 5145 int prevNetid = NETID_UNSET; 5146 int[] transports = new int[0]; 5147 boolean hadIPv4 = false; 5148 boolean hadIPv6 = false; 5149 5150 if (newNai != null) { 5151 newNetid = newNai.network.netId; 5152 transports = newNai.networkCapabilities.getTransportTypes(); 5153 } 5154 if (prevNai != null) { 5155 prevNetid = prevNai.network.netId; 5156 final LinkProperties lp = prevNai.linkProperties; 5157 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute(); 5158 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute(); 5159 } 5160 5161 DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6); 5162 } 5163} 5164