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