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