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