ConnectivityService.java revision 767708db54edbdb26e166157fa05966769a629cc
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.numNetworkRequests(); i++) { 1908 pw.println(nai.requestAt(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.numNetworkRequests()); 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.numNetworkRequests(); i++) { 2306 NetworkRequest request = nai.requestAt(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.isSatisfyingRequest(mDefaultRequest.requestId)) { 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.isSatisfyingRequest(nri.request.requestId) || 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.isSatisfyingRequest(nri.request.requestId)) { 2452 nai.removeRequest(nri.request.requestId); 2453 if (VDBG) { 2454 log(" Removing from current network " + nai.name() + 2455 ", leaving " + nai.numNetworkRequests() + " requests."); 2456 } 2457 if (unneeded(nai)) { 2458 if (DBG) log("no live requests for " + nai.name() + "; disconnecting"); 2459 teardownUnneededNetwork(nai); 2460 } else { 2461 // suspect there should only be one pass through here 2462 // but if any were kept do the check below 2463 wasKept |= true; 2464 } 2465 } 2466 } 2467 2468 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId); 2469 if (nai != null) { 2470 mNetworkForRequestId.remove(nri.request.requestId); 2471 } 2472 // Maintain the illusion. When this request arrived, we might have pretended 2473 // that a network connected to serve it, even though the network was already 2474 // connected. Now that this request has gone away, we might have to pretend 2475 // that the network disconnected. LegacyTypeTracker will generate that 2476 // phantom disconnect for this type. 2477 if (nri.request.legacyType != TYPE_NONE && nai != null) { 2478 boolean doRemove = true; 2479 if (wasKept) { 2480 // check if any of the remaining requests for this network are for the 2481 // same legacy type - if so, don't remove the nai 2482 for (int i = 0; i < nai.numNetworkRequests(); i++) { 2483 NetworkRequest otherRequest = nai.requestAt(i); 2484 if (otherRequest.legacyType == nri.request.legacyType && 2485 otherRequest.isRequest()) { 2486 if (DBG) log(" still have other legacy request - leaving"); 2487 doRemove = false; 2488 } 2489 } 2490 } 2491 2492 if (doRemove) { 2493 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false); 2494 } 2495 } 2496 2497 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 2498 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST, 2499 nri.request); 2500 } 2501 } else { 2502 // listens don't have a singular affectedNetwork. Check all networks to see 2503 // if this listen request applies and remove it. 2504 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2505 nai.removeRequest(nri.request.requestId); 2506 if (nri.request.networkCapabilities.hasSignalStrength() && 2507 nai.satisfiesImmutableCapabilitiesOf(nri.request)) { 2508 updateSignalStrengthThresholds(nai, "RELEASE", nri.request); 2509 } 2510 } 2511 } 2512 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED); 2513 } 2514 } 2515 2516 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) { 2517 enforceConnectivityInternalPermission(); 2518 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED, 2519 accept ? 1 : 0, always ? 1: 0, network)); 2520 } 2521 2522 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) { 2523 if (DBG) log("handleSetAcceptUnvalidated network=" + network + 2524 " accept=" + accept + " always=" + always); 2525 2526 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 2527 if (nai == null) { 2528 // Nothing to do. 2529 return; 2530 } 2531 2532 if (nai.everValidated) { 2533 // The network validated while the dialog box was up. Take no action. 2534 return; 2535 } 2536 2537 if (!nai.networkMisc.explicitlySelected) { 2538 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network"); 2539 } 2540 2541 if (accept != nai.networkMisc.acceptUnvalidated) { 2542 int oldScore = nai.getCurrentScore(); 2543 nai.networkMisc.acceptUnvalidated = accept; 2544 rematchAllNetworksAndRequests(nai, oldScore); 2545 sendUpdatedScoreToFactories(nai); 2546 } 2547 2548 if (always) { 2549 nai.asyncChannel.sendMessage( 2550 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0); 2551 } 2552 2553 if (!accept) { 2554 // Tell the NetworkAgent to not automatically reconnect to the network. 2555 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT); 2556 // Teardown the nework. 2557 teardownUnneededNetwork(nai); 2558 } 2559 2560 } 2561 2562 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) { 2563 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network); 2564 mHandler.sendMessageDelayed( 2565 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network), 2566 PROMPT_UNVALIDATED_DELAY_MS); 2567 } 2568 2569 private void handlePromptUnvalidated(Network network) { 2570 if (VDBG) log("handlePromptUnvalidated " + network); 2571 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 2572 2573 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if 2574 // we haven't already been told to switch to it regardless of whether it validated or not. 2575 // Also don't prompt on captive portals because we're already prompting the user to sign in. 2576 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected || 2577 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) { 2578 return; 2579 } 2580 2581 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED); 2582 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null)); 2583 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 2584 intent.setClassName("com.android.settings", 2585 "com.android.settings.wifi.WifiNoInternetDialog"); 2586 2587 PendingIntent pendingIntent = PendingIntent.getActivityAsUser( 2588 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT); 2589 2590 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET, 2591 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true); 2592 } 2593 2594 private class InternalHandler extends Handler { 2595 public InternalHandler(Looper looper) { 2596 super(looper); 2597 } 2598 2599 @Override 2600 public void handleMessage(Message msg) { 2601 switch (msg.what) { 2602 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK: 2603 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: { 2604 String causedBy = null; 2605 synchronized (ConnectivityService.this) { 2606 if (msg.arg1 == mNetTransitionWakeLockSerialNumber && 2607 mNetTransitionWakeLock.isHeld()) { 2608 mNetTransitionWakeLock.release(); 2609 causedBy = mNetTransitionWakeLockCausedBy; 2610 } else { 2611 break; 2612 } 2613 } 2614 if (VDBG) { 2615 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) { 2616 log("Failed to find a new network - expiring NetTransition Wakelock"); 2617 } else { 2618 log("NetTransition Wakelock (" + 2619 (causedBy == null ? "unknown" : causedBy) + 2620 " cleared because we found a replacement network"); 2621 } 2622 } 2623 break; 2624 } 2625 case EVENT_APPLY_GLOBAL_HTTP_PROXY: { 2626 handleDeprecatedGlobalHttpProxy(); 2627 break; 2628 } 2629 case EVENT_PROXY_HAS_CHANGED: { 2630 handleApplyDefaultProxy((ProxyInfo)msg.obj); 2631 break; 2632 } 2633 case EVENT_REGISTER_NETWORK_FACTORY: { 2634 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj); 2635 break; 2636 } 2637 case EVENT_UNREGISTER_NETWORK_FACTORY: { 2638 handleUnregisterNetworkFactory((Messenger)msg.obj); 2639 break; 2640 } 2641 case EVENT_REGISTER_NETWORK_AGENT: { 2642 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj); 2643 break; 2644 } 2645 case EVENT_REGISTER_NETWORK_REQUEST: 2646 case EVENT_REGISTER_NETWORK_LISTENER: { 2647 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj); 2648 break; 2649 } 2650 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: 2651 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: { 2652 handleRegisterNetworkRequestWithIntent(msg); 2653 break; 2654 } 2655 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: { 2656 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1); 2657 break; 2658 } 2659 case EVENT_RELEASE_NETWORK_REQUEST: { 2660 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1); 2661 break; 2662 } 2663 case EVENT_SET_ACCEPT_UNVALIDATED: { 2664 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0); 2665 break; 2666 } 2667 case EVENT_PROMPT_UNVALIDATED: { 2668 handlePromptUnvalidated((Network) msg.obj); 2669 break; 2670 } 2671 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: { 2672 handleMobileDataAlwaysOn(); 2673 break; 2674 } 2675 // Sent by KeepaliveTracker to process an app request on the state machine thread. 2676 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: { 2677 mKeepaliveTracker.handleStartKeepalive(msg); 2678 break; 2679 } 2680 // Sent by KeepaliveTracker to process an app request on the state machine thread. 2681 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: { 2682 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj); 2683 int slot = msg.arg1; 2684 int reason = msg.arg2; 2685 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason); 2686 break; 2687 } 2688 case EVENT_SYSTEM_READY: { 2689 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2690 nai.networkMonitor.systemReady = true; 2691 } 2692 break; 2693 } 2694 } 2695 } 2696 } 2697 2698 // javadoc from interface 2699 public int tether(String iface) { 2700 ConnectivityManager.enforceTetherChangePermission(mContext); 2701 if (isTetheringSupported()) { 2702 final int status = mTethering.tether(iface); 2703 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) { 2704 try { 2705 mPolicyManager.onTetheringChanged(iface, true); 2706 } catch (RemoteException e) { 2707 } 2708 } 2709 return status; 2710 } else { 2711 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2712 } 2713 } 2714 2715 // javadoc from interface 2716 public int untether(String iface) { 2717 ConnectivityManager.enforceTetherChangePermission(mContext); 2718 2719 if (isTetheringSupported()) { 2720 final int status = mTethering.untether(iface); 2721 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) { 2722 try { 2723 mPolicyManager.onTetheringChanged(iface, false); 2724 } catch (RemoteException e) { 2725 } 2726 } 2727 return status; 2728 } else { 2729 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2730 } 2731 } 2732 2733 // javadoc from interface 2734 public int getLastTetherError(String iface) { 2735 enforceTetherAccessPermission(); 2736 2737 if (isTetheringSupported()) { 2738 return mTethering.getLastTetherError(iface); 2739 } else { 2740 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2741 } 2742 } 2743 2744 // TODO - proper iface API for selection by property, inspection, etc 2745 public String[] getTetherableUsbRegexs() { 2746 enforceTetherAccessPermission(); 2747 if (isTetheringSupported()) { 2748 return mTethering.getTetherableUsbRegexs(); 2749 } else { 2750 return new String[0]; 2751 } 2752 } 2753 2754 public String[] getTetherableWifiRegexs() { 2755 enforceTetherAccessPermission(); 2756 if (isTetheringSupported()) { 2757 return mTethering.getTetherableWifiRegexs(); 2758 } else { 2759 return new String[0]; 2760 } 2761 } 2762 2763 public String[] getTetherableBluetoothRegexs() { 2764 enforceTetherAccessPermission(); 2765 if (isTetheringSupported()) { 2766 return mTethering.getTetherableBluetoothRegexs(); 2767 } else { 2768 return new String[0]; 2769 } 2770 } 2771 2772 public int setUsbTethering(boolean enable) { 2773 ConnectivityManager.enforceTetherChangePermission(mContext); 2774 if (isTetheringSupported()) { 2775 return mTethering.setUsbTethering(enable); 2776 } else { 2777 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2778 } 2779 } 2780 2781 // TODO - move iface listing, queries, etc to new module 2782 // javadoc from interface 2783 public String[] getTetherableIfaces() { 2784 enforceTetherAccessPermission(); 2785 return mTethering.getTetherableIfaces(); 2786 } 2787 2788 public String[] getTetheredIfaces() { 2789 enforceTetherAccessPermission(); 2790 return mTethering.getTetheredIfaces(); 2791 } 2792 2793 public String[] getTetheringErroredIfaces() { 2794 enforceTetherAccessPermission(); 2795 return mTethering.getErroredIfaces(); 2796 } 2797 2798 public String[] getTetheredDhcpRanges() { 2799 enforceConnectivityInternalPermission(); 2800 return mTethering.getTetheredDhcpRanges(); 2801 } 2802 2803 // if ro.tether.denied = true we default to no tethering 2804 // gservices could set the secure setting to 1 though to enable it on a build where it 2805 // had previously been turned off. 2806 @Override 2807 public boolean isTetheringSupported() { 2808 enforceTetherAccessPermission(); 2809 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 2810 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(), 2811 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0) 2812 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING); 2813 return tetherEnabledInSettings && mUserManager.isAdminUser() && 2814 ((mTethering.getTetherableUsbRegexs().length != 0 || 2815 mTethering.getTetherableWifiRegexs().length != 0 || 2816 mTethering.getTetherableBluetoothRegexs().length != 0) && 2817 mTethering.getUpstreamIfaceTypes().length != 0); 2818 } 2819 2820 @Override 2821 public void startTethering(int type, ResultReceiver receiver, 2822 boolean showProvisioningUi) { 2823 ConnectivityManager.enforceTetherChangePermission(mContext); 2824 if (!isTetheringSupported()) { 2825 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null); 2826 return; 2827 } 2828 mTethering.startTethering(type, receiver, showProvisioningUi); 2829 } 2830 2831 @Override 2832 public void stopTethering(int type) { 2833 ConnectivityManager.enforceTetherChangePermission(mContext); 2834 mTethering.stopTethering(type); 2835 } 2836 2837 // Called when we lose the default network and have no replacement yet. 2838 // This will automatically be cleared after X seconds or a new default network 2839 // becomes CONNECTED, whichever happens first. The timer is started by the 2840 // first caller and not restarted by subsequent callers. 2841 private void requestNetworkTransitionWakelock(String forWhom) { 2842 int serialNum = 0; 2843 synchronized (this) { 2844 if (mNetTransitionWakeLock.isHeld()) return; 2845 serialNum = ++mNetTransitionWakeLockSerialNumber; 2846 mNetTransitionWakeLock.acquire(); 2847 mNetTransitionWakeLockCausedBy = forWhom; 2848 } 2849 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2850 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0), 2851 mNetTransitionWakeLockTimeout); 2852 return; 2853 } 2854 2855 // 100 percent is full good, 0 is full bad. 2856 public void reportInetCondition(int networkType, int percentage) { 2857 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 2858 if (nai == null) return; 2859 reportNetworkConnectivity(nai.network, percentage > 50); 2860 } 2861 2862 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) { 2863 enforceAccessPermission(); 2864 enforceInternetPermission(); 2865 2866 NetworkAgentInfo nai; 2867 if (network == null) { 2868 nai = getDefaultNetwork(); 2869 } else { 2870 nai = getNetworkAgentInfoForNetwork(network); 2871 } 2872 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING || 2873 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) { 2874 return; 2875 } 2876 // Revalidate if the app report does not match our current validated state. 2877 if (hasConnectivity == nai.lastValidated) return; 2878 final int uid = Binder.getCallingUid(); 2879 if (DBG) { 2880 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity + 2881 ") by " + uid); 2882 } 2883 synchronized (nai) { 2884 // Validating a network that has not yet connected could result in a call to 2885 // rematchNetworkAndRequests() which is not meant to work on such networks. 2886 if (!nai.everConnected) return; 2887 2888 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return; 2889 2890 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid); 2891 } 2892 } 2893 2894 private ProxyInfo getDefaultProxy() { 2895 // this information is already available as a world read/writable jvm property 2896 // so this API change wouldn't have a benifit. It also breaks the passing 2897 // of proxy info to all the JVMs. 2898 // enforceAccessPermission(); 2899 synchronized (mProxyLock) { 2900 ProxyInfo ret = mGlobalProxy; 2901 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy; 2902 return ret; 2903 } 2904 } 2905 2906 public ProxyInfo getProxyForNetwork(Network network) { 2907 if (network == null) return getDefaultProxy(); 2908 final ProxyInfo globalProxy = getGlobalProxy(); 2909 if (globalProxy != null) return globalProxy; 2910 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null; 2911 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which 2912 // caller may not have. 2913 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 2914 if (nai == null) return null; 2915 synchronized (nai) { 2916 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy(); 2917 if (proxyInfo == null) return null; 2918 return new ProxyInfo(proxyInfo); 2919 } 2920 } 2921 2922 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present 2923 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific 2924 // proxy is null then there is no proxy in place). 2925 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) { 2926 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 2927 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) { 2928 proxy = null; 2929 } 2930 return proxy; 2931 } 2932 2933 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it 2934 // better for determining if a new proxy broadcast is necessary: 2935 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to 2936 // avoid unnecessary broadcasts. 2937 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL 2938 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler) 2939 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but 2940 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port 2941 // all set. 2942 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) { 2943 a = canonicalizeProxyInfo(a); 2944 b = canonicalizeProxyInfo(b); 2945 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check 2946 // hosts even when PAC URLs are present to account for the legacy PAC resolver. 2947 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost())); 2948 } 2949 2950 public void setGlobalProxy(ProxyInfo proxyProperties) { 2951 enforceConnectivityInternalPermission(); 2952 2953 synchronized (mProxyLock) { 2954 if (proxyProperties == mGlobalProxy) return; 2955 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return; 2956 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return; 2957 2958 String host = ""; 2959 int port = 0; 2960 String exclList = ""; 2961 String pacFileUrl = ""; 2962 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) || 2963 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) { 2964 if (!proxyProperties.isValid()) { 2965 if (DBG) 2966 log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 2967 return; 2968 } 2969 mGlobalProxy = new ProxyInfo(proxyProperties); 2970 host = mGlobalProxy.getHost(); 2971 port = mGlobalProxy.getPort(); 2972 exclList = mGlobalProxy.getExclusionListAsString(); 2973 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) { 2974 pacFileUrl = proxyProperties.getPacFileUrl().toString(); 2975 } 2976 } else { 2977 mGlobalProxy = null; 2978 } 2979 ContentResolver res = mContext.getContentResolver(); 2980 final long token = Binder.clearCallingIdentity(); 2981 try { 2982 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host); 2983 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port); 2984 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 2985 exclList); 2986 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl); 2987 } finally { 2988 Binder.restoreCallingIdentity(token); 2989 } 2990 2991 if (mGlobalProxy == null) { 2992 proxyProperties = mDefaultProxy; 2993 } 2994 sendProxyBroadcast(proxyProperties); 2995 } 2996 } 2997 2998 private void loadGlobalProxy() { 2999 ContentResolver res = mContext.getContentResolver(); 3000 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST); 3001 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0); 3002 String exclList = Settings.Global.getString(res, 3003 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST); 3004 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC); 3005 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) { 3006 ProxyInfo proxyProperties; 3007 if (!TextUtils.isEmpty(pacFileUrl)) { 3008 proxyProperties = new ProxyInfo(pacFileUrl); 3009 } else { 3010 proxyProperties = new ProxyInfo(host, port, exclList); 3011 } 3012 if (!proxyProperties.isValid()) { 3013 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3014 return; 3015 } 3016 3017 synchronized (mProxyLock) { 3018 mGlobalProxy = proxyProperties; 3019 } 3020 } 3021 } 3022 3023 public ProxyInfo getGlobalProxy() { 3024 // this information is already available as a world read/writable jvm property 3025 // so this API change wouldn't have a benifit. It also breaks the passing 3026 // of proxy info to all the JVMs. 3027 // enforceAccessPermission(); 3028 synchronized (mProxyLock) { 3029 return mGlobalProxy; 3030 } 3031 } 3032 3033 private void handleApplyDefaultProxy(ProxyInfo proxy) { 3034 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 3035 && Uri.EMPTY.equals(proxy.getPacFileUrl())) { 3036 proxy = null; 3037 } 3038 synchronized (mProxyLock) { 3039 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return; 3040 if (mDefaultProxy == proxy) return; // catches repeated nulls 3041 if (proxy != null && !proxy.isValid()) { 3042 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString()); 3043 return; 3044 } 3045 3046 // This call could be coming from the PacManager, containing the port of the local 3047 // proxy. If this new proxy matches the global proxy then copy this proxy to the 3048 // global (to get the correct local port), and send a broadcast. 3049 // TODO: Switch PacManager to have its own message to send back rather than 3050 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy. 3051 if ((mGlobalProxy != null) && (proxy != null) 3052 && (!Uri.EMPTY.equals(proxy.getPacFileUrl())) 3053 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) { 3054 mGlobalProxy = proxy; 3055 sendProxyBroadcast(mGlobalProxy); 3056 return; 3057 } 3058 mDefaultProxy = proxy; 3059 3060 if (mGlobalProxy != null) return; 3061 if (!mDefaultProxyDisabled) { 3062 sendProxyBroadcast(proxy); 3063 } 3064 } 3065 } 3066 3067 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy. 3068 // This method gets called when any network changes proxy, but the broadcast only ever contains 3069 // the default proxy (even if it hasn't changed). 3070 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network 3071 // world where an app might be bound to a non-default network. 3072 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) { 3073 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy(); 3074 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy(); 3075 3076 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) { 3077 sendProxyBroadcast(getDefaultProxy()); 3078 } 3079 } 3080 3081 private void handleDeprecatedGlobalHttpProxy() { 3082 String proxy = Settings.Global.getString(mContext.getContentResolver(), 3083 Settings.Global.HTTP_PROXY); 3084 if (!TextUtils.isEmpty(proxy)) { 3085 String data[] = proxy.split(":"); 3086 if (data.length == 0) { 3087 return; 3088 } 3089 3090 String proxyHost = data[0]; 3091 int proxyPort = 8080; 3092 if (data.length > 1) { 3093 try { 3094 proxyPort = Integer.parseInt(data[1]); 3095 } catch (NumberFormatException e) { 3096 return; 3097 } 3098 } 3099 ProxyInfo p = new ProxyInfo(data[0], proxyPort, ""); 3100 setGlobalProxy(p); 3101 } 3102 } 3103 3104 private void sendProxyBroadcast(ProxyInfo proxy) { 3105 if (proxy == null) proxy = new ProxyInfo("", 0, ""); 3106 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return; 3107 if (DBG) log("sending Proxy Broadcast for " + proxy); 3108 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); 3109 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 3110 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3111 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy); 3112 final long ident = Binder.clearCallingIdentity(); 3113 try { 3114 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 3115 } finally { 3116 Binder.restoreCallingIdentity(ident); 3117 } 3118 } 3119 3120 private static class SettingsObserver extends ContentObserver { 3121 final private HashMap<Uri, Integer> mUriEventMap; 3122 final private Context mContext; 3123 final private Handler mHandler; 3124 3125 SettingsObserver(Context context, Handler handler) { 3126 super(null); 3127 mUriEventMap = new HashMap<Uri, Integer>(); 3128 mContext = context; 3129 mHandler = handler; 3130 } 3131 3132 void observe(Uri uri, int what) { 3133 mUriEventMap.put(uri, what); 3134 final ContentResolver resolver = mContext.getContentResolver(); 3135 resolver.registerContentObserver(uri, false, this); 3136 } 3137 3138 @Override 3139 public void onChange(boolean selfChange) { 3140 Slog.wtf(TAG, "Should never be reached."); 3141 } 3142 3143 @Override 3144 public void onChange(boolean selfChange, Uri uri) { 3145 final Integer what = mUriEventMap.get(uri); 3146 if (what != null) { 3147 mHandler.obtainMessage(what.intValue()).sendToTarget(); 3148 } else { 3149 loge("No matching event to send for URI=" + uri); 3150 } 3151 } 3152 } 3153 3154 private static void log(String s) { 3155 Slog.d(TAG, s); 3156 } 3157 3158 private static void loge(String s) { 3159 Slog.e(TAG, s); 3160 } 3161 3162 private static <T> T checkNotNull(T value, String message) { 3163 if (value == null) { 3164 throw new NullPointerException(message); 3165 } 3166 return value; 3167 } 3168 3169 /** 3170 * Prepare for a VPN application. 3171 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId}, 3172 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required. 3173 * 3174 * @param oldPackage Package name of the application which currently controls VPN, which will 3175 * be replaced. If there is no such application, this should should either be 3176 * {@code null} or {@link VpnConfig.LEGACY_VPN}. 3177 * @param newPackage Package name of the application which should gain control of VPN, or 3178 * {@code null} to disable. 3179 * @param userId User for whom to prepare the new VPN. 3180 * 3181 * @hide 3182 */ 3183 @Override 3184 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage, 3185 int userId) { 3186 enforceCrossUserPermission(userId); 3187 throwIfLockdownEnabled(); 3188 3189 synchronized(mVpns) { 3190 Vpn vpn = mVpns.get(userId); 3191 if (vpn != null) { 3192 return vpn.prepare(oldPackage, newPackage); 3193 } else { 3194 return false; 3195 } 3196 } 3197 } 3198 3199 /** 3200 * Set whether the VPN package has the ability to launch VPNs without user intervention. 3201 * This method is used by system-privileged apps. 3202 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId}, 3203 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required. 3204 * 3205 * @param packageName The package for which authorization state should change. 3206 * @param userId User for whom {@code packageName} is installed. 3207 * @param authorized {@code true} if this app should be able to start a VPN connection without 3208 * explicit user approval, {@code false} if not. 3209 * 3210 * @hide 3211 */ 3212 @Override 3213 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) { 3214 enforceCrossUserPermission(userId); 3215 3216 synchronized(mVpns) { 3217 Vpn vpn = mVpns.get(userId); 3218 if (vpn != null) { 3219 vpn.setPackageAuthorization(packageName, authorized); 3220 } 3221 } 3222 } 3223 3224 /** 3225 * Configure a TUN interface and return its file descriptor. Parameters 3226 * are encoded and opaque to this class. This method is used by VpnBuilder 3227 * and not available in ConnectivityManager. Permissions are checked in 3228 * Vpn class. 3229 * @hide 3230 */ 3231 @Override 3232 public ParcelFileDescriptor establishVpn(VpnConfig config) { 3233 throwIfLockdownEnabled(); 3234 int user = UserHandle.getUserId(Binder.getCallingUid()); 3235 synchronized(mVpns) { 3236 return mVpns.get(user).establish(config); 3237 } 3238 } 3239 3240 /** 3241 * Start legacy VPN, controlling native daemons as needed. Creates a 3242 * secondary thread to perform connection work, returning quickly. 3243 */ 3244 @Override 3245 public void startLegacyVpn(VpnProfile profile) { 3246 throwIfLockdownEnabled(); 3247 final LinkProperties egress = getActiveLinkProperties(); 3248 if (egress == null) { 3249 throw new IllegalStateException("Missing active network connection"); 3250 } 3251 int user = UserHandle.getUserId(Binder.getCallingUid()); 3252 synchronized(mVpns) { 3253 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress); 3254 } 3255 } 3256 3257 /** 3258 * Return the information of the ongoing legacy VPN. This method is used 3259 * by VpnSettings and not available in ConnectivityManager. Permissions 3260 * are checked in Vpn class. 3261 */ 3262 @Override 3263 public LegacyVpnInfo getLegacyVpnInfo(int userId) { 3264 enforceCrossUserPermission(userId); 3265 3266 synchronized(mVpns) { 3267 return mVpns.get(userId).getLegacyVpnInfo(); 3268 } 3269 } 3270 3271 /** 3272 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService 3273 * and not available in ConnectivityManager. 3274 */ 3275 @Override 3276 public VpnInfo[] getAllVpnInfo() { 3277 enforceConnectivityInternalPermission(); 3278 if (mLockdownEnabled) { 3279 return new VpnInfo[0]; 3280 } 3281 3282 synchronized(mVpns) { 3283 List<VpnInfo> infoList = new ArrayList<>(); 3284 for (int i = 0; i < mVpns.size(); i++) { 3285 VpnInfo info = createVpnInfo(mVpns.valueAt(i)); 3286 if (info != null) { 3287 infoList.add(info); 3288 } 3289 } 3290 return infoList.toArray(new VpnInfo[infoList.size()]); 3291 } 3292 } 3293 3294 /** 3295 * @return VPN information for accounting, or null if we can't retrieve all required 3296 * information, e.g primary underlying iface. 3297 */ 3298 @Nullable 3299 private VpnInfo createVpnInfo(Vpn vpn) { 3300 VpnInfo info = vpn.getVpnInfo(); 3301 if (info == null) { 3302 return null; 3303 } 3304 Network[] underlyingNetworks = vpn.getUnderlyingNetworks(); 3305 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret 3306 // the underlyingNetworks list. 3307 if (underlyingNetworks == null) { 3308 NetworkAgentInfo defaultNetwork = getDefaultNetwork(); 3309 if (defaultNetwork != null && defaultNetwork.linkProperties != null) { 3310 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName(); 3311 } 3312 } else if (underlyingNetworks.length > 0) { 3313 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]); 3314 if (linkProperties != null) { 3315 info.primaryUnderlyingIface = linkProperties.getInterfaceName(); 3316 } 3317 } 3318 return info.primaryUnderlyingIface == null ? null : info; 3319 } 3320 3321 /** 3322 * Returns the information of the ongoing VPN for {@code userId}. This method is used by 3323 * VpnDialogs and not available in ConnectivityManager. 3324 * Permissions are checked in Vpn class. 3325 * @hide 3326 */ 3327 @Override 3328 public VpnConfig getVpnConfig(int userId) { 3329 enforceCrossUserPermission(userId); 3330 synchronized(mVpns) { 3331 Vpn vpn = mVpns.get(userId); 3332 if (vpn != null) { 3333 return vpn.getVpnConfig(); 3334 } else { 3335 return null; 3336 } 3337 } 3338 } 3339 3340 @Override 3341 public boolean updateLockdownVpn() { 3342 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 3343 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM"); 3344 return false; 3345 } 3346 3347 // Tear down existing lockdown if profile was removed 3348 mLockdownEnabled = LockdownVpnTracker.isEnabled(); 3349 if (mLockdownEnabled) { 3350 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN)); 3351 final VpnProfile profile = VpnProfile.decode( 3352 profileName, mKeyStore.get(Credentials.VPN + profileName)); 3353 if (profile == null) { 3354 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName); 3355 setLockdownTracker(null); 3356 return true; 3357 } 3358 int user = UserHandle.getUserId(Binder.getCallingUid()); 3359 synchronized(mVpns) { 3360 Vpn vpn = mVpns.get(user); 3361 if (vpn == null) { 3362 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown"); 3363 return false; 3364 } 3365 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile)); 3366 } 3367 } else { 3368 setLockdownTracker(null); 3369 } 3370 3371 return true; 3372 } 3373 3374 /** 3375 * Internally set new {@link LockdownVpnTracker}, shutting down any existing 3376 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown. 3377 */ 3378 private void setLockdownTracker(LockdownVpnTracker tracker) { 3379 // Shutdown any existing tracker 3380 final LockdownVpnTracker existing = mLockdownTracker; 3381 mLockdownTracker = null; 3382 if (existing != null) { 3383 existing.shutdown(); 3384 } 3385 3386 try { 3387 if (tracker != null) { 3388 mNetd.setFirewallEnabled(true); 3389 mNetd.setFirewallInterfaceRule("lo", true); 3390 mLockdownTracker = tracker; 3391 mLockdownTracker.init(); 3392 } else { 3393 mNetd.setFirewallEnabled(false); 3394 } 3395 } catch (RemoteException e) { 3396 // ignored; NMS lives inside system_server 3397 } 3398 } 3399 3400 private void throwIfLockdownEnabled() { 3401 if (mLockdownEnabled) { 3402 throw new IllegalStateException("Unavailable in lockdown mode"); 3403 } 3404 } 3405 3406 /** 3407 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform 3408 * some setup and then call {@code establish()} to connect. 3409 * 3410 * @return {@code true} if the service was started, the service was already connected, or there 3411 * was no always-on VPN to start. {@code false} otherwise. 3412 */ 3413 private boolean startAlwaysOnVpn(int userId) { 3414 synchronized (mVpns) { 3415 Vpn vpn = mVpns.get(userId); 3416 if (vpn == null) { 3417 // Shouldn't happen as all codepaths that point here should have checked the Vpn 3418 // exists already. 3419 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration"); 3420 return false; 3421 } 3422 3423 return vpn.startAlwaysOnVpn(); 3424 } 3425 } 3426 3427 @Override 3428 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) { 3429 enforceConnectivityInternalPermission(); 3430 enforceCrossUserPermission(userId); 3431 3432 // Can't set always-on VPN if legacy VPN is already in lockdown mode. 3433 if (LockdownVpnTracker.isEnabled()) { 3434 return false; 3435 } 3436 3437 synchronized (mVpns) { 3438 Vpn vpn = mVpns.get(userId); 3439 if (vpn == null) { 3440 Slog.w(TAG, "User " + userId + " has no Vpn configuration"); 3441 return false; 3442 } 3443 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) { 3444 return false; 3445 } 3446 if (!startAlwaysOnVpn(userId)) { 3447 vpn.setAlwaysOnPackage(null, false); 3448 return false; 3449 } 3450 3451 vpn.saveAlwaysOnPackage(); 3452 } 3453 return true; 3454 } 3455 3456 @Override 3457 public String getAlwaysOnVpnPackage(int userId) { 3458 enforceConnectivityInternalPermission(); 3459 enforceCrossUserPermission(userId); 3460 3461 synchronized (mVpns) { 3462 Vpn vpn = mVpns.get(userId); 3463 if (vpn == null) { 3464 Slog.w(TAG, "User " + userId + " has no Vpn configuration"); 3465 return null; 3466 } 3467 return vpn.getAlwaysOnPackage(); 3468 } 3469 } 3470 3471 @Override 3472 public int checkMobileProvisioning(int suggestedTimeOutMs) { 3473 // TODO: Remove? Any reason to trigger a provisioning check? 3474 return -1; 3475 } 3476 3477 private static final String NOTIFICATION_ID = "CaptivePortal.Notification"; 3478 private static enum NotificationType { SIGN_IN, NO_INTERNET; }; 3479 3480 private void setProvNotificationVisible(boolean visible, int networkType, String action) { 3481 Intent intent = new Intent(action); 3482 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); 3483 // Concatenate the range of types onto the range of NetIDs. 3484 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE); 3485 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN, 3486 networkType, null, pendingIntent, false); 3487 } 3488 3489 /** 3490 * Show or hide network provisioning notifications. 3491 * 3492 * We use notifications for two purposes: to notify that a network requires sign in 3493 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access 3494 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a 3495 * particular network we can display the notification type that was most recently requested. 3496 * So for example if a captive portal fails to reply within a few seconds of connecting, we 3497 * might first display NO_INTERNET, and then when the captive portal check completes, display 3498 * SIGN_IN. 3499 * 3500 * @param id an identifier that uniquely identifies this notification. This must match 3501 * between show and hide calls. We use the NetID value but for legacy callers 3502 * we concatenate the range of types with the range of NetIDs. 3503 */ 3504 private void setProvNotificationVisibleIntent(boolean visible, int id, 3505 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent, 3506 boolean highPriority) { 3507 if (VDBG || (DBG && visible)) { 3508 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible 3509 + " networkType=" + getNetworkTypeName(networkType) 3510 + " extraInfo=" + extraInfo + " highPriority=" + highPriority); 3511 } 3512 3513 Resources r = Resources.getSystem(); 3514 NotificationManager notificationManager = (NotificationManager) mContext 3515 .getSystemService(Context.NOTIFICATION_SERVICE); 3516 3517 if (visible) { 3518 CharSequence title; 3519 CharSequence details; 3520 int icon; 3521 if (notifyType == NotificationType.NO_INTERNET && 3522 networkType == ConnectivityManager.TYPE_WIFI) { 3523 title = r.getString(R.string.wifi_no_internet, 0); 3524 details = r.getString(R.string.wifi_no_internet_detailed); 3525 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon. 3526 } else if (notifyType == NotificationType.SIGN_IN) { 3527 switch (networkType) { 3528 case ConnectivityManager.TYPE_WIFI: 3529 title = r.getString(R.string.wifi_available_sign_in, 0); 3530 details = r.getString(R.string.network_available_sign_in_detailed, 3531 extraInfo); 3532 icon = R.drawable.stat_notify_wifi_in_range; 3533 break; 3534 case ConnectivityManager.TYPE_MOBILE: 3535 case ConnectivityManager.TYPE_MOBILE_HIPRI: 3536 title = r.getString(R.string.network_available_sign_in, 0); 3537 // TODO: Change this to pull from NetworkInfo once a printable 3538 // name has been added to it 3539 details = mTelephonyManager.getNetworkOperatorName(); 3540 icon = R.drawable.stat_notify_rssi_in_range; 3541 break; 3542 default: 3543 title = r.getString(R.string.network_available_sign_in, 0); 3544 details = r.getString(R.string.network_available_sign_in_detailed, 3545 extraInfo); 3546 icon = R.drawable.stat_notify_rssi_in_range; 3547 break; 3548 } 3549 } else { 3550 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type " 3551 + getNetworkTypeName(networkType)); 3552 return; 3553 } 3554 3555 Notification notification = new Notification.Builder(mContext) 3556 .setWhen(0) 3557 .setSmallIcon(icon) 3558 .setAutoCancel(true) 3559 .setTicker(title) 3560 .setColor(mContext.getColor( 3561 com.android.internal.R.color.system_notification_accent_color)) 3562 .setContentTitle(title) 3563 .setContentText(details) 3564 .setContentIntent(intent) 3565 .setLocalOnly(true) 3566 .setPriority(highPriority ? 3567 Notification.PRIORITY_HIGH : 3568 Notification.PRIORITY_DEFAULT) 3569 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0) 3570 .setOnlyAlertOnce(true) 3571 .build(); 3572 3573 try { 3574 notificationManager.notifyAsUser(NOTIFICATION_ID, id, notification, UserHandle.ALL); 3575 } catch (NullPointerException npe) { 3576 loge("setNotificationVisible: visible notificationManager npe=" + npe); 3577 npe.printStackTrace(); 3578 } 3579 } else { 3580 try { 3581 notificationManager.cancelAsUser(NOTIFICATION_ID, id, UserHandle.ALL); 3582 } catch (NullPointerException npe) { 3583 loge("setNotificationVisible: cancel notificationManager npe=" + npe); 3584 npe.printStackTrace(); 3585 } 3586 } 3587 } 3588 3589 /** Location to an updatable file listing carrier provisioning urls. 3590 * An example: 3591 * 3592 * <?xml version="1.0" encoding="utf-8"?> 3593 * <provisioningUrls> 3594 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl> 3595 * </provisioningUrls> 3596 */ 3597 private static final String PROVISIONING_URL_PATH = 3598 "/data/misc/radio/provisioning_urls.xml"; 3599 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH); 3600 3601 /** XML tag for root element. */ 3602 private static final String TAG_PROVISIONING_URLS = "provisioningUrls"; 3603 /** XML tag for individual url */ 3604 private static final String TAG_PROVISIONING_URL = "provisioningUrl"; 3605 /** XML attribute for mcc */ 3606 private static final String ATTR_MCC = "mcc"; 3607 /** XML attribute for mnc */ 3608 private static final String ATTR_MNC = "mnc"; 3609 3610 private String getProvisioningUrlBaseFromFile() { 3611 FileReader fileReader = null; 3612 XmlPullParser parser = null; 3613 Configuration config = mContext.getResources().getConfiguration(); 3614 3615 try { 3616 fileReader = new FileReader(mProvisioningUrlFile); 3617 parser = Xml.newPullParser(); 3618 parser.setInput(fileReader); 3619 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS); 3620 3621 while (true) { 3622 XmlUtils.nextElement(parser); 3623 3624 String element = parser.getName(); 3625 if (element == null) break; 3626 3627 if (element.equals(TAG_PROVISIONING_URL)) { 3628 String mcc = parser.getAttributeValue(null, ATTR_MCC); 3629 try { 3630 if (mcc != null && Integer.parseInt(mcc) == config.mcc) { 3631 String mnc = parser.getAttributeValue(null, ATTR_MNC); 3632 if (mnc != null && Integer.parseInt(mnc) == config.mnc) { 3633 parser.next(); 3634 if (parser.getEventType() == XmlPullParser.TEXT) { 3635 return parser.getText(); 3636 } 3637 } 3638 } 3639 } catch (NumberFormatException e) { 3640 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e); 3641 } 3642 } 3643 } 3644 return null; 3645 } catch (FileNotFoundException e) { 3646 loge("Carrier Provisioning Urls file not found"); 3647 } catch (XmlPullParserException e) { 3648 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e); 3649 } catch (IOException e) { 3650 loge("I/O exception reading Carrier Provisioning Urls file: " + e); 3651 } finally { 3652 if (fileReader != null) { 3653 try { 3654 fileReader.close(); 3655 } catch (IOException e) {} 3656 } 3657 } 3658 return null; 3659 } 3660 3661 @Override 3662 public String getMobileProvisioningUrl() { 3663 enforceConnectivityInternalPermission(); 3664 String url = getProvisioningUrlBaseFromFile(); 3665 if (TextUtils.isEmpty(url)) { 3666 url = mContext.getResources().getString(R.string.mobile_provisioning_url); 3667 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url); 3668 } else { 3669 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url); 3670 } 3671 // populate the iccid, imei and phone number in the provisioning url. 3672 if (!TextUtils.isEmpty(url)) { 3673 String phoneNumber = mTelephonyManager.getLine1Number(); 3674 if (TextUtils.isEmpty(phoneNumber)) { 3675 phoneNumber = "0000000000"; 3676 } 3677 url = String.format(url, 3678 mTelephonyManager.getSimSerialNumber() /* ICCID */, 3679 mTelephonyManager.getDeviceId() /* IMEI */, 3680 phoneNumber /* Phone numer */); 3681 } 3682 3683 return url; 3684 } 3685 3686 @Override 3687 public void setProvisioningNotificationVisible(boolean visible, int networkType, 3688 String action) { 3689 enforceConnectivityInternalPermission(); 3690 final long ident = Binder.clearCallingIdentity(); 3691 try { 3692 setProvNotificationVisible(visible, networkType, action); 3693 } finally { 3694 Binder.restoreCallingIdentity(ident); 3695 } 3696 } 3697 3698 @Override 3699 public void setAirplaneMode(boolean enable) { 3700 enforceConnectivityInternalPermission(); 3701 final long ident = Binder.clearCallingIdentity(); 3702 try { 3703 final ContentResolver cr = mContext.getContentResolver(); 3704 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 3705 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 3706 intent.putExtra("state", enable); 3707 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 3708 } finally { 3709 Binder.restoreCallingIdentity(ident); 3710 } 3711 } 3712 3713 private void onUserStart(int userId) { 3714 synchronized(mVpns) { 3715 Vpn userVpn = mVpns.get(userId); 3716 if (userVpn != null) { 3717 loge("Starting user already has a VPN"); 3718 return; 3719 } 3720 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); 3721 mVpns.put(userId, userVpn); 3722 3723 final ContentResolver cr = mContext.getContentResolver(); 3724 String alwaysOnPackage = Settings.Secure.getStringForUser(cr, 3725 Settings.Secure.ALWAYS_ON_VPN_APP, userId); 3726 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr, 3727 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0; 3728 if (alwaysOnPackage != null) { 3729 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown); 3730 } 3731 } 3732 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) { 3733 updateLockdownVpn(); 3734 } 3735 } 3736 3737 private void onUserStop(int userId) { 3738 synchronized(mVpns) { 3739 Vpn userVpn = mVpns.get(userId); 3740 if (userVpn == null) { 3741 loge("Stopped user has no VPN"); 3742 return; 3743 } 3744 userVpn.onUserStopped(); 3745 mVpns.delete(userId); 3746 } 3747 } 3748 3749 private void onUserAdded(int userId) { 3750 synchronized(mVpns) { 3751 final int vpnsSize = mVpns.size(); 3752 for (int i = 0; i < vpnsSize; i++) { 3753 Vpn vpn = mVpns.valueAt(i); 3754 vpn.onUserAdded(userId); 3755 } 3756 } 3757 } 3758 3759 private void onUserRemoved(int userId) { 3760 synchronized(mVpns) { 3761 final int vpnsSize = mVpns.size(); 3762 for (int i = 0; i < vpnsSize; i++) { 3763 Vpn vpn = mVpns.valueAt(i); 3764 vpn.onUserRemoved(userId); 3765 } 3766 } 3767 } 3768 3769 private void onUserUnlocked(int userId) { 3770 // User present may be sent because of an unlock, which might mean an unlocked keystore. 3771 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) { 3772 updateLockdownVpn(); 3773 } else { 3774 startAlwaysOnVpn(userId); 3775 } 3776 } 3777 3778 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() { 3779 @Override 3780 public void onReceive(Context context, Intent intent) { 3781 final String action = intent.getAction(); 3782 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 3783 if (userId == UserHandle.USER_NULL) return; 3784 3785 if (Intent.ACTION_USER_STARTED.equals(action)) { 3786 onUserStart(userId); 3787 } else if (Intent.ACTION_USER_STOPPED.equals(action)) { 3788 onUserStop(userId); 3789 } else if (Intent.ACTION_USER_ADDED.equals(action)) { 3790 onUserAdded(userId); 3791 } else if (Intent.ACTION_USER_REMOVED.equals(action)) { 3792 onUserRemoved(userId); 3793 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) { 3794 onUserUnlocked(userId); 3795 } 3796 } 3797 }; 3798 3799 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = 3800 new HashMap<Messenger, NetworkFactoryInfo>(); 3801 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = 3802 new HashMap<NetworkRequest, NetworkRequestInfo>(); 3803 3804 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100; 3805 // Map from UID to number of NetworkRequests that UID has filed. 3806 @GuardedBy("mUidToNetworkRequestCount") 3807 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray(); 3808 3809 private static class NetworkFactoryInfo { 3810 public final String name; 3811 public final Messenger messenger; 3812 public final AsyncChannel asyncChannel; 3813 3814 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) { 3815 this.name = name; 3816 this.messenger = messenger; 3817 this.asyncChannel = asyncChannel; 3818 } 3819 } 3820 3821 /** 3822 * Tracks info about the requester. 3823 * Also used to notice when the calling process dies so we can self-expire 3824 */ 3825 private class NetworkRequestInfo implements IBinder.DeathRecipient { 3826 final NetworkRequest request; 3827 final PendingIntent mPendingIntent; 3828 boolean mPendingIntentSent; 3829 private final IBinder mBinder; 3830 final int mPid; 3831 final int mUid; 3832 final Messenger messenger; 3833 3834 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) { 3835 request = r; 3836 ensureRequestHasType(); 3837 mPendingIntent = pi; 3838 messenger = null; 3839 mBinder = null; 3840 mPid = getCallingPid(); 3841 mUid = getCallingUid(); 3842 enforceRequestCountLimit(); 3843 } 3844 3845 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) { 3846 super(); 3847 messenger = m; 3848 request = r; 3849 ensureRequestHasType(); 3850 mBinder = binder; 3851 mPid = getCallingPid(); 3852 mUid = getCallingUid(); 3853 mPendingIntent = null; 3854 enforceRequestCountLimit(); 3855 3856 try { 3857 mBinder.linkToDeath(this, 0); 3858 } catch (RemoteException e) { 3859 binderDied(); 3860 } 3861 } 3862 3863 private void ensureRequestHasType() { 3864 if (request.type == NetworkRequest.Type.NONE) { 3865 throw new IllegalArgumentException( 3866 "All NetworkRequests in ConnectivityService must have a type"); 3867 } 3868 } 3869 3870 private void enforceRequestCountLimit() { 3871 synchronized (mUidToNetworkRequestCount) { 3872 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1; 3873 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) { 3874 throw new IllegalArgumentException("Too many NetworkRequests filed"); 3875 } 3876 mUidToNetworkRequestCount.put(mUid, networkRequests); 3877 } 3878 } 3879 3880 void unlinkDeathRecipient() { 3881 if (mBinder != null) { 3882 mBinder.unlinkToDeath(this, 0); 3883 } 3884 } 3885 3886 public void binderDied() { 3887 log("ConnectivityService NetworkRequestInfo binderDied(" + 3888 request + ", " + mBinder + ")"); 3889 releaseNetworkRequest(request); 3890 } 3891 3892 public String toString() { 3893 return "uid/pid:" + mUid + "/" + mPid + " " + request + 3894 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent); 3895 } 3896 } 3897 3898 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) { 3899 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability(); 3900 if (badCapability != null) { 3901 throw new IllegalArgumentException("Cannot request network with " + badCapability); 3902 } 3903 } 3904 3905 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) { 3906 final SortedSet<Integer> thresholds = new TreeSet(); 3907 synchronized (nai) { 3908 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 3909 if (nri.request.networkCapabilities.hasSignalStrength() && 3910 nai.satisfiesImmutableCapabilitiesOf(nri.request)) { 3911 thresholds.add(nri.request.networkCapabilities.getSignalStrength()); 3912 } 3913 } 3914 } 3915 return new ArrayList<Integer>(thresholds); 3916 } 3917 3918 private void updateSignalStrengthThresholds( 3919 NetworkAgentInfo nai, String reason, NetworkRequest request) { 3920 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai); 3921 Bundle thresholds = new Bundle(); 3922 thresholds.putIntegerArrayList("thresholds", thresholdsArray); 3923 3924 if (VDBG || (DBG && !"CONNECT".equals(reason))) { 3925 String detail; 3926 if (request != null && request.networkCapabilities.hasSignalStrength()) { 3927 detail = reason + " " + request.networkCapabilities.getSignalStrength(); 3928 } else { 3929 detail = reason; 3930 } 3931 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s", 3932 detail, Arrays.toString(thresholdsArray.toArray()), nai.name())); 3933 } 3934 3935 nai.asyncChannel.sendMessage( 3936 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS, 3937 0, 0, thresholds); 3938 } 3939 3940 @Override 3941 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities, 3942 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) { 3943 final NetworkRequest.Type type = (networkCapabilities == null) 3944 ? NetworkRequest.Type.TRACK_DEFAULT 3945 : NetworkRequest.Type.REQUEST; 3946 // If the requested networkCapabilities is null, take them instead from 3947 // the default network request. This allows callers to keep track of 3948 // the system default network. 3949 if (type == NetworkRequest.Type.TRACK_DEFAULT) { 3950 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities); 3951 enforceAccessPermission(); 3952 } else { 3953 networkCapabilities = new NetworkCapabilities(networkCapabilities); 3954 enforceNetworkRequestPermissions(networkCapabilities); 3955 } 3956 enforceMeteredApnPolicy(networkCapabilities); 3957 ensureRequestableCapabilities(networkCapabilities); 3958 3959 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) { 3960 throw new IllegalArgumentException("Bad timeout specified"); 3961 } 3962 3963 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER 3964 .equals(networkCapabilities.getNetworkSpecifier())) { 3965 throw new IllegalArgumentException("Invalid network specifier - must not be '" 3966 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'"); 3967 } 3968 3969 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType, 3970 nextNetworkRequestId(), type); 3971 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder); 3972 if (DBG) log("requestNetwork for " + nri); 3973 3974 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri)); 3975 if (timeoutMs > 0) { 3976 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST, 3977 nri), timeoutMs); 3978 } 3979 return networkRequest; 3980 } 3981 3982 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) { 3983 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) { 3984 enforceConnectivityInternalPermission(); 3985 } else { 3986 enforceChangePermission(); 3987 } 3988 } 3989 3990 @Override 3991 public boolean requestBandwidthUpdate(Network network) { 3992 enforceAccessPermission(); 3993 NetworkAgentInfo nai = null; 3994 if (network == null) { 3995 return false; 3996 } 3997 synchronized (mNetworkForNetId) { 3998 nai = mNetworkForNetId.get(network.netId); 3999 } 4000 if (nai != null) { 4001 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE); 4002 return true; 4003 } 4004 return false; 4005 } 4006 4007 private boolean isSystem(int uid) { 4008 return uid < Process.FIRST_APPLICATION_UID; 4009 } 4010 4011 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) { 4012 final int uid = Binder.getCallingUid(); 4013 if (isSystem(uid)) { 4014 return; 4015 } 4016 // if UID is restricted, don't allow them to bring up metered APNs 4017 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) { 4018 final int uidRules; 4019 synchronized(mRulesLock) { 4020 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL); 4021 } 4022 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0 4023 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) { 4024 // we could silently fail or we can filter the available nets to only give 4025 // them those they have access to. Chose the more useful option. 4026 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED); 4027 } 4028 } 4029 } 4030 4031 @Override 4032 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities, 4033 PendingIntent operation) { 4034 checkNotNull(operation, "PendingIntent cannot be null."); 4035 networkCapabilities = new NetworkCapabilities(networkCapabilities); 4036 enforceNetworkRequestPermissions(networkCapabilities); 4037 enforceMeteredApnPolicy(networkCapabilities); 4038 ensureRequestableCapabilities(networkCapabilities); 4039 4040 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE, 4041 nextNetworkRequestId(), NetworkRequest.Type.REQUEST); 4042 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation); 4043 if (DBG) log("pendingRequest for " + nri); 4044 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT, 4045 nri)); 4046 return networkRequest; 4047 } 4048 4049 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) { 4050 mHandler.sendMessageDelayed( 4051 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, 4052 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs); 4053 } 4054 4055 @Override 4056 public void releasePendingNetworkRequest(PendingIntent operation) { 4057 checkNotNull(operation, "PendingIntent cannot be null."); 4058 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, 4059 getCallingUid(), 0, operation)); 4060 } 4061 4062 // In order to implement the compatibility measure for pre-M apps that call 4063 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly, 4064 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork. 4065 // This ensures it has permission to do so. 4066 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) { 4067 if (nc == null) { 4068 return false; 4069 } 4070 int[] transportTypes = nc.getTransportTypes(); 4071 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) { 4072 return false; 4073 } 4074 try { 4075 mContext.enforceCallingOrSelfPermission( 4076 android.Manifest.permission.ACCESS_WIFI_STATE, 4077 "ConnectivityService"); 4078 } catch (SecurityException e) { 4079 return false; 4080 } 4081 return true; 4082 } 4083 4084 @Override 4085 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities, 4086 Messenger messenger, IBinder binder) { 4087 if (!hasWifiNetworkListenPermission(networkCapabilities)) { 4088 enforceAccessPermission(); 4089 } 4090 4091 NetworkRequest networkRequest = new NetworkRequest( 4092 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(), 4093 NetworkRequest.Type.LISTEN); 4094 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder); 4095 if (VDBG) log("listenForNetwork for " + nri); 4096 4097 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 4098 return networkRequest; 4099 } 4100 4101 @Override 4102 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities, 4103 PendingIntent operation) { 4104 checkNotNull(operation, "PendingIntent cannot be null."); 4105 if (!hasWifiNetworkListenPermission(networkCapabilities)) { 4106 enforceAccessPermission(); 4107 } 4108 4109 NetworkRequest networkRequest = new NetworkRequest( 4110 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(), 4111 NetworkRequest.Type.LISTEN); 4112 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation); 4113 if (VDBG) log("pendingListenForNetwork for " + nri); 4114 4115 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 4116 } 4117 4118 @Override 4119 public void releaseNetworkRequest(NetworkRequest networkRequest) { 4120 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 4121 0, networkRequest)); 4122 } 4123 4124 @Override 4125 public void registerNetworkFactory(Messenger messenger, String name) { 4126 enforceConnectivityInternalPermission(); 4127 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel()); 4128 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi)); 4129 } 4130 4131 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) { 4132 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name); 4133 mNetworkFactoryInfos.put(nfi.messenger, nfi); 4134 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger); 4135 } 4136 4137 @Override 4138 public void unregisterNetworkFactory(Messenger messenger) { 4139 enforceConnectivityInternalPermission(); 4140 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger)); 4141 } 4142 4143 private void handleUnregisterNetworkFactory(Messenger messenger) { 4144 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger); 4145 if (nfi == null) { 4146 loge("Failed to find Messenger in unregisterNetworkFactory"); 4147 return; 4148 } 4149 if (DBG) log("unregisterNetworkFactory for " + nfi.name); 4150 } 4151 4152 /** 4153 * NetworkAgentInfo supporting a request by requestId. 4154 * These have already been vetted (their Capabilities satisfy the request) 4155 * and the are the highest scored network available. 4156 * the are keyed off the Requests requestId. 4157 */ 4158 // TODO: Yikes, this is accessed on multiple threads: add synchronization. 4159 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = 4160 new SparseArray<NetworkAgentInfo>(); 4161 4162 // NOTE: Accessed on multiple threads, must be synchronized on itself. 4163 @GuardedBy("mNetworkForNetId") 4164 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = 4165 new SparseArray<NetworkAgentInfo>(); 4166 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId. 4167 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so 4168 // there may not be a strict 1:1 correlation between the two. 4169 @GuardedBy("mNetworkForNetId") 4170 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray(); 4171 4172 // NetworkAgentInfo keyed off its connecting messenger 4173 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays 4174 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump(). 4175 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = 4176 new HashMap<Messenger, NetworkAgentInfo>(); 4177 4178 @GuardedBy("mBlockedAppUids") 4179 private final HashSet<Integer> mBlockedAppUids = new HashSet(); 4180 4181 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated. 4182 private final NetworkRequest mDefaultRequest; 4183 4184 // Request used to optionally keep mobile data active even when higher 4185 // priority networks like Wi-Fi are active. 4186 private final NetworkRequest mDefaultMobileDataRequest; 4187 4188 private NetworkAgentInfo getDefaultNetwork() { 4189 return mNetworkForRequestId.get(mDefaultRequest.requestId); 4190 } 4191 4192 private boolean isDefaultNetwork(NetworkAgentInfo nai) { 4193 return nai == getDefaultNetwork(); 4194 } 4195 4196 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo, 4197 LinkProperties linkProperties, NetworkCapabilities networkCapabilities, 4198 int currentScore, NetworkMisc networkMisc) { 4199 enforceConnectivityInternalPermission(); 4200 4201 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network 4202 // satisfies mDefaultRequest. 4203 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), 4204 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties( 4205 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore, 4206 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this); 4207 synchronized (this) { 4208 nai.networkMonitor.systemReady = mSystemReady; 4209 } 4210 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network, 4211 networkInfo.getExtraInfo()); 4212 if (DBG) log("registerNetworkAgent " + nai); 4213 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai)); 4214 return nai.network.netId; 4215 } 4216 4217 private void handleRegisterNetworkAgent(NetworkAgentInfo na) { 4218 if (VDBG) log("Got NetworkAgent Messenger"); 4219 mNetworkAgentInfos.put(na.messenger, na); 4220 synchronized (mNetworkForNetId) { 4221 mNetworkForNetId.put(na.network.netId, na); 4222 } 4223 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger); 4224 NetworkInfo networkInfo = na.networkInfo; 4225 na.networkInfo = null; 4226 updateNetworkInfo(na, networkInfo); 4227 } 4228 4229 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) { 4230 LinkProperties newLp = networkAgent.linkProperties; 4231 int netId = networkAgent.network.netId; 4232 4233 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before 4234 // we do anything else, make sure its LinkProperties are accurate. 4235 if (networkAgent.clatd != null) { 4236 networkAgent.clatd.fixupLinkProperties(oldLp); 4237 } 4238 4239 updateInterfaces(newLp, oldLp, netId); 4240 updateMtu(newLp, oldLp); 4241 // TODO - figure out what to do for clat 4242// for (LinkProperties lp : newLp.getStackedLinks()) { 4243// updateMtu(lp, null); 4244// } 4245 updateTcpBufferSizes(networkAgent); 4246 4247 updateRoutes(newLp, oldLp, netId); 4248 updateDnses(newLp, oldLp, netId); 4249 4250 updateClat(newLp, oldLp, networkAgent); 4251 if (isDefaultNetwork(networkAgent)) { 4252 handleApplyDefaultProxy(newLp.getHttpProxy()); 4253 } else { 4254 updateProxy(newLp, oldLp, networkAgent); 4255 } 4256 // TODO - move this check to cover the whole function 4257 if (!Objects.equals(newLp, oldLp)) { 4258 notifyIfacesChangedForNetworkStats(); 4259 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED); 4260 } 4261 4262 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent); 4263 } 4264 4265 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) { 4266 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted(); 4267 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai); 4268 4269 if (!wasRunningClat && shouldRunClat) { 4270 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai); 4271 nai.clatd.start(); 4272 } else if (wasRunningClat && !shouldRunClat) { 4273 nai.clatd.stop(); 4274 } 4275 } 4276 4277 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) { 4278 CompareResult<String> interfaceDiff = new CompareResult<String>(); 4279 if (oldLp != null) { 4280 interfaceDiff = oldLp.compareAllInterfaceNames(newLp); 4281 } else if (newLp != null) { 4282 interfaceDiff.added = newLp.getAllInterfaceNames(); 4283 } 4284 for (String iface : interfaceDiff.added) { 4285 try { 4286 if (DBG) log("Adding iface " + iface + " to network " + netId); 4287 mNetd.addInterfaceToNetwork(iface, netId); 4288 } catch (Exception e) { 4289 loge("Exception adding interface: " + e); 4290 } 4291 } 4292 for (String iface : interfaceDiff.removed) { 4293 try { 4294 if (DBG) log("Removing iface " + iface + " from network " + netId); 4295 mNetd.removeInterfaceFromNetwork(iface, netId); 4296 } catch (Exception e) { 4297 loge("Exception removing interface: " + e); 4298 } 4299 } 4300 } 4301 4302 /** 4303 * Have netd update routes from oldLp to newLp. 4304 * @return true if routes changed between oldLp and newLp 4305 */ 4306 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) { 4307 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 4308 if (oldLp != null) { 4309 routeDiff = oldLp.compareAllRoutes(newLp); 4310 } else if (newLp != null) { 4311 routeDiff.added = newLp.getAllRoutes(); 4312 } 4313 4314 // add routes before removing old in case it helps with continuous connectivity 4315 4316 // do this twice, adding non-nexthop routes first, then routes they are dependent on 4317 for (RouteInfo route : routeDiff.added) { 4318 if (route.hasGateway()) continue; 4319 if (VDBG) log("Adding Route [" + route + "] to network " + netId); 4320 try { 4321 mNetd.addRoute(netId, route); 4322 } catch (Exception e) { 4323 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) { 4324 loge("Exception in addRoute for non-gateway: " + e); 4325 } 4326 } 4327 } 4328 for (RouteInfo route : routeDiff.added) { 4329 if (route.hasGateway() == false) continue; 4330 if (VDBG) log("Adding Route [" + route + "] to network " + netId); 4331 try { 4332 mNetd.addRoute(netId, route); 4333 } catch (Exception e) { 4334 if ((route.getGateway() instanceof Inet4Address) || VDBG) { 4335 loge("Exception in addRoute for gateway: " + e); 4336 } 4337 } 4338 } 4339 4340 for (RouteInfo route : routeDiff.removed) { 4341 if (VDBG) log("Removing Route [" + route + "] from network " + netId); 4342 try { 4343 mNetd.removeRoute(netId, route); 4344 } catch (Exception e) { 4345 loge("Exception in removeRoute: " + e); 4346 } 4347 } 4348 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty(); 4349 } 4350 4351 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) { 4352 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) { 4353 return; // no updating necessary 4354 } 4355 4356 Collection<InetAddress> dnses = newLp.getDnsServers(); 4357 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses); 4358 try { 4359 mNetd.setDnsConfigurationForNetwork( 4360 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains()); 4361 } catch (Exception e) { 4362 loge("Exception in setDnsConfigurationForNetwork: " + e); 4363 } 4364 final NetworkAgentInfo defaultNai = getDefaultNetwork(); 4365 if (defaultNai != null && defaultNai.network.netId == netId) { 4366 setDefaultDnsSystemProperties(dnses); 4367 } 4368 flushVmDnsCache(); 4369 } 4370 4371 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) { 4372 int last = 0; 4373 for (InetAddress dns : dnses) { 4374 ++last; 4375 String key = "net.dns" + last; 4376 String value = dns.getHostAddress(); 4377 SystemProperties.set(key, value); 4378 } 4379 for (int i = last + 1; i <= mNumDnsEntries; ++i) { 4380 String key = "net.dns" + i; 4381 SystemProperties.set(key, ""); 4382 } 4383 mNumDnsEntries = last; 4384 } 4385 4386 /** 4387 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities} 4388 * augmented with any stateful capabilities implied from {@code networkAgent} 4389 * (e.g., validated status and captive portal status). 4390 * 4391 * @param nai the network having its capabilities updated. 4392 * @param networkCapabilities the new network capabilities. 4393 */ 4394 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) { 4395 // Don't modify caller's NetworkCapabilities. 4396 networkCapabilities = new NetworkCapabilities(networkCapabilities); 4397 if (nai.lastValidated) { 4398 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED); 4399 } else { 4400 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED); 4401 } 4402 if (nai.lastCaptivePortalDetected) { 4403 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL); 4404 } else { 4405 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL); 4406 } 4407 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) { 4408 final int oldScore = nai.getCurrentScore(); 4409 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) != 4410 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) { 4411 try { 4412 mNetd.setNetworkPermission(nai.network.netId, 4413 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ? 4414 null : NetworkManagementService.PERMISSION_SYSTEM); 4415 } catch (RemoteException e) { 4416 loge("Exception in setNetworkPermission: " + e); 4417 } 4418 } 4419 synchronized (nai) { 4420 nai.networkCapabilities = networkCapabilities; 4421 } 4422 rematchAllNetworksAndRequests(nai, oldScore); 4423 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED); 4424 } 4425 } 4426 4427 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) { 4428 for (int i = 0; i < nai.numNetworkRequests(); i++) { 4429 NetworkRequest nr = nai.requestAt(i); 4430 // Don't send listening requests to factories. b/17393458 4431 if (!nr.isRequest()) continue; 4432 sendUpdatedScoreToFactories(nr, nai.getCurrentScore()); 4433 } 4434 } 4435 4436 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) { 4437 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString()); 4438 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 4439 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0, 4440 networkRequest); 4441 } 4442 } 4443 4444 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent, 4445 int notificationType) { 4446 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) { 4447 Intent intent = new Intent(); 4448 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network); 4449 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request); 4450 nri.mPendingIntentSent = true; 4451 sendIntent(nri.mPendingIntent, intent); 4452 } 4453 // else not handled 4454 } 4455 4456 private void sendIntent(PendingIntent pendingIntent, Intent intent) { 4457 mPendingIntentWakeLock.acquire(); 4458 try { 4459 if (DBG) log("Sending " + pendingIntent); 4460 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */); 4461 } catch (PendingIntent.CanceledException e) { 4462 if (DBG) log(pendingIntent + " was not sent, it had been canceled."); 4463 mPendingIntentWakeLock.release(); 4464 releasePendingNetworkRequest(pendingIntent); 4465 } 4466 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished() 4467 } 4468 4469 @Override 4470 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, 4471 String resultData, Bundle resultExtras) { 4472 if (DBG) log("Finished sending " + pendingIntent); 4473 mPendingIntentWakeLock.release(); 4474 // Release with a delay so the receiving client has an opportunity to put in its 4475 // own request. 4476 releasePendingNetworkRequestWithDelay(pendingIntent); 4477 } 4478 4479 private void callCallbackForRequest(NetworkRequestInfo nri, 4480 NetworkAgentInfo networkAgent, int notificationType) { 4481 if (nri.messenger == null) return; // Default request has no msgr 4482 Bundle bundle = new Bundle(); 4483 bundle.putParcelable(NetworkRequest.class.getSimpleName(), 4484 new NetworkRequest(nri.request)); 4485 Message msg = Message.obtain(); 4486 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL && 4487 notificationType != ConnectivityManager.CALLBACK_RELEASED) { 4488 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network); 4489 } 4490 switch (notificationType) { 4491 case ConnectivityManager.CALLBACK_LOSING: { 4492 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor 4493 break; 4494 } 4495 case ConnectivityManager.CALLBACK_CAP_CHANGED: { 4496 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(), 4497 new NetworkCapabilities(networkAgent.networkCapabilities)); 4498 break; 4499 } 4500 case ConnectivityManager.CALLBACK_IP_CHANGED: { 4501 bundle.putParcelable(LinkProperties.class.getSimpleName(), 4502 new LinkProperties(networkAgent.linkProperties)); 4503 break; 4504 } 4505 } 4506 msg.what = notificationType; 4507 msg.setData(bundle); 4508 try { 4509 if (VDBG) { 4510 log("sending notification " + notifyTypeToName(notificationType) + 4511 " for " + nri.request); 4512 } 4513 nri.messenger.send(msg); 4514 } catch (RemoteException e) { 4515 // may occur naturally in the race of binder death. 4516 loge("RemoteException caught trying to send a callback msg for " + nri.request); 4517 } 4518 } 4519 4520 private void teardownUnneededNetwork(NetworkAgentInfo nai) { 4521 if (nai.numRequestNetworkRequests() != 0) { 4522 for (int i = 0; i < nai.numNetworkRequests(); i++) { 4523 NetworkRequest nr = nai.requestAt(i); 4524 // Ignore listening requests. 4525 if (!nr.isRequest()) continue; 4526 loge("Dead network still had at least " + nr); 4527 break; 4528 } 4529 } 4530 nai.asyncChannel.disconnect(); 4531 } 4532 4533 private void handleLingerComplete(NetworkAgentInfo oldNetwork) { 4534 if (oldNetwork == null) { 4535 loge("Unknown NetworkAgentInfo in handleLingerComplete"); 4536 return; 4537 } 4538 if (DBG) log("handleLingerComplete for " + oldNetwork.name()); 4539 teardownUnneededNetwork(oldNetwork); 4540 } 4541 4542 private void makeDefault(NetworkAgentInfo newNetwork) { 4543 if (DBG) log("Switching to new default network: " + newNetwork); 4544 setupDataActivityTracking(newNetwork); 4545 try { 4546 mNetd.setDefaultNetId(newNetwork.network.netId); 4547 } catch (Exception e) { 4548 loge("Exception setting default network :" + e); 4549 } 4550 notifyLockdownVpn(newNetwork); 4551 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy()); 4552 updateTcpBufferSizes(newNetwork); 4553 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers()); 4554 } 4555 4556 // Handles a network appearing or improving its score. 4557 // 4558 // - Evaluates all current NetworkRequests that can be 4559 // satisfied by newNetwork, and reassigns to newNetwork 4560 // any such requests for which newNetwork is the best. 4561 // 4562 // - Lingers any validated Networks that as a result are no longer 4563 // needed. A network is needed if it is the best network for 4564 // one or more NetworkRequests, or if it is a VPN. 4565 // 4566 // - Tears down newNetwork if it just became validated 4567 // but turns out to be unneeded. 4568 // 4569 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated 4570 // networks that have no chance (i.e. even if validated) 4571 // of becoming the highest scoring network. 4572 // 4573 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy, 4574 // it does not remove NetworkRequests that other Networks could better satisfy. 4575 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}. 4576 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests} 4577 // as it performs better by a factor of the number of Networks. 4578 // 4579 // @param newNetwork is the network to be matched against NetworkRequests. 4580 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be 4581 // performed to tear down unvalidated networks that have no chance (i.e. even if 4582 // validated) of becoming the highest scoring network. 4583 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, 4584 ReapUnvalidatedNetworks reapUnvalidatedNetworks) { 4585 if (!newNetwork.everConnected) return; 4586 boolean keep = newNetwork.isVPN(); 4587 boolean isNewDefault = false; 4588 NetworkAgentInfo oldDefaultNetwork = null; 4589 if (VDBG) log("rematching " + newNetwork.name()); 4590 // Find and migrate to this Network any NetworkRequests for 4591 // which this network is now the best. 4592 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>(); 4593 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>(); 4594 if (VDBG) log(" network has: " + newNetwork.networkCapabilities); 4595 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 4596 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId); 4597 final boolean satisfies = newNetwork.satisfies(nri.request); 4598 if (newNetwork == currentNetwork && satisfies) { 4599 if (VDBG) { 4600 log("Network " + newNetwork.name() + " was already satisfying" + 4601 " request " + nri.request.requestId + ". No change."); 4602 } 4603 keep = true; 4604 continue; 4605 } 4606 4607 // check if it satisfies the NetworkCapabilities 4608 if (VDBG) log(" checking if request is satisfied: " + nri.request); 4609 if (satisfies) { 4610 if (!nri.request.isRequest()) { 4611 // This is not a request, it's a callback listener. 4612 // Add it to newNetwork regardless of score. 4613 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri); 4614 continue; 4615 } 4616 4617 // next check if it's better than any current network we're using for 4618 // this request 4619 if (VDBG) { 4620 log("currentScore = " + 4621 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) + 4622 ", newScore = " + newNetwork.getCurrentScore()); 4623 } 4624 if (currentNetwork == null || 4625 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) { 4626 if (VDBG) log("rematch for " + newNetwork.name()); 4627 if (currentNetwork != null) { 4628 if (VDBG) log(" accepting network in place of " + currentNetwork.name()); 4629 currentNetwork.removeRequest(nri.request.requestId); 4630 currentNetwork.networkLingered.add(nri.request); 4631 affectedNetworks.add(currentNetwork); 4632 } else { 4633 if (VDBG) log(" accepting network in place of null"); 4634 } 4635 unlinger(newNetwork); 4636 mNetworkForRequestId.put(nri.request.requestId, newNetwork); 4637 if (!newNetwork.addRequest(nri.request)) { 4638 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request); 4639 } 4640 addedRequests.add(nri); 4641 keep = true; 4642 // Tell NetworkFactories about the new score, so they can stop 4643 // trying to connect if they know they cannot match it. 4644 // TODO - this could get expensive if we have alot of requests for this 4645 // network. Think about if there is a way to reduce this. Push 4646 // netid->request mapping to each factory? 4647 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore()); 4648 if (mDefaultRequest.requestId == nri.request.requestId) { 4649 isNewDefault = true; 4650 oldDefaultNetwork = currentNetwork; 4651 } 4652 } 4653 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) { 4654 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri", 4655 // mark it as no longer satisfying "nri". Because networks are processed by 4656 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will 4657 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher 4658 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri". 4659 // This means this code doesn't have to handle the case where "currentNetwork" no 4660 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork". 4661 if (DBG) { 4662 log("Network " + newNetwork.name() + " stopped satisfying" + 4663 " request " + nri.request.requestId); 4664 } 4665 newNetwork.removeRequest(nri.request.requestId); 4666 if (currentNetwork == newNetwork) { 4667 mNetworkForRequestId.remove(nri.request.requestId); 4668 sendUpdatedScoreToFactories(nri.request, 0); 4669 } else { 4670 if (nri.request.isRequest()) { 4671 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " + 4672 newNetwork.name() + 4673 " without updating mNetworkForRequestId or factories!"); 4674 } 4675 } 4676 // TODO: technically, sending CALLBACK_LOST here is 4677 // incorrect if nri is a request (not a listen) and there 4678 // is a replacement network currently connected that can 4679 // satisfy it. However, the only capability that can both 4680 // a) be requested and b) change is NET_CAPABILITY_TRUSTED, 4681 // so this code is only incorrect for a network that loses 4682 // the TRUSTED capability, which is a rare case. 4683 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST); 4684 } 4685 } 4686 // Linger any networks that are no longer needed. 4687 for (NetworkAgentInfo nai : affectedNetworks) { 4688 if (nai.lingering) { 4689 // Already lingered. Nothing to do. This can only happen if "nai" is in 4690 // "affectedNetworks" twice. The reasoning being that to get added to 4691 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest 4692 // (i.e. not lingered) so it could have only been lingered by this loop. 4693 // unneeded(nai) will be false and we'll call unlinger() below which would 4694 // be bad, so handle it here. 4695 } else if (unneeded(nai)) { 4696 linger(nai); 4697 } else { 4698 // Clear nai.networkLingered we might have added above. 4699 unlinger(nai); 4700 } 4701 } 4702 if (isNewDefault) { 4703 // Notify system services that this network is up. 4704 makeDefault(newNetwork); 4705 // Log 0 -> X and Y -> X default network transitions, where X is the new default. 4706 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork); 4707 synchronized (ConnectivityService.this) { 4708 // have a new default network, release the transition wakelock in 4709 // a second if it's held. The second pause is to allow apps 4710 // to reconnect over the new network 4711 if (mNetTransitionWakeLock.isHeld()) { 4712 mHandler.sendMessageDelayed(mHandler.obtainMessage( 4713 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 4714 mNetTransitionWakeLockSerialNumber, 0), 4715 1000); 4716 } 4717 } 4718 } 4719 4720 // do this after the default net is switched, but 4721 // before LegacyTypeTracker sends legacy broadcasts 4722 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri); 4723 4724 if (isNewDefault) { 4725 // Maintain the illusion: since the legacy API only 4726 // understands one network at a time, we must pretend 4727 // that the current default network disconnected before 4728 // the new one connected. 4729 if (oldDefaultNetwork != null) { 4730 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(), 4731 oldDefaultNetwork, true); 4732 } 4733 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0; 4734 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork); 4735 notifyLockdownVpn(newNetwork); 4736 } 4737 4738 if (keep) { 4739 // Notify battery stats service about this network, both the normal 4740 // interface and any stacked links. 4741 // TODO: Avoid redoing this; this must only be done once when a network comes online. 4742 try { 4743 final IBatteryStats bs = BatteryStatsService.getService(); 4744 final int type = newNetwork.networkInfo.getType(); 4745 4746 final String baseIface = newNetwork.linkProperties.getInterfaceName(); 4747 bs.noteNetworkInterfaceType(baseIface, type); 4748 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) { 4749 final String stackedIface = stacked.getInterfaceName(); 4750 bs.noteNetworkInterfaceType(stackedIface, type); 4751 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface); 4752 } 4753 } catch (RemoteException ignored) { 4754 } 4755 4756 // This has to happen after the notifyNetworkCallbacks as that tickles each 4757 // ConnectivityManager instance so that legacy requests correctly bind dns 4758 // requests to this network. The legacy users are listening for this bcast 4759 // and will generally do a dns request so they can ensureRouteToHost and if 4760 // they do that before the callbacks happen they'll use the default network. 4761 // 4762 // TODO: Is there still a race here? We send the broadcast 4763 // after sending the callback, but if the app can receive the 4764 // broadcast before the callback, it might still break. 4765 // 4766 // This *does* introduce a race where if the user uses the new api 4767 // (notification callbacks) and then uses the old api (getNetworkInfo(type)) 4768 // they may get old info. Reverse this after the old startUsing api is removed. 4769 // This is on top of the multiple intent sequencing referenced in the todo above. 4770 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) { 4771 NetworkRequest nr = newNetwork.requestAt(i); 4772 if (nr.legacyType != TYPE_NONE && nr.isRequest()) { 4773 // legacy type tracker filters out repeat adds 4774 mLegacyTypeTracker.add(nr.legacyType, newNetwork); 4775 } 4776 } 4777 4778 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above, 4779 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest 4780 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the 4781 // newNetwork to the tracker explicitly (it's a no-op if it has already been added). 4782 if (newNetwork.isVPN()) { 4783 mLegacyTypeTracker.add(TYPE_VPN, newNetwork); 4784 } 4785 } 4786 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) { 4787 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 4788 if (unneeded(nai)) { 4789 if (DBG) log("Reaping " + nai.name()); 4790 teardownUnneededNetwork(nai); 4791 } 4792 } 4793 } 4794 } 4795 4796 /** 4797 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks 4798 * being disconnected. 4799 * @param changed If only one Network's score or capabilities have been modified since the last 4800 * time this function was called, pass this Network in this argument, otherwise pass 4801 * null. 4802 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not 4803 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via 4804 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if 4805 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a 4806 * network's score. 4807 */ 4808 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) { 4809 // TODO: This may get slow. The "changed" parameter is provided for future optimization 4810 // to avoid the slowness. It is not simply enough to process just "changed", for 4811 // example in the case where "changed"'s score decreases and another network should begin 4812 // satifying a NetworkRequest that "changed" currently satisfies. 4813 4814 // Optimization: Only reprocess "changed" if its score improved. This is safe because it 4815 // can only add more NetworkRequests satisfied by "changed", and this is exactly what 4816 // rematchNetworkAndRequests() handles. 4817 if (changed != null && oldScore < changed.getCurrentScore()) { 4818 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP); 4819 } else { 4820 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray( 4821 new NetworkAgentInfo[mNetworkAgentInfos.size()]); 4822 // Rematch higher scoring networks first to prevent requests first matching a lower 4823 // scoring network and then a higher scoring network, which could produce multiple 4824 // callbacks and inadvertently unlinger networks. 4825 Arrays.sort(nais); 4826 for (NetworkAgentInfo nai : nais) { 4827 rematchNetworkAndRequests(nai, 4828 // Only reap the last time through the loop. Reaping before all rematching 4829 // is complete could incorrectly teardown a network that hasn't yet been 4830 // rematched. 4831 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP 4832 : ReapUnvalidatedNetworks.REAP); 4833 } 4834 } 4835 } 4836 4837 private void updateInetCondition(NetworkAgentInfo nai) { 4838 // Don't bother updating until we've graduated to validated at least once. 4839 if (!nai.everValidated) return; 4840 // For now only update icons for default connection. 4841 // TODO: Update WiFi and cellular icons separately. b/17237507 4842 if (!isDefaultNetwork(nai)) return; 4843 4844 int newInetCondition = nai.lastValidated ? 100 : 0; 4845 // Don't repeat publish. 4846 if (newInetCondition == mDefaultInetConditionPublished) return; 4847 4848 mDefaultInetConditionPublished = newInetCondition; 4849 sendInetConditionBroadcast(nai.networkInfo); 4850 } 4851 4852 private void notifyLockdownVpn(NetworkAgentInfo nai) { 4853 if (mLockdownTracker != null) { 4854 if (nai != null && nai.isVPN()) { 4855 mLockdownTracker.onVpnStateChanged(nai.networkInfo); 4856 } else { 4857 mLockdownTracker.onNetworkInfoChanged(); 4858 } 4859 } 4860 } 4861 4862 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) { 4863 NetworkInfo.State state = newInfo.getState(); 4864 NetworkInfo oldInfo = null; 4865 final int oldScore = networkAgent.getCurrentScore(); 4866 synchronized (networkAgent) { 4867 oldInfo = networkAgent.networkInfo; 4868 networkAgent.networkInfo = newInfo; 4869 } 4870 notifyLockdownVpn(networkAgent); 4871 4872 if (oldInfo != null && oldInfo.getState() == state) { 4873 if (oldInfo.isRoaming() != newInfo.isRoaming()) { 4874 if (VDBG) log("roaming status changed, notifying NetworkStatsService"); 4875 notifyIfacesChangedForNetworkStats(); 4876 } else if (VDBG) log("ignoring duplicate network state non-change"); 4877 // In either case, no further work should be needed. 4878 return; 4879 } 4880 if (DBG) { 4881 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " + 4882 (oldInfo == null ? "null" : oldInfo.getState()) + 4883 " to " + state); 4884 } 4885 4886 if (!networkAgent.created 4887 && (state == NetworkInfo.State.CONNECTED 4888 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) { 4889 try { 4890 // This should never fail. Specifying an already in use NetID will cause failure. 4891 if (networkAgent.isVPN()) { 4892 mNetd.createVirtualNetwork(networkAgent.network.netId, 4893 !networkAgent.linkProperties.getDnsServers().isEmpty(), 4894 (networkAgent.networkMisc == null || 4895 !networkAgent.networkMisc.allowBypass)); 4896 } else { 4897 mNetd.createPhysicalNetwork(networkAgent.network.netId, 4898 networkAgent.networkCapabilities.hasCapability( 4899 NET_CAPABILITY_NOT_RESTRICTED) ? 4900 null : NetworkManagementService.PERMISSION_SYSTEM); 4901 } 4902 } catch (Exception e) { 4903 loge("Error creating network " + networkAgent.network.netId + ": " 4904 + e.getMessage()); 4905 return; 4906 } 4907 networkAgent.created = true; 4908 } 4909 4910 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) { 4911 networkAgent.everConnected = true; 4912 4913 updateLinkProperties(networkAgent, null); 4914 notifyIfacesChangedForNetworkStats(); 4915 4916 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 4917 scheduleUnvalidatedPrompt(networkAgent); 4918 4919 if (networkAgent.isVPN()) { 4920 // Temporarily disable the default proxy (not global). 4921 synchronized (mProxyLock) { 4922 if (!mDefaultProxyDisabled) { 4923 mDefaultProxyDisabled = true; 4924 if (mGlobalProxy == null && mDefaultProxy != null) { 4925 sendProxyBroadcast(null); 4926 } 4927 } 4928 } 4929 // TODO: support proxy per network. 4930 } 4931 4932 // Whether a particular NetworkRequest listen should cause signal strength thresholds to 4933 // be communicated to a particular NetworkAgent depends only on the network's immutable, 4934 // capabilities, so it only needs to be done once on initial connect, not every time the 4935 // network's capabilities change. Note that we do this before rematching the network, 4936 // so we could decide to tear it down immediately afterwards. That's fine though - on 4937 // disconnection NetworkAgents should stop any signal strength monitoring they have been 4938 // doing. 4939 updateSignalStrengthThresholds(networkAgent, "CONNECT", null); 4940 4941 // Consider network even though it is not yet validated. 4942 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP); 4943 4944 // This has to happen after matching the requests, because callbacks are just requests. 4945 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK); 4946 } else if (state == NetworkInfo.State.DISCONNECTED) { 4947 networkAgent.asyncChannel.disconnect(); 4948 if (networkAgent.isVPN()) { 4949 synchronized (mProxyLock) { 4950 if (mDefaultProxyDisabled) { 4951 mDefaultProxyDisabled = false; 4952 if (mGlobalProxy == null && mDefaultProxy != null) { 4953 sendProxyBroadcast(mDefaultProxy); 4954 } 4955 } 4956 } 4957 } 4958 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) || 4959 state == NetworkInfo.State.SUSPENDED) { 4960 // going into or coming out of SUSPEND: rescore and notify 4961 if (networkAgent.getCurrentScore() != oldScore) { 4962 rematchAllNetworksAndRequests(networkAgent, oldScore); 4963 } 4964 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ? 4965 ConnectivityManager.CALLBACK_SUSPENDED : 4966 ConnectivityManager.CALLBACK_RESUMED)); 4967 mLegacyTypeTracker.update(networkAgent); 4968 } 4969 } 4970 4971 private void updateNetworkScore(NetworkAgentInfo nai, int score) { 4972 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score); 4973 if (score < 0) { 4974 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score + 4975 "). Bumping score to min of 0"); 4976 score = 0; 4977 } 4978 4979 final int oldScore = nai.getCurrentScore(); 4980 nai.setCurrentScore(score); 4981 4982 rematchAllNetworksAndRequests(nai, oldScore); 4983 4984 sendUpdatedScoreToFactories(nai); 4985 } 4986 4987 // notify only this one new request of the current state 4988 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) { 4989 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE; 4990 // TODO - read state from monitor to decide what to send. 4991// if (nai.networkMonitor.isLingering()) { 4992// notifyType = NetworkCallbacks.LOSING; 4993// } else if (nai.networkMonitor.isEvaluating()) { 4994// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType); 4995// } 4996 if (nri.mPendingIntent == null) { 4997 callCallbackForRequest(nri, nai, notifyType); 4998 } else { 4999 sendPendingIntentForRequest(nri, nai, notifyType); 5000 } 5001 } 5002 5003 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) { 5004 // The NetworkInfo we actually send out has no bearing on the real 5005 // state of affairs. For example, if the default connection is mobile, 5006 // and a request for HIPRI has just gone away, we need to pretend that 5007 // HIPRI has just disconnected. So we need to set the type to HIPRI and 5008 // the state to DISCONNECTED, even though the network is of type MOBILE 5009 // and is still connected. 5010 NetworkInfo info = new NetworkInfo(nai.networkInfo); 5011 info.setType(type); 5012 if (state != DetailedState.DISCONNECTED) { 5013 info.setDetailedState(state, null, info.getExtraInfo()); 5014 sendConnectedBroadcast(info); 5015 } else { 5016 info.setDetailedState(state, info.getReason(), info.getExtraInfo()); 5017 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 5018 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 5019 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 5020 if (info.isFailover()) { 5021 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 5022 nai.networkInfo.setFailover(false); 5023 } 5024 if (info.getReason() != null) { 5025 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 5026 } 5027 if (info.getExtraInfo() != null) { 5028 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo()); 5029 } 5030 NetworkAgentInfo newDefaultAgent = null; 5031 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) { 5032 newDefaultAgent = getDefaultNetwork(); 5033 if (newDefaultAgent != null) { 5034 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, 5035 newDefaultAgent.networkInfo); 5036 } else { 5037 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 5038 } 5039 } 5040 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, 5041 mDefaultInetConditionPublished); 5042 sendStickyBroadcast(intent); 5043 if (newDefaultAgent != null) { 5044 sendConnectedBroadcast(newDefaultAgent.networkInfo); 5045 } 5046 } 5047 } 5048 5049 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) { 5050 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name()); 5051 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) { 5052 NetworkRequest nr = networkAgent.requestAt(i); 5053 NetworkRequestInfo nri = mNetworkRequests.get(nr); 5054 if (VDBG) log(" sending notification for " + nr); 5055 if (nri.mPendingIntent == null) { 5056 callCallbackForRequest(nri, networkAgent, notifyType); 5057 } else { 5058 sendPendingIntentForRequest(nri, networkAgent, notifyType); 5059 } 5060 } 5061 } 5062 5063 private String notifyTypeToName(int notifyType) { 5064 switch (notifyType) { 5065 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK"; 5066 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE"; 5067 case ConnectivityManager.CALLBACK_LOSING: return "LOSING"; 5068 case ConnectivityManager.CALLBACK_LOST: return "LOST"; 5069 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE"; 5070 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED"; 5071 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED"; 5072 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED"; 5073 } 5074 return "UNKNOWN"; 5075 } 5076 5077 /** 5078 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the 5079 * properties tracked by NetworkStatsService on an active iface has changed. 5080 */ 5081 private void notifyIfacesChangedForNetworkStats() { 5082 try { 5083 mStatsService.forceUpdateIfaces(); 5084 } catch (Exception ignored) { 5085 } 5086 } 5087 5088 @Override 5089 public boolean addVpnAddress(String address, int prefixLength) { 5090 throwIfLockdownEnabled(); 5091 int user = UserHandle.getUserId(Binder.getCallingUid()); 5092 synchronized (mVpns) { 5093 return mVpns.get(user).addAddress(address, prefixLength); 5094 } 5095 } 5096 5097 @Override 5098 public boolean removeVpnAddress(String address, int prefixLength) { 5099 throwIfLockdownEnabled(); 5100 int user = UserHandle.getUserId(Binder.getCallingUid()); 5101 synchronized (mVpns) { 5102 return mVpns.get(user).removeAddress(address, prefixLength); 5103 } 5104 } 5105 5106 @Override 5107 public boolean setUnderlyingNetworksForVpn(Network[] networks) { 5108 throwIfLockdownEnabled(); 5109 int user = UserHandle.getUserId(Binder.getCallingUid()); 5110 boolean success; 5111 synchronized (mVpns) { 5112 success = mVpns.get(user).setUnderlyingNetworks(networks); 5113 } 5114 if (success) { 5115 notifyIfacesChangedForNetworkStats(); 5116 } 5117 return success; 5118 } 5119 5120 @Override 5121 public String getCaptivePortalServerUrl() { 5122 return NetworkMonitor.getCaptivePortalServerUrl(mContext); 5123 } 5124 5125 @Override 5126 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger, 5127 IBinder binder, String srcAddr, int srcPort, String dstAddr) { 5128 enforceKeepalivePermission(); 5129 mKeepaliveTracker.startNattKeepalive( 5130 getNetworkAgentInfoForNetwork(network), 5131 intervalSeconds, messenger, binder, 5132 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT); 5133 } 5134 5135 @Override 5136 public void stopKeepalive(Network network, int slot) { 5137 mHandler.sendMessage(mHandler.obtainMessage( 5138 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network)); 5139 } 5140 5141 @Override 5142 public void factoryReset() { 5143 enforceConnectivityInternalPermission(); 5144 5145 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) { 5146 return; 5147 } 5148 5149 final int userId = UserHandle.getCallingUserId(); 5150 5151 // Turn airplane mode off 5152 setAirplaneMode(false); 5153 5154 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) { 5155 // Untether 5156 for (String tether : getTetheredIfaces()) { 5157 untether(tether); 5158 } 5159 } 5160 5161 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) { 5162 // Remove always-on package 5163 synchronized (mVpns) { 5164 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId); 5165 if (alwaysOnPackage != null) { 5166 setAlwaysOnVpnPackage(userId, null, false); 5167 setVpnPackageAuthorization(alwaysOnPackage, userId, false); 5168 } 5169 } 5170 5171 // Turn VPN off 5172 VpnConfig vpnConfig = getVpnConfig(userId); 5173 if (vpnConfig != null) { 5174 if (vpnConfig.legacy) { 5175 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId); 5176 } else { 5177 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections 5178 // in the future without user intervention. 5179 setVpnPackageAuthorization(vpnConfig.user, userId, false); 5180 5181 prepareVpn(null, VpnConfig.LEGACY_VPN, userId); 5182 } 5183 } 5184 } 5185 } 5186 5187 @VisibleForTesting 5188 public NetworkMonitor createNetworkMonitor(Context context, Handler handler, 5189 NetworkAgentInfo nai, NetworkRequest defaultRequest) { 5190 return new NetworkMonitor(context, handler, nai, defaultRequest); 5191 } 5192 5193 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) { 5194 int newNetid = NETID_UNSET; 5195 int prevNetid = NETID_UNSET; 5196 int[] transports = new int[0]; 5197 boolean hadIPv4 = false; 5198 boolean hadIPv6 = false; 5199 5200 if (newNai != null) { 5201 newNetid = newNai.network.netId; 5202 transports = newNai.networkCapabilities.getTransportTypes(); 5203 } 5204 if (prevNai != null) { 5205 prevNetid = prevNai.network.netId; 5206 final LinkProperties lp = prevNai.linkProperties; 5207 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute(); 5208 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute(); 5209 } 5210 5211 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6)); 5212 } 5213 5214 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) { 5215 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype)); 5216 } 5217} 5218