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