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