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