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