ConnectivityService.java revision 9be58c55806faf3833d0288cb043d4eb9a37930d
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 private void handleNetworkUnvalidated(NetworkAgentInfo nai) { 2775 NetworkCapabilities nc = nai.networkCapabilities; 2776 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc); 2777 2778 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && !avoidBadWifi()) { 2779 showValidationNotification(nai, NotificationType.LOST_INTERNET); 2780 } 2781 } 2782 2783 private class InternalHandler extends Handler { 2784 public InternalHandler(Looper looper) { 2785 super(looper); 2786 } 2787 2788 @Override 2789 public void handleMessage(Message msg) { 2790 switch (msg.what) { 2791 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK: 2792 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: { 2793 String causedBy = null; 2794 synchronized (ConnectivityService.this) { 2795 if (msg.arg1 == mNetTransitionWakeLockSerialNumber && 2796 mNetTransitionWakeLock.isHeld()) { 2797 mNetTransitionWakeLock.release(); 2798 causedBy = mNetTransitionWakeLockCausedBy; 2799 } else { 2800 break; 2801 } 2802 } 2803 if (VDBG) { 2804 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) { 2805 log("Failed to find a new network - expiring NetTransition Wakelock"); 2806 } else { 2807 log("NetTransition Wakelock (" + 2808 (causedBy == null ? "unknown" : causedBy) + 2809 " cleared because we found a replacement network"); 2810 } 2811 } 2812 break; 2813 } 2814 case EVENT_APPLY_GLOBAL_HTTP_PROXY: { 2815 handleDeprecatedGlobalHttpProxy(); 2816 break; 2817 } 2818 case EVENT_PROXY_HAS_CHANGED: { 2819 handleApplyDefaultProxy((ProxyInfo)msg.obj); 2820 break; 2821 } 2822 case EVENT_REGISTER_NETWORK_FACTORY: { 2823 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj); 2824 break; 2825 } 2826 case EVENT_UNREGISTER_NETWORK_FACTORY: { 2827 handleUnregisterNetworkFactory((Messenger)msg.obj); 2828 break; 2829 } 2830 case EVENT_REGISTER_NETWORK_AGENT: { 2831 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj); 2832 break; 2833 } 2834 case EVENT_REGISTER_NETWORK_REQUEST: 2835 case EVENT_REGISTER_NETWORK_LISTENER: { 2836 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj); 2837 break; 2838 } 2839 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: 2840 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: { 2841 handleRegisterNetworkRequestWithIntent(msg); 2842 break; 2843 } 2844 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: { 2845 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1); 2846 break; 2847 } 2848 case EVENT_RELEASE_NETWORK_REQUEST: { 2849 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1); 2850 break; 2851 } 2852 case EVENT_SET_ACCEPT_UNVALIDATED: { 2853 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0); 2854 break; 2855 } 2856 case EVENT_PROMPT_UNVALIDATED: { 2857 handlePromptUnvalidated((Network) msg.obj); 2858 break; 2859 } 2860 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: { 2861 handleMobileDataAlwaysOn(); 2862 break; 2863 } 2864 case EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI: { 2865 rematchAllNetworksAndRequests(null, 0); 2866 break; 2867 } 2868 case EVENT_REQUEST_LINKPROPERTIES: 2869 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1); 2870 break; 2871 case EVENT_REQUEST_NETCAPABILITIES: 2872 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1); 2873 break; 2874 // Sent by KeepaliveTracker to process an app request on the state machine thread. 2875 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: { 2876 mKeepaliveTracker.handleStartKeepalive(msg); 2877 break; 2878 } 2879 // Sent by KeepaliveTracker to process an app request on the state machine thread. 2880 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: { 2881 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj); 2882 int slot = msg.arg1; 2883 int reason = msg.arg2; 2884 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason); 2885 break; 2886 } 2887 case EVENT_SYSTEM_READY: { 2888 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2889 nai.networkMonitor.systemReady = true; 2890 } 2891 break; 2892 } 2893 } 2894 } 2895 } 2896 2897 // javadoc from interface 2898 @Override 2899 public int tether(String iface) { 2900 ConnectivityManager.enforceTetherChangePermission(mContext); 2901 if (isTetheringSupported()) { 2902 final int status = mTethering.tether(iface); 2903 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) { 2904 try { 2905 mPolicyManager.onTetheringChanged(iface, true); 2906 } catch (RemoteException e) { 2907 } 2908 } 2909 return status; 2910 } else { 2911 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2912 } 2913 } 2914 2915 // javadoc from interface 2916 @Override 2917 public int untether(String iface) { 2918 ConnectivityManager.enforceTetherChangePermission(mContext); 2919 2920 if (isTetheringSupported()) { 2921 final int status = mTethering.untether(iface); 2922 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) { 2923 try { 2924 mPolicyManager.onTetheringChanged(iface, false); 2925 } catch (RemoteException e) { 2926 } 2927 } 2928 return status; 2929 } else { 2930 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2931 } 2932 } 2933 2934 // javadoc from interface 2935 @Override 2936 public int getLastTetherError(String iface) { 2937 enforceTetherAccessPermission(); 2938 2939 if (isTetheringSupported()) { 2940 return mTethering.getLastTetherError(iface); 2941 } else { 2942 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2943 } 2944 } 2945 2946 // TODO - proper iface API for selection by property, inspection, etc 2947 @Override 2948 public String[] getTetherableUsbRegexs() { 2949 enforceTetherAccessPermission(); 2950 if (isTetheringSupported()) { 2951 return mTethering.getTetherableUsbRegexs(); 2952 } else { 2953 return new String[0]; 2954 } 2955 } 2956 2957 @Override 2958 public String[] getTetherableWifiRegexs() { 2959 enforceTetherAccessPermission(); 2960 if (isTetheringSupported()) { 2961 return mTethering.getTetherableWifiRegexs(); 2962 } else { 2963 return new String[0]; 2964 } 2965 } 2966 2967 @Override 2968 public String[] getTetherableBluetoothRegexs() { 2969 enforceTetherAccessPermission(); 2970 if (isTetheringSupported()) { 2971 return mTethering.getTetherableBluetoothRegexs(); 2972 } else { 2973 return new String[0]; 2974 } 2975 } 2976 2977 @Override 2978 public int setUsbTethering(boolean enable) { 2979 ConnectivityManager.enforceTetherChangePermission(mContext); 2980 if (isTetheringSupported()) { 2981 return mTethering.setUsbTethering(enable); 2982 } else { 2983 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2984 } 2985 } 2986 2987 // TODO - move iface listing, queries, etc to new module 2988 // javadoc from interface 2989 @Override 2990 public String[] getTetherableIfaces() { 2991 enforceTetherAccessPermission(); 2992 return mTethering.getTetherableIfaces(); 2993 } 2994 2995 @Override 2996 public String[] getTetheredIfaces() { 2997 enforceTetherAccessPermission(); 2998 return mTethering.getTetheredIfaces(); 2999 } 3000 3001 @Override 3002 public String[] getTetheringErroredIfaces() { 3003 enforceTetherAccessPermission(); 3004 return mTethering.getErroredIfaces(); 3005 } 3006 3007 @Override 3008 public String[] getTetheredDhcpRanges() { 3009 enforceConnectivityInternalPermission(); 3010 return mTethering.getTetheredDhcpRanges(); 3011 } 3012 3013 // if ro.tether.denied = true we default to no tethering 3014 // gservices could set the secure setting to 1 though to enable it on a build where it 3015 // had previously been turned off. 3016 @Override 3017 public boolean isTetheringSupported() { 3018 enforceTetherAccessPermission(); 3019 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 3020 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(), 3021 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0) 3022 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING); 3023 return tetherEnabledInSettings && mUserManager.isAdminUser() && 3024 ((mTethering.getTetherableUsbRegexs().length != 0 || 3025 mTethering.getTetherableWifiRegexs().length != 0 || 3026 mTethering.getTetherableBluetoothRegexs().length != 0) && 3027 mTethering.getUpstreamIfaceTypes().length != 0); 3028 } 3029 3030 @Override 3031 public void startTethering(int type, ResultReceiver receiver, 3032 boolean showProvisioningUi) { 3033 ConnectivityManager.enforceTetherChangePermission(mContext); 3034 if (!isTetheringSupported()) { 3035 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null); 3036 return; 3037 } 3038 mTethering.startTethering(type, receiver, showProvisioningUi); 3039 } 3040 3041 @Override 3042 public void stopTethering(int type) { 3043 ConnectivityManager.enforceTetherChangePermission(mContext); 3044 mTethering.stopTethering(type); 3045 } 3046 3047 // Called when we lose the default network and have no replacement yet. 3048 // This will automatically be cleared after X seconds or a new default network 3049 // becomes CONNECTED, whichever happens first. The timer is started by the 3050 // first caller and not restarted by subsequent callers. 3051 private void requestNetworkTransitionWakelock(String forWhom) { 3052 int serialNum = 0; 3053 synchronized (this) { 3054 if (mNetTransitionWakeLock.isHeld()) return; 3055 serialNum = ++mNetTransitionWakeLockSerialNumber; 3056 mNetTransitionWakeLock.acquire(); 3057 mNetTransitionWakeLockCausedBy = forWhom; 3058 } 3059 mHandler.sendMessageDelayed(mHandler.obtainMessage( 3060 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0), 3061 mNetTransitionWakeLockTimeout); 3062 return; 3063 } 3064 3065 // 100 percent is full good, 0 is full bad. 3066 @Override 3067 public void reportInetCondition(int networkType, int percentage) { 3068 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 3069 if (nai == null) return; 3070 reportNetworkConnectivity(nai.network, percentage > 50); 3071 } 3072 3073 @Override 3074 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) { 3075 enforceAccessPermission(); 3076 enforceInternetPermission(); 3077 3078 NetworkAgentInfo nai; 3079 if (network == null) { 3080 nai = getDefaultNetwork(); 3081 } else { 3082 nai = getNetworkAgentInfoForNetwork(network); 3083 } 3084 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING || 3085 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) { 3086 return; 3087 } 3088 // Revalidate if the app report does not match our current validated state. 3089 if (hasConnectivity == nai.lastValidated) return; 3090 final int uid = Binder.getCallingUid(); 3091 if (DBG) { 3092 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity + 3093 ") by " + uid); 3094 } 3095 synchronized (nai) { 3096 // Validating a network that has not yet connected could result in a call to 3097 // rematchNetworkAndRequests() which is not meant to work on such networks. 3098 if (!nai.everConnected) return; 3099 3100 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return; 3101 3102 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid); 3103 } 3104 } 3105 3106 private ProxyInfo getDefaultProxy() { 3107 // this information is already available as a world read/writable jvm property 3108 // so this API change wouldn't have a benifit. It also breaks the passing 3109 // of proxy info to all the JVMs. 3110 // enforceAccessPermission(); 3111 synchronized (mProxyLock) { 3112 ProxyInfo ret = mGlobalProxy; 3113 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy; 3114 return ret; 3115 } 3116 } 3117 3118 @Override 3119 public ProxyInfo getProxyForNetwork(Network network) { 3120 if (network == null) return getDefaultProxy(); 3121 final ProxyInfo globalProxy = getGlobalProxy(); 3122 if (globalProxy != null) return globalProxy; 3123 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null; 3124 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which 3125 // caller may not have. 3126 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 3127 if (nai == null) return null; 3128 synchronized (nai) { 3129 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy(); 3130 if (proxyInfo == null) return null; 3131 return new ProxyInfo(proxyInfo); 3132 } 3133 } 3134 3135 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present 3136 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific 3137 // proxy is null then there is no proxy in place). 3138 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) { 3139 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 3140 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) { 3141 proxy = null; 3142 } 3143 return proxy; 3144 } 3145 3146 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it 3147 // better for determining if a new proxy broadcast is necessary: 3148 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to 3149 // avoid unnecessary broadcasts. 3150 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL 3151 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler) 3152 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but 3153 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port 3154 // all set. 3155 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) { 3156 a = canonicalizeProxyInfo(a); 3157 b = canonicalizeProxyInfo(b); 3158 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check 3159 // hosts even when PAC URLs are present to account for the legacy PAC resolver. 3160 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost())); 3161 } 3162 3163 public void setGlobalProxy(ProxyInfo proxyProperties) { 3164 enforceConnectivityInternalPermission(); 3165 3166 synchronized (mProxyLock) { 3167 if (proxyProperties == mGlobalProxy) return; 3168 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return; 3169 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return; 3170 3171 String host = ""; 3172 int port = 0; 3173 String exclList = ""; 3174 String pacFileUrl = ""; 3175 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) || 3176 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) { 3177 if (!proxyProperties.isValid()) { 3178 if (DBG) 3179 log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3180 return; 3181 } 3182 mGlobalProxy = new ProxyInfo(proxyProperties); 3183 host = mGlobalProxy.getHost(); 3184 port = mGlobalProxy.getPort(); 3185 exclList = mGlobalProxy.getExclusionListAsString(); 3186 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) { 3187 pacFileUrl = proxyProperties.getPacFileUrl().toString(); 3188 } 3189 } else { 3190 mGlobalProxy = null; 3191 } 3192 ContentResolver res = mContext.getContentResolver(); 3193 final long token = Binder.clearCallingIdentity(); 3194 try { 3195 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host); 3196 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port); 3197 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 3198 exclList); 3199 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl); 3200 } finally { 3201 Binder.restoreCallingIdentity(token); 3202 } 3203 3204 if (mGlobalProxy == null) { 3205 proxyProperties = mDefaultProxy; 3206 } 3207 sendProxyBroadcast(proxyProperties); 3208 } 3209 } 3210 3211 private void loadGlobalProxy() { 3212 ContentResolver res = mContext.getContentResolver(); 3213 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST); 3214 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0); 3215 String exclList = Settings.Global.getString(res, 3216 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST); 3217 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC); 3218 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) { 3219 ProxyInfo proxyProperties; 3220 if (!TextUtils.isEmpty(pacFileUrl)) { 3221 proxyProperties = new ProxyInfo(pacFileUrl); 3222 } else { 3223 proxyProperties = new ProxyInfo(host, port, exclList); 3224 } 3225 if (!proxyProperties.isValid()) { 3226 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3227 return; 3228 } 3229 3230 synchronized (mProxyLock) { 3231 mGlobalProxy = proxyProperties; 3232 } 3233 } 3234 } 3235 3236 public ProxyInfo getGlobalProxy() { 3237 // this information is already available as a world read/writable jvm property 3238 // so this API change wouldn't have a benifit. It also breaks the passing 3239 // of proxy info to all the JVMs. 3240 // enforceAccessPermission(); 3241 synchronized (mProxyLock) { 3242 return mGlobalProxy; 3243 } 3244 } 3245 3246 private void handleApplyDefaultProxy(ProxyInfo proxy) { 3247 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 3248 && Uri.EMPTY.equals(proxy.getPacFileUrl())) { 3249 proxy = null; 3250 } 3251 synchronized (mProxyLock) { 3252 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return; 3253 if (mDefaultProxy == proxy) return; // catches repeated nulls 3254 if (proxy != null && !proxy.isValid()) { 3255 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString()); 3256 return; 3257 } 3258 3259 // This call could be coming from the PacManager, containing the port of the local 3260 // proxy. If this new proxy matches the global proxy then copy this proxy to the 3261 // global (to get the correct local port), and send a broadcast. 3262 // TODO: Switch PacManager to have its own message to send back rather than 3263 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy. 3264 if ((mGlobalProxy != null) && (proxy != null) 3265 && (!Uri.EMPTY.equals(proxy.getPacFileUrl())) 3266 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) { 3267 mGlobalProxy = proxy; 3268 sendProxyBroadcast(mGlobalProxy); 3269 return; 3270 } 3271 mDefaultProxy = proxy; 3272 3273 if (mGlobalProxy != null) return; 3274 if (!mDefaultProxyDisabled) { 3275 sendProxyBroadcast(proxy); 3276 } 3277 } 3278 } 3279 3280 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy. 3281 // This method gets called when any network changes proxy, but the broadcast only ever contains 3282 // the default proxy (even if it hasn't changed). 3283 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network 3284 // world where an app might be bound to a non-default network. 3285 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) { 3286 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy(); 3287 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy(); 3288 3289 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) { 3290 sendProxyBroadcast(getDefaultProxy()); 3291 } 3292 } 3293 3294 private void handleDeprecatedGlobalHttpProxy() { 3295 String proxy = Settings.Global.getString(mContext.getContentResolver(), 3296 Settings.Global.HTTP_PROXY); 3297 if (!TextUtils.isEmpty(proxy)) { 3298 String data[] = proxy.split(":"); 3299 if (data.length == 0) { 3300 return; 3301 } 3302 3303 String proxyHost = data[0]; 3304 int proxyPort = 8080; 3305 if (data.length > 1) { 3306 try { 3307 proxyPort = Integer.parseInt(data[1]); 3308 } catch (NumberFormatException e) { 3309 return; 3310 } 3311 } 3312 ProxyInfo p = new ProxyInfo(data[0], proxyPort, ""); 3313 setGlobalProxy(p); 3314 } 3315 } 3316 3317 private void sendProxyBroadcast(ProxyInfo proxy) { 3318 if (proxy == null) proxy = new ProxyInfo("", 0, ""); 3319 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return; 3320 if (DBG) log("sending Proxy Broadcast for " + proxy); 3321 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); 3322 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 3323 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3324 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy); 3325 final long ident = Binder.clearCallingIdentity(); 3326 try { 3327 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 3328 } finally { 3329 Binder.restoreCallingIdentity(ident); 3330 } 3331 } 3332 3333 private static class SettingsObserver extends ContentObserver { 3334 final private HashMap<Uri, Integer> mUriEventMap; 3335 final private Context mContext; 3336 final private Handler mHandler; 3337 3338 SettingsObserver(Context context, Handler handler) { 3339 super(null); 3340 mUriEventMap = new HashMap<Uri, Integer>(); 3341 mContext = context; 3342 mHandler = handler; 3343 } 3344 3345 void observe(Uri uri, int what) { 3346 mUriEventMap.put(uri, what); 3347 final ContentResolver resolver = mContext.getContentResolver(); 3348 resolver.registerContentObserver(uri, false, this); 3349 } 3350 3351 @Override 3352 public void onChange(boolean selfChange) { 3353 Slog.wtf(TAG, "Should never be reached."); 3354 } 3355 3356 @Override 3357 public void onChange(boolean selfChange, Uri uri) { 3358 final Integer what = mUriEventMap.get(uri); 3359 if (what != null) { 3360 mHandler.obtainMessage(what.intValue()).sendToTarget(); 3361 } else { 3362 loge("No matching event to send for URI=" + uri); 3363 } 3364 } 3365 } 3366 3367 private static void log(String s) { 3368 Slog.d(TAG, s); 3369 } 3370 3371 private static void loge(String s) { 3372 Slog.e(TAG, s); 3373 } 3374 3375 private static <T> T checkNotNull(T value, String message) { 3376 if (value == null) { 3377 throw new NullPointerException(message); 3378 } 3379 return value; 3380 } 3381 3382 /** 3383 * Prepare for a VPN application. 3384 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId}, 3385 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required. 3386 * 3387 * @param oldPackage Package name of the application which currently controls VPN, which will 3388 * be replaced. If there is no such application, this should should either be 3389 * {@code null} or {@link VpnConfig.LEGACY_VPN}. 3390 * @param newPackage Package name of the application which should gain control of VPN, or 3391 * {@code null} to disable. 3392 * @param userId User for whom to prepare the new VPN. 3393 * 3394 * @hide 3395 */ 3396 @Override 3397 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage, 3398 int userId) { 3399 enforceCrossUserPermission(userId); 3400 throwIfLockdownEnabled(); 3401 3402 synchronized(mVpns) { 3403 Vpn vpn = mVpns.get(userId); 3404 if (vpn != null) { 3405 return vpn.prepare(oldPackage, newPackage); 3406 } else { 3407 return false; 3408 } 3409 } 3410 } 3411 3412 /** 3413 * Set whether the VPN package has the ability to launch VPNs without user intervention. 3414 * This method is used by system-privileged apps. 3415 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId}, 3416 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required. 3417 * 3418 * @param packageName The package for which authorization state should change. 3419 * @param userId User for whom {@code packageName} is installed. 3420 * @param authorized {@code true} if this app should be able to start a VPN connection without 3421 * explicit user approval, {@code false} if not. 3422 * 3423 * @hide 3424 */ 3425 @Override 3426 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) { 3427 enforceCrossUserPermission(userId); 3428 3429 synchronized(mVpns) { 3430 Vpn vpn = mVpns.get(userId); 3431 if (vpn != null) { 3432 vpn.setPackageAuthorization(packageName, authorized); 3433 } 3434 } 3435 } 3436 3437 /** 3438 * Configure a TUN interface and return its file descriptor. Parameters 3439 * are encoded and opaque to this class. This method is used by VpnBuilder 3440 * and not available in ConnectivityManager. Permissions are checked in 3441 * Vpn class. 3442 * @hide 3443 */ 3444 @Override 3445 public ParcelFileDescriptor establishVpn(VpnConfig config) { 3446 throwIfLockdownEnabled(); 3447 int user = UserHandle.getUserId(Binder.getCallingUid()); 3448 synchronized(mVpns) { 3449 return mVpns.get(user).establish(config); 3450 } 3451 } 3452 3453 /** 3454 * Start legacy VPN, controlling native daemons as needed. Creates a 3455 * secondary thread to perform connection work, returning quickly. 3456 */ 3457 @Override 3458 public void startLegacyVpn(VpnProfile profile) { 3459 throwIfLockdownEnabled(); 3460 final LinkProperties egress = getActiveLinkProperties(); 3461 if (egress == null) { 3462 throw new IllegalStateException("Missing active network connection"); 3463 } 3464 int user = UserHandle.getUserId(Binder.getCallingUid()); 3465 synchronized(mVpns) { 3466 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress); 3467 } 3468 } 3469 3470 /** 3471 * Return the information of the ongoing legacy VPN. This method is used 3472 * by VpnSettings and not available in ConnectivityManager. Permissions 3473 * are checked in Vpn class. 3474 */ 3475 @Override 3476 public LegacyVpnInfo getLegacyVpnInfo(int userId) { 3477 enforceCrossUserPermission(userId); 3478 3479 synchronized(mVpns) { 3480 return mVpns.get(userId).getLegacyVpnInfo(); 3481 } 3482 } 3483 3484 /** 3485 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService 3486 * and not available in ConnectivityManager. 3487 */ 3488 @Override 3489 public VpnInfo[] getAllVpnInfo() { 3490 enforceConnectivityInternalPermission(); 3491 if (mLockdownEnabled) { 3492 return new VpnInfo[0]; 3493 } 3494 3495 synchronized(mVpns) { 3496 List<VpnInfo> infoList = new ArrayList<>(); 3497 for (int i = 0; i < mVpns.size(); i++) { 3498 VpnInfo info = createVpnInfo(mVpns.valueAt(i)); 3499 if (info != null) { 3500 infoList.add(info); 3501 } 3502 } 3503 return infoList.toArray(new VpnInfo[infoList.size()]); 3504 } 3505 } 3506 3507 /** 3508 * @return VPN information for accounting, or null if we can't retrieve all required 3509 * information, e.g primary underlying iface. 3510 */ 3511 @Nullable 3512 private VpnInfo createVpnInfo(Vpn vpn) { 3513 VpnInfo info = vpn.getVpnInfo(); 3514 if (info == null) { 3515 return null; 3516 } 3517 Network[] underlyingNetworks = vpn.getUnderlyingNetworks(); 3518 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret 3519 // the underlyingNetworks list. 3520 if (underlyingNetworks == null) { 3521 NetworkAgentInfo defaultNetwork = getDefaultNetwork(); 3522 if (defaultNetwork != null && defaultNetwork.linkProperties != null) { 3523 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName(); 3524 } 3525 } else if (underlyingNetworks.length > 0) { 3526 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]); 3527 if (linkProperties != null) { 3528 info.primaryUnderlyingIface = linkProperties.getInterfaceName(); 3529 } 3530 } 3531 return info.primaryUnderlyingIface == null ? null : info; 3532 } 3533 3534 /** 3535 * Returns the information of the ongoing VPN for {@code userId}. This method is used by 3536 * VpnDialogs and not available in ConnectivityManager. 3537 * Permissions are checked in Vpn class. 3538 * @hide 3539 */ 3540 @Override 3541 public VpnConfig getVpnConfig(int userId) { 3542 enforceCrossUserPermission(userId); 3543 synchronized(mVpns) { 3544 Vpn vpn = mVpns.get(userId); 3545 if (vpn != null) { 3546 return vpn.getVpnConfig(); 3547 } else { 3548 return null; 3549 } 3550 } 3551 } 3552 3553 @Override 3554 public boolean updateLockdownVpn() { 3555 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 3556 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM"); 3557 return false; 3558 } 3559 3560 // Tear down existing lockdown if profile was removed 3561 mLockdownEnabled = LockdownVpnTracker.isEnabled(); 3562 if (mLockdownEnabled) { 3563 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN)); 3564 final VpnProfile profile = VpnProfile.decode( 3565 profileName, mKeyStore.get(Credentials.VPN + profileName)); 3566 if (profile == null) { 3567 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName); 3568 setLockdownTracker(null); 3569 return true; 3570 } 3571 int user = UserHandle.getUserId(Binder.getCallingUid()); 3572 synchronized(mVpns) { 3573 Vpn vpn = mVpns.get(user); 3574 if (vpn == null) { 3575 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown"); 3576 return false; 3577 } 3578 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile)); 3579 } 3580 } else { 3581 setLockdownTracker(null); 3582 } 3583 3584 return true; 3585 } 3586 3587 /** 3588 * Internally set new {@link LockdownVpnTracker}, shutting down any existing 3589 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown. 3590 */ 3591 private void setLockdownTracker(LockdownVpnTracker tracker) { 3592 // Shutdown any existing tracker 3593 final LockdownVpnTracker existing = mLockdownTracker; 3594 mLockdownTracker = null; 3595 if (existing != null) { 3596 existing.shutdown(); 3597 } 3598 3599 try { 3600 if (tracker != null) { 3601 mNetd.setFirewallEnabled(true); 3602 mNetd.setFirewallInterfaceRule("lo", true); 3603 mLockdownTracker = tracker; 3604 mLockdownTracker.init(); 3605 } else { 3606 mNetd.setFirewallEnabled(false); 3607 } 3608 } catch (RemoteException e) { 3609 // ignored; NMS lives inside system_server 3610 } 3611 } 3612 3613 private void throwIfLockdownEnabled() { 3614 if (mLockdownEnabled) { 3615 throw new IllegalStateException("Unavailable in lockdown mode"); 3616 } 3617 } 3618 3619 /** 3620 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform 3621 * some setup and then call {@code establish()} to connect. 3622 * 3623 * @return {@code true} if the service was started, the service was already connected, or there 3624 * was no always-on VPN to start. {@code false} otherwise. 3625 */ 3626 private boolean startAlwaysOnVpn(int userId) { 3627 synchronized (mVpns) { 3628 Vpn vpn = mVpns.get(userId); 3629 if (vpn == null) { 3630 // Shouldn't happen as all codepaths that point here should have checked the Vpn 3631 // exists already. 3632 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration"); 3633 return false; 3634 } 3635 3636 return vpn.startAlwaysOnVpn(); 3637 } 3638 } 3639 3640 @Override 3641 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) { 3642 enforceConnectivityInternalPermission(); 3643 enforceCrossUserPermission(userId); 3644 3645 // Can't set always-on VPN if legacy VPN is already in lockdown mode. 3646 if (LockdownVpnTracker.isEnabled()) { 3647 return false; 3648 } 3649 3650 synchronized (mVpns) { 3651 Vpn vpn = mVpns.get(userId); 3652 if (vpn == null) { 3653 Slog.w(TAG, "User " + userId + " has no Vpn configuration"); 3654 return false; 3655 } 3656 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) { 3657 return false; 3658 } 3659 if (!startAlwaysOnVpn(userId)) { 3660 vpn.setAlwaysOnPackage(null, false); 3661 return false; 3662 } 3663 3664 vpn.saveAlwaysOnPackage(); 3665 } 3666 return true; 3667 } 3668 3669 @Override 3670 public String getAlwaysOnVpnPackage(int userId) { 3671 enforceConnectivityInternalPermission(); 3672 enforceCrossUserPermission(userId); 3673 3674 synchronized (mVpns) { 3675 Vpn vpn = mVpns.get(userId); 3676 if (vpn == null) { 3677 Slog.w(TAG, "User " + userId + " has no Vpn configuration"); 3678 return null; 3679 } 3680 return vpn.getAlwaysOnPackage(); 3681 } 3682 } 3683 3684 @Override 3685 public int checkMobileProvisioning(int suggestedTimeOutMs) { 3686 // TODO: Remove? Any reason to trigger a provisioning check? 3687 return -1; 3688 } 3689 3690 /** Location to an updatable file listing carrier provisioning urls. 3691 * An example: 3692 * 3693 * <?xml version="1.0" encoding="utf-8"?> 3694 * <provisioningUrls> 3695 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl> 3696 * </provisioningUrls> 3697 */ 3698 private static final String PROVISIONING_URL_PATH = 3699 "/data/misc/radio/provisioning_urls.xml"; 3700 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH); 3701 3702 /** XML tag for root element. */ 3703 private static final String TAG_PROVISIONING_URLS = "provisioningUrls"; 3704 /** XML tag for individual url */ 3705 private static final String TAG_PROVISIONING_URL = "provisioningUrl"; 3706 /** XML attribute for mcc */ 3707 private static final String ATTR_MCC = "mcc"; 3708 /** XML attribute for mnc */ 3709 private static final String ATTR_MNC = "mnc"; 3710 3711 private String getProvisioningUrlBaseFromFile() { 3712 FileReader fileReader = null; 3713 XmlPullParser parser = null; 3714 Configuration config = mContext.getResources().getConfiguration(); 3715 3716 try { 3717 fileReader = new FileReader(mProvisioningUrlFile); 3718 parser = Xml.newPullParser(); 3719 parser.setInput(fileReader); 3720 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS); 3721 3722 while (true) { 3723 XmlUtils.nextElement(parser); 3724 3725 String element = parser.getName(); 3726 if (element == null) break; 3727 3728 if (element.equals(TAG_PROVISIONING_URL)) { 3729 String mcc = parser.getAttributeValue(null, ATTR_MCC); 3730 try { 3731 if (mcc != null && Integer.parseInt(mcc) == config.mcc) { 3732 String mnc = parser.getAttributeValue(null, ATTR_MNC); 3733 if (mnc != null && Integer.parseInt(mnc) == config.mnc) { 3734 parser.next(); 3735 if (parser.getEventType() == XmlPullParser.TEXT) { 3736 return parser.getText(); 3737 } 3738 } 3739 } 3740 } catch (NumberFormatException e) { 3741 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e); 3742 } 3743 } 3744 } 3745 return null; 3746 } catch (FileNotFoundException e) { 3747 loge("Carrier Provisioning Urls file not found"); 3748 } catch (XmlPullParserException e) { 3749 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e); 3750 } catch (IOException e) { 3751 loge("I/O exception reading Carrier Provisioning Urls file: " + e); 3752 } finally { 3753 if (fileReader != null) { 3754 try { 3755 fileReader.close(); 3756 } catch (IOException e) {} 3757 } 3758 } 3759 return null; 3760 } 3761 3762 @Override 3763 public String getMobileProvisioningUrl() { 3764 enforceConnectivityInternalPermission(); 3765 String url = getProvisioningUrlBaseFromFile(); 3766 if (TextUtils.isEmpty(url)) { 3767 url = mContext.getResources().getString(R.string.mobile_provisioning_url); 3768 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url); 3769 } else { 3770 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url); 3771 } 3772 // populate the iccid, imei and phone number in the provisioning url. 3773 if (!TextUtils.isEmpty(url)) { 3774 String phoneNumber = mTelephonyManager.getLine1Number(); 3775 if (TextUtils.isEmpty(phoneNumber)) { 3776 phoneNumber = "0000000000"; 3777 } 3778 url = String.format(url, 3779 mTelephonyManager.getSimSerialNumber() /* ICCID */, 3780 mTelephonyManager.getDeviceId() /* IMEI */, 3781 phoneNumber /* Phone numer */); 3782 } 3783 3784 return url; 3785 } 3786 3787 @Override 3788 public void setProvisioningNotificationVisible(boolean visible, int networkType, 3789 String action) { 3790 enforceConnectivityInternalPermission(); 3791 final long ident = Binder.clearCallingIdentity(); 3792 try { 3793 // Concatenate the range of types onto the range of NetIDs. 3794 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE); 3795 mNotifier.setProvNotificationVisible(visible, id, action); 3796 } finally { 3797 Binder.restoreCallingIdentity(ident); 3798 } 3799 } 3800 3801 @Override 3802 public void setAirplaneMode(boolean enable) { 3803 enforceConnectivityInternalPermission(); 3804 final long ident = Binder.clearCallingIdentity(); 3805 try { 3806 final ContentResolver cr = mContext.getContentResolver(); 3807 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 3808 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 3809 intent.putExtra("state", enable); 3810 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 3811 } finally { 3812 Binder.restoreCallingIdentity(ident); 3813 } 3814 } 3815 3816 private void onUserStart(int userId) { 3817 synchronized(mVpns) { 3818 Vpn userVpn = mVpns.get(userId); 3819 if (userVpn != null) { 3820 loge("Starting user already has a VPN"); 3821 return; 3822 } 3823 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); 3824 mVpns.put(userId, userVpn); 3825 3826 final ContentResolver cr = mContext.getContentResolver(); 3827 String alwaysOnPackage = Settings.Secure.getStringForUser(cr, 3828 Settings.Secure.ALWAYS_ON_VPN_APP, userId); 3829 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr, 3830 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0; 3831 if (alwaysOnPackage != null) { 3832 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown); 3833 } 3834 } 3835 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) { 3836 updateLockdownVpn(); 3837 } 3838 } 3839 3840 private void onUserStop(int userId) { 3841 synchronized(mVpns) { 3842 Vpn userVpn = mVpns.get(userId); 3843 if (userVpn == null) { 3844 loge("Stopped user has no VPN"); 3845 return; 3846 } 3847 userVpn.onUserStopped(); 3848 mVpns.delete(userId); 3849 } 3850 } 3851 3852 private void onUserAdded(int userId) { 3853 synchronized(mVpns) { 3854 final int vpnsSize = mVpns.size(); 3855 for (int i = 0; i < vpnsSize; i++) { 3856 Vpn vpn = mVpns.valueAt(i); 3857 vpn.onUserAdded(userId); 3858 } 3859 } 3860 } 3861 3862 private void onUserRemoved(int userId) { 3863 synchronized(mVpns) { 3864 final int vpnsSize = mVpns.size(); 3865 for (int i = 0; i < vpnsSize; i++) { 3866 Vpn vpn = mVpns.valueAt(i); 3867 vpn.onUserRemoved(userId); 3868 } 3869 } 3870 } 3871 3872 private void onUserUnlocked(int userId) { 3873 // User present may be sent because of an unlock, which might mean an unlocked keystore. 3874 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) { 3875 updateLockdownVpn(); 3876 } else { 3877 startAlwaysOnVpn(userId); 3878 } 3879 } 3880 3881 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() { 3882 @Override 3883 public void onReceive(Context context, Intent intent) { 3884 final String action = intent.getAction(); 3885 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 3886 if (userId == UserHandle.USER_NULL) return; 3887 3888 if (Intent.ACTION_USER_STARTED.equals(action)) { 3889 onUserStart(userId); 3890 } else if (Intent.ACTION_USER_STOPPED.equals(action)) { 3891 onUserStop(userId); 3892 } else if (Intent.ACTION_USER_ADDED.equals(action)) { 3893 onUserAdded(userId); 3894 } else if (Intent.ACTION_USER_REMOVED.equals(action)) { 3895 onUserRemoved(userId); 3896 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) { 3897 onUserUnlocked(userId); 3898 } 3899 } 3900 }; 3901 3902 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = 3903 new HashMap<Messenger, NetworkFactoryInfo>(); 3904 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = 3905 new HashMap<NetworkRequest, NetworkRequestInfo>(); 3906 3907 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100; 3908 // Map from UID to number of NetworkRequests that UID has filed. 3909 @GuardedBy("mUidToNetworkRequestCount") 3910 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray(); 3911 3912 private static class NetworkFactoryInfo { 3913 public final String name; 3914 public final Messenger messenger; 3915 public final AsyncChannel asyncChannel; 3916 3917 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) { 3918 this.name = name; 3919 this.messenger = messenger; 3920 this.asyncChannel = asyncChannel; 3921 } 3922 } 3923 3924 private void ensureNetworkRequestHasType(NetworkRequest request) { 3925 if (request.type == NetworkRequest.Type.NONE) { 3926 throw new IllegalArgumentException( 3927 "All NetworkRequests in ConnectivityService must have a type"); 3928 } 3929 } 3930 3931 /** 3932 * Tracks info about the requester. 3933 * Also used to notice when the calling process dies so we can self-expire 3934 */ 3935 private class NetworkRequestInfo implements IBinder.DeathRecipient { 3936 final NetworkRequest request; 3937 final PendingIntent mPendingIntent; 3938 boolean mPendingIntentSent; 3939 private final IBinder mBinder; 3940 final int mPid; 3941 final int mUid; 3942 final Messenger messenger; 3943 3944 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) { 3945 request = r; 3946 ensureNetworkRequestHasType(request); 3947 mPendingIntent = pi; 3948 messenger = null; 3949 mBinder = null; 3950 mPid = getCallingPid(); 3951 mUid = getCallingUid(); 3952 enforceRequestCountLimit(); 3953 } 3954 3955 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) { 3956 super(); 3957 messenger = m; 3958 request = r; 3959 ensureNetworkRequestHasType(request); 3960 mBinder = binder; 3961 mPid = getCallingPid(); 3962 mUid = getCallingUid(); 3963 mPendingIntent = null; 3964 enforceRequestCountLimit(); 3965 3966 try { 3967 mBinder.linkToDeath(this, 0); 3968 } catch (RemoteException e) { 3969 binderDied(); 3970 } 3971 } 3972 3973 private void enforceRequestCountLimit() { 3974 synchronized (mUidToNetworkRequestCount) { 3975 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1; 3976 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) { 3977 throw new IllegalArgumentException("Too many NetworkRequests filed"); 3978 } 3979 mUidToNetworkRequestCount.put(mUid, networkRequests); 3980 } 3981 } 3982 3983 void unlinkDeathRecipient() { 3984 if (mBinder != null) { 3985 mBinder.unlinkToDeath(this, 0); 3986 } 3987 } 3988 3989 public void binderDied() { 3990 log("ConnectivityService NetworkRequestInfo binderDied(" + 3991 request + ", " + mBinder + ")"); 3992 releaseNetworkRequest(request); 3993 } 3994 3995 public String toString() { 3996 return "uid/pid:" + mUid + "/" + mPid + " " + request + 3997 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent); 3998 } 3999 } 4000 4001 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) { 4002 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability(); 4003 if (badCapability != null) { 4004 throw new IllegalArgumentException("Cannot request network with " + badCapability); 4005 } 4006 } 4007 4008 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) { 4009 final SortedSet<Integer> thresholds = new TreeSet(); 4010 synchronized (nai) { 4011 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 4012 if (nri.request.networkCapabilities.hasSignalStrength() && 4013 nai.satisfiesImmutableCapabilitiesOf(nri.request)) { 4014 thresholds.add(nri.request.networkCapabilities.getSignalStrength()); 4015 } 4016 } 4017 } 4018 return new ArrayList<Integer>(thresholds); 4019 } 4020 4021 private void updateSignalStrengthThresholds( 4022 NetworkAgentInfo nai, String reason, NetworkRequest request) { 4023 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai); 4024 Bundle thresholds = new Bundle(); 4025 thresholds.putIntegerArrayList("thresholds", thresholdsArray); 4026 4027 if (VDBG || (DBG && !"CONNECT".equals(reason))) { 4028 String detail; 4029 if (request != null && request.networkCapabilities.hasSignalStrength()) { 4030 detail = reason + " " + request.networkCapabilities.getSignalStrength(); 4031 } else { 4032 detail = reason; 4033 } 4034 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s", 4035 detail, Arrays.toString(thresholdsArray.toArray()), nai.name())); 4036 } 4037 4038 nai.asyncChannel.sendMessage( 4039 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS, 4040 0, 0, thresholds); 4041 } 4042 4043 @Override 4044 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities, 4045 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) { 4046 final NetworkRequest.Type type = (networkCapabilities == null) 4047 ? NetworkRequest.Type.TRACK_DEFAULT 4048 : NetworkRequest.Type.REQUEST; 4049 // If the requested networkCapabilities is null, take them instead from 4050 // the default network request. This allows callers to keep track of 4051 // the system default network. 4052 if (type == NetworkRequest.Type.TRACK_DEFAULT) { 4053 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities); 4054 enforceAccessPermission(); 4055 } else { 4056 networkCapabilities = new NetworkCapabilities(networkCapabilities); 4057 enforceNetworkRequestPermissions(networkCapabilities); 4058 // TODO: this is incorrect. We mark the request as metered or not depending on the state 4059 // of the app when the request is filed, but we never change the request if the app 4060 // changes network state. http://b/29964605 4061 enforceMeteredApnPolicy(networkCapabilities); 4062 } 4063 ensureRequestableCapabilities(networkCapabilities); 4064 4065 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) { 4066 throw new IllegalArgumentException("Bad timeout specified"); 4067 } 4068 4069 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER 4070 .equals(networkCapabilities.getNetworkSpecifier())) { 4071 throw new IllegalArgumentException("Invalid network specifier - must not be '" 4072 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'"); 4073 } 4074 4075 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType, 4076 nextNetworkRequestId(), type); 4077 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder); 4078 if (DBG) log("requestNetwork for " + nri); 4079 4080 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri)); 4081 if (timeoutMs > 0) { 4082 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST, 4083 nri), timeoutMs); 4084 } 4085 return networkRequest; 4086 } 4087 4088 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) { 4089 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) { 4090 enforceConnectivityRestrictedNetworksPermission(); 4091 } else { 4092 enforceChangePermission(); 4093 } 4094 } 4095 4096 @Override 4097 public boolean requestBandwidthUpdate(Network network) { 4098 enforceAccessPermission(); 4099 NetworkAgentInfo nai = null; 4100 if (network == null) { 4101 return false; 4102 } 4103 synchronized (mNetworkForNetId) { 4104 nai = mNetworkForNetId.get(network.netId); 4105 } 4106 if (nai != null) { 4107 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE); 4108 return true; 4109 } 4110 return false; 4111 } 4112 4113 private boolean isSystem(int uid) { 4114 return uid < Process.FIRST_APPLICATION_UID; 4115 } 4116 4117 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) { 4118 final int uid = Binder.getCallingUid(); 4119 if (isSystem(uid)) { 4120 return; 4121 } 4122 // if UID is restricted, don't allow them to bring up metered APNs 4123 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) { 4124 final int uidRules; 4125 synchronized(mRulesLock) { 4126 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL); 4127 } 4128 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0 4129 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) { 4130 // we could silently fail or we can filter the available nets to only give 4131 // them those they have access to. Chose the more useful option. 4132 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED); 4133 } 4134 } 4135 } 4136 4137 @Override 4138 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities, 4139 PendingIntent operation) { 4140 checkNotNull(operation, "PendingIntent cannot be null."); 4141 networkCapabilities = new NetworkCapabilities(networkCapabilities); 4142 enforceNetworkRequestPermissions(networkCapabilities); 4143 enforceMeteredApnPolicy(networkCapabilities); 4144 ensureRequestableCapabilities(networkCapabilities); 4145 4146 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE, 4147 nextNetworkRequestId(), NetworkRequest.Type.REQUEST); 4148 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation); 4149 if (DBG) log("pendingRequest for " + nri); 4150 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT, 4151 nri)); 4152 return networkRequest; 4153 } 4154 4155 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) { 4156 mHandler.sendMessageDelayed( 4157 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, 4158 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs); 4159 } 4160 4161 @Override 4162 public void releasePendingNetworkRequest(PendingIntent operation) { 4163 checkNotNull(operation, "PendingIntent cannot be null."); 4164 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, 4165 getCallingUid(), 0, operation)); 4166 } 4167 4168 // In order to implement the compatibility measure for pre-M apps that call 4169 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly, 4170 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork. 4171 // This ensures it has permission to do so. 4172 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) { 4173 if (nc == null) { 4174 return false; 4175 } 4176 int[] transportTypes = nc.getTransportTypes(); 4177 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) { 4178 return false; 4179 } 4180 try { 4181 mContext.enforceCallingOrSelfPermission( 4182 android.Manifest.permission.ACCESS_WIFI_STATE, 4183 "ConnectivityService"); 4184 } catch (SecurityException e) { 4185 return false; 4186 } 4187 return true; 4188 } 4189 4190 @Override 4191 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities, 4192 Messenger messenger, IBinder binder) { 4193 if (!hasWifiNetworkListenPermission(networkCapabilities)) { 4194 enforceAccessPermission(); 4195 } 4196 4197 NetworkRequest networkRequest = new NetworkRequest( 4198 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(), 4199 NetworkRequest.Type.LISTEN); 4200 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder); 4201 if (VDBG) log("listenForNetwork for " + nri); 4202 4203 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 4204 return networkRequest; 4205 } 4206 4207 @Override 4208 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities, 4209 PendingIntent operation) { 4210 checkNotNull(operation, "PendingIntent cannot be null."); 4211 if (!hasWifiNetworkListenPermission(networkCapabilities)) { 4212 enforceAccessPermission(); 4213 } 4214 4215 NetworkRequest networkRequest = new NetworkRequest( 4216 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(), 4217 NetworkRequest.Type.LISTEN); 4218 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation); 4219 if (VDBG) log("pendingListenForNetwork for " + nri); 4220 4221 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 4222 } 4223 4224 @Override 4225 public void requestLinkProperties(NetworkRequest networkRequest) { 4226 ensureNetworkRequestHasType(networkRequest); 4227 if (networkRequest.type == NetworkRequest.Type.LISTEN) return; 4228 mHandler.sendMessage(mHandler.obtainMessage( 4229 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest)); 4230 } 4231 4232 @Override 4233 public void requestNetworkCapabilities(NetworkRequest networkRequest) { 4234 ensureNetworkRequestHasType(networkRequest); 4235 if (networkRequest.type == NetworkRequest.Type.LISTEN) return; 4236 mHandler.sendMessage(mHandler.obtainMessage( 4237 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest)); 4238 } 4239 4240 @Override 4241 public void releaseNetworkRequest(NetworkRequest networkRequest) { 4242 ensureNetworkRequestHasType(networkRequest); 4243 mHandler.sendMessage(mHandler.obtainMessage( 4244 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest)); 4245 } 4246 4247 @Override 4248 public void registerNetworkFactory(Messenger messenger, String name) { 4249 enforceConnectivityInternalPermission(); 4250 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel()); 4251 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi)); 4252 } 4253 4254 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) { 4255 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name); 4256 mNetworkFactoryInfos.put(nfi.messenger, nfi); 4257 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger); 4258 } 4259 4260 @Override 4261 public void unregisterNetworkFactory(Messenger messenger) { 4262 enforceConnectivityInternalPermission(); 4263 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger)); 4264 } 4265 4266 private void handleUnregisterNetworkFactory(Messenger messenger) { 4267 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger); 4268 if (nfi == null) { 4269 loge("Failed to find Messenger in unregisterNetworkFactory"); 4270 return; 4271 } 4272 if (DBG) log("unregisterNetworkFactory for " + nfi.name); 4273 } 4274 4275 /** 4276 * NetworkAgentInfo supporting a request by requestId. 4277 * These have already been vetted (their Capabilities satisfy the request) 4278 * and the are the highest scored network available. 4279 * the are keyed off the Requests requestId. 4280 */ 4281 // TODO: Yikes, this is accessed on multiple threads: add synchronization. 4282 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = 4283 new SparseArray<NetworkAgentInfo>(); 4284 4285 // NOTE: Accessed on multiple threads, must be synchronized on itself. 4286 @GuardedBy("mNetworkForNetId") 4287 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = 4288 new SparseArray<NetworkAgentInfo>(); 4289 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId. 4290 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so 4291 // there may not be a strict 1:1 correlation between the two. 4292 @GuardedBy("mNetworkForNetId") 4293 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray(); 4294 4295 // NetworkAgentInfo keyed off its connecting messenger 4296 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays 4297 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump(). 4298 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = 4299 new HashMap<Messenger, NetworkAgentInfo>(); 4300 4301 @GuardedBy("mBlockedAppUids") 4302 private final HashSet<Integer> mBlockedAppUids = new HashSet(); 4303 4304 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated. 4305 private final NetworkRequest mDefaultRequest; 4306 4307 // Request used to optionally keep mobile data active even when higher 4308 // priority networks like Wi-Fi are active. 4309 private final NetworkRequest mDefaultMobileDataRequest; 4310 4311 private NetworkAgentInfo getDefaultNetwork() { 4312 return mNetworkForRequestId.get(mDefaultRequest.requestId); 4313 } 4314 4315 private boolean isDefaultNetwork(NetworkAgentInfo nai) { 4316 return nai == getDefaultNetwork(); 4317 } 4318 4319 private boolean isDefaultRequest(NetworkRequestInfo nri) { 4320 return nri.request.requestId == mDefaultRequest.requestId; 4321 } 4322 4323 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo, 4324 LinkProperties linkProperties, NetworkCapabilities networkCapabilities, 4325 int currentScore, NetworkMisc networkMisc) { 4326 enforceConnectivityInternalPermission(); 4327 4328 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network 4329 // satisfies mDefaultRequest. 4330 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), 4331 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties( 4332 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore, 4333 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this); 4334 synchronized (this) { 4335 nai.networkMonitor.systemReady = mSystemReady; 4336 } 4337 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network, 4338 networkInfo.getExtraInfo()); 4339 if (DBG) log("registerNetworkAgent " + nai); 4340 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai)); 4341 return nai.network.netId; 4342 } 4343 4344 private void handleRegisterNetworkAgent(NetworkAgentInfo na) { 4345 if (VDBG) log("Got NetworkAgent Messenger"); 4346 mNetworkAgentInfos.put(na.messenger, na); 4347 synchronized (mNetworkForNetId) { 4348 mNetworkForNetId.put(na.network.netId, na); 4349 } 4350 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger); 4351 NetworkInfo networkInfo = na.networkInfo; 4352 na.networkInfo = null; 4353 updateNetworkInfo(na, networkInfo); 4354 } 4355 4356 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) { 4357 LinkProperties newLp = networkAgent.linkProperties; 4358 int netId = networkAgent.network.netId; 4359 4360 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before 4361 // we do anything else, make sure its LinkProperties are accurate. 4362 if (networkAgent.clatd != null) { 4363 networkAgent.clatd.fixupLinkProperties(oldLp); 4364 } 4365 4366 updateInterfaces(newLp, oldLp, netId); 4367 updateMtu(newLp, oldLp); 4368 // TODO - figure out what to do for clat 4369// for (LinkProperties lp : newLp.getStackedLinks()) { 4370// updateMtu(lp, null); 4371// } 4372 updateTcpBufferSizes(networkAgent); 4373 4374 updateRoutes(newLp, oldLp, netId); 4375 updateDnses(newLp, oldLp, netId); 4376 4377 updateClat(newLp, oldLp, networkAgent); 4378 if (isDefaultNetwork(networkAgent)) { 4379 handleApplyDefaultProxy(newLp.getHttpProxy()); 4380 } else { 4381 updateProxy(newLp, oldLp, networkAgent); 4382 } 4383 // TODO - move this check to cover the whole function 4384 if (!Objects.equals(newLp, oldLp)) { 4385 notifyIfacesChangedForNetworkStats(); 4386 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED); 4387 } 4388 4389 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent); 4390 } 4391 4392 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) { 4393 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted(); 4394 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai); 4395 4396 if (!wasRunningClat && shouldRunClat) { 4397 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai); 4398 nai.clatd.start(); 4399 } else if (wasRunningClat && !shouldRunClat) { 4400 nai.clatd.stop(); 4401 } 4402 } 4403 4404 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) { 4405 CompareResult<String> interfaceDiff = new CompareResult<String>(); 4406 if (oldLp != null) { 4407 interfaceDiff = oldLp.compareAllInterfaceNames(newLp); 4408 } else if (newLp != null) { 4409 interfaceDiff.added = newLp.getAllInterfaceNames(); 4410 } 4411 for (String iface : interfaceDiff.added) { 4412 try { 4413 if (DBG) log("Adding iface " + iface + " to network " + netId); 4414 mNetd.addInterfaceToNetwork(iface, netId); 4415 } catch (Exception e) { 4416 loge("Exception adding interface: " + e); 4417 } 4418 } 4419 for (String iface : interfaceDiff.removed) { 4420 try { 4421 if (DBG) log("Removing iface " + iface + " from network " + netId); 4422 mNetd.removeInterfaceFromNetwork(iface, netId); 4423 } catch (Exception e) { 4424 loge("Exception removing interface: " + e); 4425 } 4426 } 4427 } 4428 4429 /** 4430 * Have netd update routes from oldLp to newLp. 4431 * @return true if routes changed between oldLp and newLp 4432 */ 4433 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) { 4434 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 4435 if (oldLp != null) { 4436 routeDiff = oldLp.compareAllRoutes(newLp); 4437 } else if (newLp != null) { 4438 routeDiff.added = newLp.getAllRoutes(); 4439 } 4440 4441 // add routes before removing old in case it helps with continuous connectivity 4442 4443 // do this twice, adding non-nexthop routes first, then routes they are dependent on 4444 for (RouteInfo route : routeDiff.added) { 4445 if (route.hasGateway()) continue; 4446 if (VDBG) log("Adding Route [" + route + "] to network " + netId); 4447 try { 4448 mNetd.addRoute(netId, route); 4449 } catch (Exception e) { 4450 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) { 4451 loge("Exception in addRoute for non-gateway: " + e); 4452 } 4453 } 4454 } 4455 for (RouteInfo route : routeDiff.added) { 4456 if (route.hasGateway() == false) continue; 4457 if (VDBG) log("Adding Route [" + route + "] to network " + netId); 4458 try { 4459 mNetd.addRoute(netId, route); 4460 } catch (Exception e) { 4461 if ((route.getGateway() instanceof Inet4Address) || VDBG) { 4462 loge("Exception in addRoute for gateway: " + e); 4463 } 4464 } 4465 } 4466 4467 for (RouteInfo route : routeDiff.removed) { 4468 if (VDBG) log("Removing Route [" + route + "] from network " + netId); 4469 try { 4470 mNetd.removeRoute(netId, route); 4471 } catch (Exception e) { 4472 loge("Exception in removeRoute: " + e); 4473 } 4474 } 4475 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty(); 4476 } 4477 4478 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) { 4479 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) { 4480 return; // no updating necessary 4481 } 4482 4483 Collection<InetAddress> dnses = newLp.getDnsServers(); 4484 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses); 4485 try { 4486 mNetd.setDnsConfigurationForNetwork( 4487 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains()); 4488 } catch (Exception e) { 4489 loge("Exception in setDnsConfigurationForNetwork: " + e); 4490 } 4491 final NetworkAgentInfo defaultNai = getDefaultNetwork(); 4492 if (defaultNai != null && defaultNai.network.netId == netId) { 4493 setDefaultDnsSystemProperties(dnses); 4494 } 4495 flushVmDnsCache(); 4496 } 4497 4498 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) { 4499 int last = 0; 4500 for (InetAddress dns : dnses) { 4501 ++last; 4502 String key = "net.dns" + last; 4503 String value = dns.getHostAddress(); 4504 SystemProperties.set(key, value); 4505 } 4506 for (int i = last + 1; i <= mNumDnsEntries; ++i) { 4507 String key = "net.dns" + i; 4508 SystemProperties.set(key, ""); 4509 } 4510 mNumDnsEntries = last; 4511 } 4512 4513 /** 4514 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities} 4515 * augmented with any stateful capabilities implied from {@code networkAgent} 4516 * (e.g., validated status and captive portal status). 4517 * 4518 * @param oldScore score of the network before any of the changes that prompted us 4519 * to call this function. 4520 * @param nai the network having its capabilities updated. 4521 * @param networkCapabilities the new network capabilities. 4522 */ 4523 private void updateCapabilities( 4524 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) { 4525 // Don't modify caller's NetworkCapabilities. 4526 networkCapabilities = new NetworkCapabilities(networkCapabilities); 4527 if (nai.lastValidated) { 4528 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED); 4529 } else { 4530 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED); 4531 } 4532 if (nai.lastCaptivePortalDetected) { 4533 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL); 4534 } else { 4535 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL); 4536 } 4537 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) { 4538 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) != 4539 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) { 4540 try { 4541 mNetd.setNetworkPermission(nai.network.netId, 4542 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ? 4543 null : NetworkManagementService.PERMISSION_SYSTEM); 4544 } catch (RemoteException e) { 4545 loge("Exception in setNetworkPermission: " + e); 4546 } 4547 } 4548 synchronized (nai) { 4549 nai.networkCapabilities = networkCapabilities; 4550 } 4551 rematchAllNetworksAndRequests(nai, oldScore); 4552 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED); 4553 } 4554 } 4555 4556 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) { 4557 for (int i = 0; i < nai.numNetworkRequests(); i++) { 4558 NetworkRequest nr = nai.requestAt(i); 4559 // Don't send listening requests to factories. b/17393458 4560 if (nr.isListen()) continue; 4561 sendUpdatedScoreToFactories(nr, nai.getCurrentScore()); 4562 } 4563 } 4564 4565 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) { 4566 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString()); 4567 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 4568 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0, 4569 networkRequest); 4570 } 4571 } 4572 4573 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent, 4574 int notificationType) { 4575 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) { 4576 Intent intent = new Intent(); 4577 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network); 4578 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request); 4579 nri.mPendingIntentSent = true; 4580 sendIntent(nri.mPendingIntent, intent); 4581 } 4582 // else not handled 4583 } 4584 4585 private void sendIntent(PendingIntent pendingIntent, Intent intent) { 4586 mPendingIntentWakeLock.acquire(); 4587 try { 4588 if (DBG) log("Sending " + pendingIntent); 4589 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */); 4590 } catch (PendingIntent.CanceledException e) { 4591 if (DBG) log(pendingIntent + " was not sent, it had been canceled."); 4592 mPendingIntentWakeLock.release(); 4593 releasePendingNetworkRequest(pendingIntent); 4594 } 4595 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished() 4596 } 4597 4598 @Override 4599 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, 4600 String resultData, Bundle resultExtras) { 4601 if (DBG) log("Finished sending " + pendingIntent); 4602 mPendingIntentWakeLock.release(); 4603 // Release with a delay so the receiving client has an opportunity to put in its 4604 // own request. 4605 releasePendingNetworkRequestWithDelay(pendingIntent); 4606 } 4607 4608 private void callCallbackForRequest(NetworkRequestInfo nri, 4609 NetworkAgentInfo networkAgent, int notificationType, int arg1) { 4610 if (nri.messenger == null) return; // Default request has no msgr 4611 Bundle bundle = new Bundle(); 4612 bundle.putParcelable(NetworkRequest.class.getSimpleName(), 4613 new NetworkRequest(nri.request)); 4614 Message msg = Message.obtain(); 4615 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL && 4616 notificationType != ConnectivityManager.CALLBACK_RELEASED) { 4617 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network); 4618 } 4619 switch (notificationType) { 4620 case ConnectivityManager.CALLBACK_LOSING: { 4621 msg.arg1 = arg1; 4622 break; 4623 } 4624 case ConnectivityManager.CALLBACK_CAP_CHANGED: { 4625 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(), 4626 new NetworkCapabilities(networkAgent.networkCapabilities)); 4627 break; 4628 } 4629 case ConnectivityManager.CALLBACK_IP_CHANGED: { 4630 bundle.putParcelable(LinkProperties.class.getSimpleName(), 4631 new LinkProperties(networkAgent.linkProperties)); 4632 break; 4633 } 4634 } 4635 msg.what = notificationType; 4636 msg.setData(bundle); 4637 try { 4638 if (VDBG) { 4639 log("sending notification " + notifyTypeToName(notificationType) + 4640 " for " + nri.request); 4641 } 4642 nri.messenger.send(msg); 4643 } catch (RemoteException e) { 4644 // may occur naturally in the race of binder death. 4645 loge("RemoteException caught trying to send a callback msg for " + nri.request); 4646 } 4647 } 4648 4649 private void teardownUnneededNetwork(NetworkAgentInfo nai) { 4650 if (nai.numRequestNetworkRequests() != 0) { 4651 for (int i = 0; i < nai.numNetworkRequests(); i++) { 4652 NetworkRequest nr = nai.requestAt(i); 4653 // Ignore listening requests. 4654 if (nr.isListen()) continue; 4655 loge("Dead network still had at least " + nr); 4656 break; 4657 } 4658 } 4659 nai.asyncChannel.disconnect(); 4660 } 4661 4662 private void handleLingerComplete(NetworkAgentInfo oldNetwork) { 4663 if (oldNetwork == null) { 4664 loge("Unknown NetworkAgentInfo in handleLingerComplete"); 4665 return; 4666 } 4667 if (DBG) log("handleLingerComplete for " + oldNetwork.name()); 4668 4669 // If we get here it means that the last linger timeout for this network expired. So there 4670 // must be no other active linger timers, and we must stop lingering. 4671 oldNetwork.clearLingerState(); 4672 4673 if (unneeded(oldNetwork)) { 4674 teardownUnneededNetwork(oldNetwork); 4675 } 4676 } 4677 4678 private void makeDefault(NetworkAgentInfo newNetwork) { 4679 if (DBG) log("Switching to new default network: " + newNetwork); 4680 setupDataActivityTracking(newNetwork); 4681 try { 4682 mNetd.setDefaultNetId(newNetwork.network.netId); 4683 } catch (Exception e) { 4684 loge("Exception setting default network :" + e); 4685 } 4686 notifyLockdownVpn(newNetwork); 4687 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy()); 4688 updateTcpBufferSizes(newNetwork); 4689 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers()); 4690 } 4691 4692 // Handles a network appearing or improving its score. 4693 // 4694 // - Evaluates all current NetworkRequests that can be 4695 // satisfied by newNetwork, and reassigns to newNetwork 4696 // any such requests for which newNetwork is the best. 4697 // 4698 // - Lingers any validated Networks that as a result are no longer 4699 // needed. A network is needed if it is the best network for 4700 // one or more NetworkRequests, or if it is a VPN. 4701 // 4702 // - Tears down newNetwork if it just became validated 4703 // but turns out to be unneeded. 4704 // 4705 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated 4706 // networks that have no chance (i.e. even if validated) 4707 // of becoming the highest scoring network. 4708 // 4709 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy, 4710 // it does not remove NetworkRequests that other Networks could better satisfy. 4711 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}. 4712 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests} 4713 // as it performs better by a factor of the number of Networks. 4714 // 4715 // @param newNetwork is the network to be matched against NetworkRequests. 4716 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be 4717 // performed to tear down unvalidated networks that have no chance (i.e. even if 4718 // validated) of becoming the highest scoring network. 4719 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, 4720 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) { 4721 if (!newNetwork.everConnected) return; 4722 boolean keep = newNetwork.isVPN(); 4723 boolean isNewDefault = false; 4724 NetworkAgentInfo oldDefaultNetwork = null; 4725 if (VDBG) log("rematching " + newNetwork.name()); 4726 // Find and migrate to this Network any NetworkRequests for 4727 // which this network is now the best. 4728 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>(); 4729 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>(); 4730 if (VDBG) log(" network has: " + newNetwork.networkCapabilities); 4731 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 4732 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId); 4733 final boolean satisfies = newNetwork.satisfies(nri.request); 4734 if (newNetwork == currentNetwork && satisfies) { 4735 if (VDBG) { 4736 log("Network " + newNetwork.name() + " was already satisfying" + 4737 " request " + nri.request.requestId + ". No change."); 4738 } 4739 keep = true; 4740 continue; 4741 } 4742 4743 // check if it satisfies the NetworkCapabilities 4744 if (VDBG) log(" checking if request is satisfied: " + nri.request); 4745 if (satisfies) { 4746 if (nri.request.isListen()) { 4747 // This is not a request, it's a callback listener. 4748 // Add it to newNetwork regardless of score. 4749 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri); 4750 continue; 4751 } 4752 4753 // next check if it's better than any current network we're using for 4754 // this request 4755 if (VDBG) { 4756 log("currentScore = " + 4757 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) + 4758 ", newScore = " + newNetwork.getCurrentScore()); 4759 } 4760 if (currentNetwork == null || 4761 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) { 4762 if (VDBG) log("rematch for " + newNetwork.name()); 4763 if (currentNetwork != null) { 4764 if (VDBG) log(" accepting network in place of " + currentNetwork.name()); 4765 currentNetwork.removeRequest(nri.request.requestId); 4766 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs); 4767 affectedNetworks.add(currentNetwork); 4768 } else { 4769 if (VDBG) log(" accepting network in place of null"); 4770 } 4771 newNetwork.unlingerRequest(nri.request); 4772 mNetworkForRequestId.put(nri.request.requestId, newNetwork); 4773 if (!newNetwork.addRequest(nri.request)) { 4774 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request); 4775 } 4776 addedRequests.add(nri); 4777 keep = true; 4778 // Tell NetworkFactories about the new score, so they can stop 4779 // trying to connect if they know they cannot match it. 4780 // TODO - this could get expensive if we have alot of requests for this 4781 // network. Think about if there is a way to reduce this. Push 4782 // netid->request mapping to each factory? 4783 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore()); 4784 if (isDefaultRequest(nri)) { 4785 isNewDefault = true; 4786 oldDefaultNetwork = currentNetwork; 4787 if (currentNetwork != null) { 4788 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork); 4789 } 4790 } 4791 } 4792 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) { 4793 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri", 4794 // mark it as no longer satisfying "nri". Because networks are processed by 4795 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will 4796 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher 4797 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri". 4798 // This means this code doesn't have to handle the case where "currentNetwork" no 4799 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork". 4800 if (DBG) { 4801 log("Network " + newNetwork.name() + " stopped satisfying" + 4802 " request " + nri.request.requestId); 4803 } 4804 newNetwork.removeRequest(nri.request.requestId); 4805 if (currentNetwork == newNetwork) { 4806 mNetworkForRequestId.remove(nri.request.requestId); 4807 sendUpdatedScoreToFactories(nri.request, 0); 4808 } else { 4809 if (nri.request.isRequest()) { 4810 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " + 4811 newNetwork.name() + 4812 " without updating mNetworkForRequestId or factories!"); 4813 } 4814 } 4815 // TODO: technically, sending CALLBACK_LOST here is 4816 // incorrect if nri is a request (not a listen) and there 4817 // is a replacement network currently connected that can 4818 // satisfy it. However, the only capability that can both 4819 // a) be requested and b) change is NET_CAPABILITY_TRUSTED, 4820 // so this code is only incorrect for a network that loses 4821 // the TRUSTED capability, which is a rare case. 4822 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0); 4823 } 4824 } 4825 if (isNewDefault) { 4826 // Notify system services that this network is up. 4827 makeDefault(newNetwork); 4828 // Log 0 -> X and Y -> X default network transitions, where X is the new default. 4829 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork); 4830 synchronized (ConnectivityService.this) { 4831 // have a new default network, release the transition wakelock in 4832 // a second if it's held. The second pause is to allow apps 4833 // to reconnect over the new network 4834 if (mNetTransitionWakeLock.isHeld()) { 4835 mHandler.sendMessageDelayed(mHandler.obtainMessage( 4836 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 4837 mNetTransitionWakeLockSerialNumber, 0), 4838 1000); 4839 } 4840 } 4841 } 4842 4843 // do this after the default net is switched, but 4844 // before LegacyTypeTracker sends legacy broadcasts 4845 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri); 4846 4847 // Linger any networks that are no longer needed. This should be done after sending the 4848 // available callback for newNetwork. 4849 for (NetworkAgentInfo nai : affectedNetworks) { 4850 updateLingerState(nai, now); 4851 } 4852 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it 4853 // does not need to be done in any particular order. 4854 updateLingerState(newNetwork, now); 4855 4856 if (isNewDefault) { 4857 // Maintain the illusion: since the legacy API only 4858 // understands one network at a time, we must pretend 4859 // that the current default network disconnected before 4860 // the new one connected. 4861 if (oldDefaultNetwork != null) { 4862 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(), 4863 oldDefaultNetwork, true); 4864 } 4865 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0; 4866 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork); 4867 notifyLockdownVpn(newNetwork); 4868 } 4869 4870 if (keep) { 4871 // Notify battery stats service about this network, both the normal 4872 // interface and any stacked links. 4873 // TODO: Avoid redoing this; this must only be done once when a network comes online. 4874 try { 4875 final IBatteryStats bs = BatteryStatsService.getService(); 4876 final int type = newNetwork.networkInfo.getType(); 4877 4878 final String baseIface = newNetwork.linkProperties.getInterfaceName(); 4879 bs.noteNetworkInterfaceType(baseIface, type); 4880 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) { 4881 final String stackedIface = stacked.getInterfaceName(); 4882 bs.noteNetworkInterfaceType(stackedIface, type); 4883 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface); 4884 } 4885 } catch (RemoteException ignored) { 4886 } 4887 4888 // This has to happen after the notifyNetworkCallbacks as that tickles each 4889 // ConnectivityManager instance so that legacy requests correctly bind dns 4890 // requests to this network. The legacy users are listening for this bcast 4891 // and will generally do a dns request so they can ensureRouteToHost and if 4892 // they do that before the callbacks happen they'll use the default network. 4893 // 4894 // TODO: Is there still a race here? We send the broadcast 4895 // after sending the callback, but if the app can receive the 4896 // broadcast before the callback, it might still break. 4897 // 4898 // This *does* introduce a race where if the user uses the new api 4899 // (notification callbacks) and then uses the old api (getNetworkInfo(type)) 4900 // they may get old info. Reverse this after the old startUsing api is removed. 4901 // This is on top of the multiple intent sequencing referenced in the todo above. 4902 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) { 4903 NetworkRequest nr = newNetwork.requestAt(i); 4904 if (nr.legacyType != TYPE_NONE && nr.isRequest()) { 4905 // legacy type tracker filters out repeat adds 4906 mLegacyTypeTracker.add(nr.legacyType, newNetwork); 4907 } 4908 } 4909 4910 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above, 4911 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest 4912 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the 4913 // newNetwork to the tracker explicitly (it's a no-op if it has already been added). 4914 if (newNetwork.isVPN()) { 4915 mLegacyTypeTracker.add(TYPE_VPN, newNetwork); 4916 } 4917 } 4918 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) { 4919 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 4920 if (unneeded(nai)) { 4921 if (nai.getLingerExpiry() > 0) { 4922 // This network has active linger timers and no requests, but is not 4923 // lingering. Linger it. 4924 // 4925 // One way (the only way?) this can happen if this network is unvalidated 4926 // and became unneeded due to another network improving its score to the 4927 // point where this network will no longer be able to satisfy any requests 4928 // even if it validates. 4929 updateLingerState(nai, now); 4930 } else { 4931 if (DBG) log("Reaping " + nai.name()); 4932 teardownUnneededNetwork(nai); 4933 } 4934 } 4935 } 4936 } 4937 } 4938 4939 /** 4940 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks 4941 * being disconnected. 4942 * @param changed If only one Network's score or capabilities have been modified since the last 4943 * time this function was called, pass this Network in this argument, otherwise pass 4944 * null. 4945 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not 4946 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via 4947 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if 4948 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a 4949 * network's score. 4950 */ 4951 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) { 4952 // TODO: This may get slow. The "changed" parameter is provided for future optimization 4953 // to avoid the slowness. It is not simply enough to process just "changed", for 4954 // example in the case where "changed"'s score decreases and another network should begin 4955 // satifying a NetworkRequest that "changed" currently satisfies. 4956 4957 // Optimization: Only reprocess "changed" if its score improved. This is safe because it 4958 // can only add more NetworkRequests satisfied by "changed", and this is exactly what 4959 // rematchNetworkAndRequests() handles. 4960 final long now = SystemClock.elapsedRealtime(); 4961 if (changed != null && oldScore < changed.getCurrentScore()) { 4962 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now); 4963 } else { 4964 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray( 4965 new NetworkAgentInfo[mNetworkAgentInfos.size()]); 4966 // Rematch higher scoring networks first to prevent requests first matching a lower 4967 // scoring network and then a higher scoring network, which could produce multiple 4968 // callbacks and inadvertently unlinger networks. 4969 Arrays.sort(nais); 4970 for (NetworkAgentInfo nai : nais) { 4971 rematchNetworkAndRequests(nai, 4972 // Only reap the last time through the loop. Reaping before all rematching 4973 // is complete could incorrectly teardown a network that hasn't yet been 4974 // rematched. 4975 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP 4976 : ReapUnvalidatedNetworks.REAP, 4977 now); 4978 } 4979 } 4980 } 4981 4982 private void updateInetCondition(NetworkAgentInfo nai) { 4983 // Don't bother updating until we've graduated to validated at least once. 4984 if (!nai.everValidated) return; 4985 // For now only update icons for default connection. 4986 // TODO: Update WiFi and cellular icons separately. b/17237507 4987 if (!isDefaultNetwork(nai)) return; 4988 4989 int newInetCondition = nai.lastValidated ? 100 : 0; 4990 // Don't repeat publish. 4991 if (newInetCondition == mDefaultInetConditionPublished) return; 4992 4993 mDefaultInetConditionPublished = newInetCondition; 4994 sendInetConditionBroadcast(nai.networkInfo); 4995 } 4996 4997 private void notifyLockdownVpn(NetworkAgentInfo nai) { 4998 if (mLockdownTracker != null) { 4999 if (nai != null && nai.isVPN()) { 5000 mLockdownTracker.onVpnStateChanged(nai.networkInfo); 5001 } else { 5002 mLockdownTracker.onNetworkInfoChanged(); 5003 } 5004 } 5005 } 5006 5007 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) { 5008 NetworkInfo.State state = newInfo.getState(); 5009 NetworkInfo oldInfo = null; 5010 final int oldScore = networkAgent.getCurrentScore(); 5011 synchronized (networkAgent) { 5012 oldInfo = networkAgent.networkInfo; 5013 networkAgent.networkInfo = newInfo; 5014 } 5015 notifyLockdownVpn(networkAgent); 5016 5017 if (oldInfo != null && oldInfo.getState() == state) { 5018 if (oldInfo.isRoaming() != newInfo.isRoaming()) { 5019 if (VDBG) log("roaming status changed, notifying NetworkStatsService"); 5020 notifyIfacesChangedForNetworkStats(); 5021 } else if (VDBG) log("ignoring duplicate network state non-change"); 5022 // In either case, no further work should be needed. 5023 return; 5024 } 5025 if (DBG) { 5026 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " + 5027 (oldInfo == null ? "null" : oldInfo.getState()) + 5028 " to " + state); 5029 } 5030 5031 if (!networkAgent.created 5032 && (state == NetworkInfo.State.CONNECTED 5033 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) { 5034 try { 5035 // This should never fail. Specifying an already in use NetID will cause failure. 5036 if (networkAgent.isVPN()) { 5037 mNetd.createVirtualNetwork(networkAgent.network.netId, 5038 !networkAgent.linkProperties.getDnsServers().isEmpty(), 5039 (networkAgent.networkMisc == null || 5040 !networkAgent.networkMisc.allowBypass)); 5041 } else { 5042 mNetd.createPhysicalNetwork(networkAgent.network.netId, 5043 networkAgent.networkCapabilities.hasCapability( 5044 NET_CAPABILITY_NOT_RESTRICTED) ? 5045 null : NetworkManagementService.PERMISSION_SYSTEM); 5046 } 5047 } catch (Exception e) { 5048 loge("Error creating network " + networkAgent.network.netId + ": " 5049 + e.getMessage()); 5050 return; 5051 } 5052 networkAgent.created = true; 5053 } 5054 5055 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) { 5056 networkAgent.everConnected = true; 5057 5058 updateLinkProperties(networkAgent, null); 5059 notifyIfacesChangedForNetworkStats(); 5060 5061 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 5062 scheduleUnvalidatedPrompt(networkAgent); 5063 5064 if (networkAgent.isVPN()) { 5065 // Temporarily disable the default proxy (not global). 5066 synchronized (mProxyLock) { 5067 if (!mDefaultProxyDisabled) { 5068 mDefaultProxyDisabled = true; 5069 if (mGlobalProxy == null && mDefaultProxy != null) { 5070 sendProxyBroadcast(null); 5071 } 5072 } 5073 } 5074 // TODO: support proxy per network. 5075 } 5076 5077 // Whether a particular NetworkRequest listen should cause signal strength thresholds to 5078 // be communicated to a particular NetworkAgent depends only on the network's immutable, 5079 // capabilities, so it only needs to be done once on initial connect, not every time the 5080 // network's capabilities change. Note that we do this before rematching the network, 5081 // so we could decide to tear it down immediately afterwards. That's fine though - on 5082 // disconnection NetworkAgents should stop any signal strength monitoring they have been 5083 // doing. 5084 updateSignalStrengthThresholds(networkAgent, "CONNECT", null); 5085 5086 // Consider network even though it is not yet validated. 5087 final long now = SystemClock.elapsedRealtime(); 5088 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now); 5089 5090 // This has to happen after matching the requests, because callbacks are just requests. 5091 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK); 5092 } else if (state == NetworkInfo.State.DISCONNECTED) { 5093 networkAgent.asyncChannel.disconnect(); 5094 if (networkAgent.isVPN()) { 5095 synchronized (mProxyLock) { 5096 if (mDefaultProxyDisabled) { 5097 mDefaultProxyDisabled = false; 5098 if (mGlobalProxy == null && mDefaultProxy != null) { 5099 sendProxyBroadcast(mDefaultProxy); 5100 } 5101 } 5102 } 5103 } 5104 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) || 5105 state == NetworkInfo.State.SUSPENDED) { 5106 // going into or coming out of SUSPEND: rescore and notify 5107 if (networkAgent.getCurrentScore() != oldScore) { 5108 rematchAllNetworksAndRequests(networkAgent, oldScore); 5109 } 5110 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ? 5111 ConnectivityManager.CALLBACK_SUSPENDED : 5112 ConnectivityManager.CALLBACK_RESUMED)); 5113 mLegacyTypeTracker.update(networkAgent); 5114 } 5115 } 5116 5117 private void updateNetworkScore(NetworkAgentInfo nai, int score) { 5118 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score); 5119 if (score < 0) { 5120 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score + 5121 "). Bumping score to min of 0"); 5122 score = 0; 5123 } 5124 5125 final int oldScore = nai.getCurrentScore(); 5126 nai.setCurrentScore(score); 5127 5128 rematchAllNetworksAndRequests(nai, oldScore); 5129 5130 sendUpdatedScoreToFactories(nai); 5131 } 5132 5133 // notify only this one new request of the current state 5134 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) { 5135 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE; 5136 if (nri.mPendingIntent == null) { 5137 callCallbackForRequest(nri, nai, notifyType, 0); 5138 } else { 5139 sendPendingIntentForRequest(nri, nai, notifyType); 5140 } 5141 } 5142 5143 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) { 5144 // The NetworkInfo we actually send out has no bearing on the real 5145 // state of affairs. For example, if the default connection is mobile, 5146 // and a request for HIPRI has just gone away, we need to pretend that 5147 // HIPRI has just disconnected. So we need to set the type to HIPRI and 5148 // the state to DISCONNECTED, even though the network is of type MOBILE 5149 // and is still connected. 5150 NetworkInfo info = new NetworkInfo(nai.networkInfo); 5151 info.setType(type); 5152 if (state != DetailedState.DISCONNECTED) { 5153 info.setDetailedState(state, null, info.getExtraInfo()); 5154 sendConnectedBroadcast(info); 5155 } else { 5156 info.setDetailedState(state, info.getReason(), info.getExtraInfo()); 5157 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 5158 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 5159 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 5160 if (info.isFailover()) { 5161 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 5162 nai.networkInfo.setFailover(false); 5163 } 5164 if (info.getReason() != null) { 5165 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 5166 } 5167 if (info.getExtraInfo() != null) { 5168 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo()); 5169 } 5170 NetworkAgentInfo newDefaultAgent = null; 5171 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) { 5172 newDefaultAgent = getDefaultNetwork(); 5173 if (newDefaultAgent != null) { 5174 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, 5175 newDefaultAgent.networkInfo); 5176 } else { 5177 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 5178 } 5179 } 5180 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, 5181 mDefaultInetConditionPublished); 5182 sendStickyBroadcast(intent); 5183 if (newDefaultAgent != null) { 5184 sendConnectedBroadcast(newDefaultAgent.networkInfo); 5185 } 5186 } 5187 } 5188 5189 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) { 5190 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name()); 5191 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) { 5192 NetworkRequest nr = networkAgent.requestAt(i); 5193 NetworkRequestInfo nri = mNetworkRequests.get(nr); 5194 if (VDBG) log(" sending notification for " + nr); 5195 if (nri.mPendingIntent == null) { 5196 callCallbackForRequest(nri, networkAgent, notifyType, arg1); 5197 } else { 5198 sendPendingIntentForRequest(nri, networkAgent, notifyType); 5199 } 5200 } 5201 } 5202 5203 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) { 5204 notifyNetworkCallbacks(networkAgent, notifyType, 0); 5205 } 5206 5207 private String notifyTypeToName(int notifyType) { 5208 switch (notifyType) { 5209 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK"; 5210 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE"; 5211 case ConnectivityManager.CALLBACK_LOSING: return "LOSING"; 5212 case ConnectivityManager.CALLBACK_LOST: return "LOST"; 5213 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE"; 5214 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED"; 5215 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED"; 5216 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED"; 5217 } 5218 return "UNKNOWN"; 5219 } 5220 5221 /** 5222 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the 5223 * properties tracked by NetworkStatsService on an active iface has changed. 5224 */ 5225 private void notifyIfacesChangedForNetworkStats() { 5226 try { 5227 mStatsService.forceUpdateIfaces(); 5228 } catch (Exception ignored) { 5229 } 5230 } 5231 5232 @Override 5233 public boolean addVpnAddress(String address, int prefixLength) { 5234 throwIfLockdownEnabled(); 5235 int user = UserHandle.getUserId(Binder.getCallingUid()); 5236 synchronized (mVpns) { 5237 return mVpns.get(user).addAddress(address, prefixLength); 5238 } 5239 } 5240 5241 @Override 5242 public boolean removeVpnAddress(String address, int prefixLength) { 5243 throwIfLockdownEnabled(); 5244 int user = UserHandle.getUserId(Binder.getCallingUid()); 5245 synchronized (mVpns) { 5246 return mVpns.get(user).removeAddress(address, prefixLength); 5247 } 5248 } 5249 5250 @Override 5251 public boolean setUnderlyingNetworksForVpn(Network[] networks) { 5252 throwIfLockdownEnabled(); 5253 int user = UserHandle.getUserId(Binder.getCallingUid()); 5254 boolean success; 5255 synchronized (mVpns) { 5256 success = mVpns.get(user).setUnderlyingNetworks(networks); 5257 } 5258 if (success) { 5259 notifyIfacesChangedForNetworkStats(); 5260 } 5261 return success; 5262 } 5263 5264 @Override 5265 public String getCaptivePortalServerUrl() { 5266 return NetworkMonitor.getCaptivePortalServerUrl(mContext); 5267 } 5268 5269 @Override 5270 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger, 5271 IBinder binder, String srcAddr, int srcPort, String dstAddr) { 5272 enforceKeepalivePermission(); 5273 mKeepaliveTracker.startNattKeepalive( 5274 getNetworkAgentInfoForNetwork(network), 5275 intervalSeconds, messenger, binder, 5276 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT); 5277 } 5278 5279 @Override 5280 public void stopKeepalive(Network network, int slot) { 5281 mHandler.sendMessage(mHandler.obtainMessage( 5282 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network)); 5283 } 5284 5285 @Override 5286 public void factoryReset() { 5287 enforceConnectivityInternalPermission(); 5288 5289 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) { 5290 return; 5291 } 5292 5293 final int userId = UserHandle.getCallingUserId(); 5294 5295 // Turn airplane mode off 5296 setAirplaneMode(false); 5297 5298 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) { 5299 // Untether 5300 for (String tether : getTetheredIfaces()) { 5301 untether(tether); 5302 } 5303 } 5304 5305 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) { 5306 // Remove always-on package 5307 synchronized (mVpns) { 5308 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId); 5309 if (alwaysOnPackage != null) { 5310 setAlwaysOnVpnPackage(userId, null, false); 5311 setVpnPackageAuthorization(alwaysOnPackage, userId, false); 5312 } 5313 } 5314 5315 // Turn VPN off 5316 VpnConfig vpnConfig = getVpnConfig(userId); 5317 if (vpnConfig != null) { 5318 if (vpnConfig.legacy) { 5319 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId); 5320 } else { 5321 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections 5322 // in the future without user intervention. 5323 setVpnPackageAuthorization(vpnConfig.user, userId, false); 5324 5325 prepareVpn(null, VpnConfig.LEGACY_VPN, userId); 5326 } 5327 } 5328 } 5329 5330 Settings.Global.putString(mContext.getContentResolver(), 5331 Settings.Global.NETWORK_AVOID_BAD_WIFI, null); 5332 } 5333 5334 @VisibleForTesting 5335 public NetworkMonitor createNetworkMonitor(Context context, Handler handler, 5336 NetworkAgentInfo nai, NetworkRequest defaultRequest) { 5337 return new NetworkMonitor(context, handler, nai, defaultRequest); 5338 } 5339 5340 @VisibleForTesting 5341 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) { 5342 return new WakeupMessage(c, h, s, cmd, 0, 0, obj); 5343 } 5344 5345 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) { 5346 int newNetid = NETID_UNSET; 5347 int prevNetid = NETID_UNSET; 5348 int[] transports = new int[0]; 5349 boolean hadIPv4 = false; 5350 boolean hadIPv6 = false; 5351 5352 if (newNai != null) { 5353 newNetid = newNai.network.netId; 5354 transports = newNai.networkCapabilities.getTransportTypes(); 5355 } 5356 if (prevNai != null) { 5357 prevNetid = prevNai.network.netId; 5358 final LinkProperties lp = prevNai.linkProperties; 5359 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute(); 5360 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute(); 5361 } 5362 5363 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6)); 5364 } 5365 5366 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) { 5367 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype)); 5368 } 5369} 5370