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