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