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