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