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