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