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