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