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