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