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