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