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