ConnectivityService.java revision f180fe31de4cc428c298a2faed394c417ade5483
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 that the network does not have Internet access (because that's 2367 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in 2368 // the future. We do this now because NetworkMonitor might not yet have finished 2369 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED. 2370 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS, 2371 NetworkAgent.INVALID_NETWORK, 0, null); 2372 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not 2373 // to reconnect to it immediately. http://b/20739299 2374 } 2375 2376 } 2377 2378 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) { 2379 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network); 2380 mHandler.sendMessageDelayed( 2381 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network), 2382 PROMPT_UNVALIDATED_DELAY_MS); 2383 } 2384 2385 private void handlePromptUnvalidated(Network network) { 2386 if (DBG) log("handlePromptUnvalidated " + network); 2387 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 2388 2389 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if 2390 // we haven't already been told to switch to it regardless of whether it validated or not. 2391 // Also don't prompt on captive portals because we're already prompting the user to sign in. 2392 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected || 2393 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) { 2394 return; 2395 } 2396 2397 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED); 2398 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null)); 2399 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 2400 intent.setClassName("com.android.settings", 2401 "com.android.settings.wifi.WifiNoInternetDialog"); 2402 2403 PendingIntent pendingIntent = PendingIntent.getActivityAsUser( 2404 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT); 2405 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET, 2406 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true); 2407 } 2408 2409 private class InternalHandler extends Handler { 2410 public InternalHandler(Looper looper) { 2411 super(looper); 2412 } 2413 2414 @Override 2415 public void handleMessage(Message msg) { 2416 switch (msg.what) { 2417 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK: 2418 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: { 2419 String causedBy = null; 2420 synchronized (ConnectivityService.this) { 2421 if (msg.arg1 == mNetTransitionWakeLockSerialNumber && 2422 mNetTransitionWakeLock.isHeld()) { 2423 mNetTransitionWakeLock.release(); 2424 causedBy = mNetTransitionWakeLockCausedBy; 2425 } else { 2426 break; 2427 } 2428 } 2429 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) { 2430 log("Failed to find a new network - expiring NetTransition Wakelock"); 2431 } else { 2432 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) + 2433 " cleared because we found a replacement network"); 2434 } 2435 break; 2436 } 2437 case EVENT_APPLY_GLOBAL_HTTP_PROXY: { 2438 handleDeprecatedGlobalHttpProxy(); 2439 break; 2440 } 2441 case EVENT_SEND_STICKY_BROADCAST_INTENT: { 2442 Intent intent = (Intent)msg.obj; 2443 sendStickyBroadcast(intent); 2444 break; 2445 } 2446 case EVENT_PROXY_HAS_CHANGED: { 2447 handleApplyDefaultProxy((ProxyInfo)msg.obj); 2448 break; 2449 } 2450 case EVENT_REGISTER_NETWORK_FACTORY: { 2451 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj); 2452 break; 2453 } 2454 case EVENT_UNREGISTER_NETWORK_FACTORY: { 2455 handleUnregisterNetworkFactory((Messenger)msg.obj); 2456 break; 2457 } 2458 case EVENT_REGISTER_NETWORK_AGENT: { 2459 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj); 2460 break; 2461 } 2462 case EVENT_REGISTER_NETWORK_REQUEST: 2463 case EVENT_REGISTER_NETWORK_LISTENER: { 2464 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj); 2465 break; 2466 } 2467 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: 2468 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: { 2469 handleRegisterNetworkRequestWithIntent(msg); 2470 break; 2471 } 2472 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: { 2473 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1); 2474 break; 2475 } 2476 case EVENT_RELEASE_NETWORK_REQUEST: { 2477 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1); 2478 break; 2479 } 2480 case EVENT_SET_ACCEPT_UNVALIDATED: { 2481 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0); 2482 break; 2483 } 2484 case EVENT_PROMPT_UNVALIDATED: { 2485 handlePromptUnvalidated((Network) msg.obj); 2486 break; 2487 } 2488 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: { 2489 handleMobileDataAlwaysOn(); 2490 break; 2491 } 2492 case EVENT_SYSTEM_READY: { 2493 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2494 nai.networkMonitor.systemReady = true; 2495 } 2496 break; 2497 } 2498 } 2499 } 2500 } 2501 2502 // javadoc from interface 2503 public int tether(String iface) { 2504 ConnectivityManager.enforceTetherChangePermission(mContext); 2505 if (isTetheringSupported()) { 2506 return mTethering.tether(iface); 2507 } else { 2508 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2509 } 2510 } 2511 2512 // javadoc from interface 2513 public int untether(String iface) { 2514 ConnectivityManager.enforceTetherChangePermission(mContext); 2515 2516 if (isTetheringSupported()) { 2517 return mTethering.untether(iface); 2518 } else { 2519 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2520 } 2521 } 2522 2523 // javadoc from interface 2524 public int getLastTetherError(String iface) { 2525 enforceTetherAccessPermission(); 2526 2527 if (isTetheringSupported()) { 2528 return mTethering.getLastTetherError(iface); 2529 } else { 2530 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2531 } 2532 } 2533 2534 // TODO - proper iface API for selection by property, inspection, etc 2535 public String[] getTetherableUsbRegexs() { 2536 enforceTetherAccessPermission(); 2537 if (isTetheringSupported()) { 2538 return mTethering.getTetherableUsbRegexs(); 2539 } else { 2540 return new String[0]; 2541 } 2542 } 2543 2544 public String[] getTetherableWifiRegexs() { 2545 enforceTetherAccessPermission(); 2546 if (isTetheringSupported()) { 2547 return mTethering.getTetherableWifiRegexs(); 2548 } else { 2549 return new String[0]; 2550 } 2551 } 2552 2553 public String[] getTetherableBluetoothRegexs() { 2554 enforceTetherAccessPermission(); 2555 if (isTetheringSupported()) { 2556 return mTethering.getTetherableBluetoothRegexs(); 2557 } else { 2558 return new String[0]; 2559 } 2560 } 2561 2562 public int setUsbTethering(boolean enable) { 2563 ConnectivityManager.enforceTetherChangePermission(mContext); 2564 if (isTetheringSupported()) { 2565 return mTethering.setUsbTethering(enable); 2566 } else { 2567 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2568 } 2569 } 2570 2571 // TODO - move iface listing, queries, etc to new module 2572 // javadoc from interface 2573 public String[] getTetherableIfaces() { 2574 enforceTetherAccessPermission(); 2575 return mTethering.getTetherableIfaces(); 2576 } 2577 2578 public String[] getTetheredIfaces() { 2579 enforceTetherAccessPermission(); 2580 return mTethering.getTetheredIfaces(); 2581 } 2582 2583 public String[] getTetheringErroredIfaces() { 2584 enforceTetherAccessPermission(); 2585 return mTethering.getErroredIfaces(); 2586 } 2587 2588 public String[] getTetheredDhcpRanges() { 2589 enforceConnectivityInternalPermission(); 2590 return mTethering.getTetheredDhcpRanges(); 2591 } 2592 2593 // if ro.tether.denied = true we default to no tethering 2594 // gservices could set the secure setting to 1 though to enable it on a build where it 2595 // had previously been turned off. 2596 public boolean isTetheringSupported() { 2597 enforceTetherAccessPermission(); 2598 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 2599 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(), 2600 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0) 2601 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING); 2602 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 || 2603 mTethering.getTetherableWifiRegexs().length != 0 || 2604 mTethering.getTetherableBluetoothRegexs().length != 0) && 2605 mTethering.getUpstreamIfaceTypes().length != 0); 2606 } 2607 2608 // Called when we lose the default network and have no replacement yet. 2609 // This will automatically be cleared after X seconds or a new default network 2610 // becomes CONNECTED, whichever happens first. The timer is started by the 2611 // first caller and not restarted by subsequent callers. 2612 private void requestNetworkTransitionWakelock(String forWhom) { 2613 int serialNum = 0; 2614 synchronized (this) { 2615 if (mNetTransitionWakeLock.isHeld()) return; 2616 serialNum = ++mNetTransitionWakeLockSerialNumber; 2617 mNetTransitionWakeLock.acquire(); 2618 mNetTransitionWakeLockCausedBy = forWhom; 2619 } 2620 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2621 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0), 2622 mNetTransitionWakeLockTimeout); 2623 return; 2624 } 2625 2626 // 100 percent is full good, 0 is full bad. 2627 public void reportInetCondition(int networkType, int percentage) { 2628 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 2629 if (nai == null) return; 2630 reportNetworkConnectivity(nai.network, percentage > 50); 2631 } 2632 2633 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) { 2634 enforceAccessPermission(); 2635 enforceInternetPermission(); 2636 2637 NetworkAgentInfo nai; 2638 if (network == null) { 2639 nai = getDefaultNetwork(); 2640 } else { 2641 nai = getNetworkAgentInfoForNetwork(network); 2642 } 2643 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING || 2644 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) { 2645 return; 2646 } 2647 // Revalidate if the app report does not match our current validated state. 2648 if (hasConnectivity == nai.lastValidated) return; 2649 final int uid = Binder.getCallingUid(); 2650 if (DBG) { 2651 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity + 2652 ") by " + uid); 2653 } 2654 synchronized (nai) { 2655 // Validating an uncreated network could result in a call to rematchNetworkAndRequests() 2656 // which isn't meant to work on uncreated networks. 2657 if (!nai.created) return; 2658 2659 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return; 2660 2661 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid); 2662 } 2663 } 2664 2665 private ProxyInfo getDefaultProxy() { 2666 // this information is already available as a world read/writable jvm property 2667 // so this API change wouldn't have a benifit. It also breaks the passing 2668 // of proxy info to all the JVMs. 2669 // enforceAccessPermission(); 2670 synchronized (mProxyLock) { 2671 ProxyInfo ret = mGlobalProxy; 2672 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy; 2673 return ret; 2674 } 2675 } 2676 2677 public ProxyInfo getProxyForNetwork(Network network) { 2678 if (network == null) return getDefaultProxy(); 2679 final ProxyInfo globalProxy = getGlobalProxy(); 2680 if (globalProxy != null) return globalProxy; 2681 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null; 2682 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which 2683 // caller may not have. 2684 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 2685 if (nai == null) return null; 2686 synchronized (nai) { 2687 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy(); 2688 if (proxyInfo == null) return null; 2689 return new ProxyInfo(proxyInfo); 2690 } 2691 } 2692 2693 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present 2694 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific 2695 // proxy is null then there is no proxy in place). 2696 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) { 2697 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 2698 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) { 2699 proxy = null; 2700 } 2701 return proxy; 2702 } 2703 2704 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it 2705 // better for determining if a new proxy broadcast is necessary: 2706 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to 2707 // avoid unnecessary broadcasts. 2708 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL 2709 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler) 2710 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but 2711 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port 2712 // all set. 2713 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) { 2714 a = canonicalizeProxyInfo(a); 2715 b = canonicalizeProxyInfo(b); 2716 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check 2717 // hosts even when PAC URLs are present to account for the legacy PAC resolver. 2718 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost())); 2719 } 2720 2721 public void setGlobalProxy(ProxyInfo proxyProperties) { 2722 enforceConnectivityInternalPermission(); 2723 2724 synchronized (mProxyLock) { 2725 if (proxyProperties == mGlobalProxy) return; 2726 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return; 2727 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return; 2728 2729 String host = ""; 2730 int port = 0; 2731 String exclList = ""; 2732 String pacFileUrl = ""; 2733 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) || 2734 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) { 2735 if (!proxyProperties.isValid()) { 2736 if (DBG) 2737 log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 2738 return; 2739 } 2740 mGlobalProxy = new ProxyInfo(proxyProperties); 2741 host = mGlobalProxy.getHost(); 2742 port = mGlobalProxy.getPort(); 2743 exclList = mGlobalProxy.getExclusionListAsString(); 2744 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) { 2745 pacFileUrl = proxyProperties.getPacFileUrl().toString(); 2746 } 2747 } else { 2748 mGlobalProxy = null; 2749 } 2750 ContentResolver res = mContext.getContentResolver(); 2751 final long token = Binder.clearCallingIdentity(); 2752 try { 2753 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host); 2754 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port); 2755 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 2756 exclList); 2757 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl); 2758 } finally { 2759 Binder.restoreCallingIdentity(token); 2760 } 2761 2762 if (mGlobalProxy == null) { 2763 proxyProperties = mDefaultProxy; 2764 } 2765 sendProxyBroadcast(proxyProperties); 2766 } 2767 } 2768 2769 private void loadGlobalProxy() { 2770 ContentResolver res = mContext.getContentResolver(); 2771 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST); 2772 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0); 2773 String exclList = Settings.Global.getString(res, 2774 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST); 2775 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC); 2776 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) { 2777 ProxyInfo proxyProperties; 2778 if (!TextUtils.isEmpty(pacFileUrl)) { 2779 proxyProperties = new ProxyInfo(pacFileUrl); 2780 } else { 2781 proxyProperties = new ProxyInfo(host, port, exclList); 2782 } 2783 if (!proxyProperties.isValid()) { 2784 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 2785 return; 2786 } 2787 2788 synchronized (mProxyLock) { 2789 mGlobalProxy = proxyProperties; 2790 } 2791 } 2792 } 2793 2794 public ProxyInfo getGlobalProxy() { 2795 // this information is already available as a world read/writable jvm property 2796 // so this API change wouldn't have a benifit. It also breaks the passing 2797 // of proxy info to all the JVMs. 2798 // enforceAccessPermission(); 2799 synchronized (mProxyLock) { 2800 return mGlobalProxy; 2801 } 2802 } 2803 2804 private void handleApplyDefaultProxy(ProxyInfo proxy) { 2805 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 2806 && Uri.EMPTY.equals(proxy.getPacFileUrl())) { 2807 proxy = null; 2808 } 2809 synchronized (mProxyLock) { 2810 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return; 2811 if (mDefaultProxy == proxy) return; // catches repeated nulls 2812 if (proxy != null && !proxy.isValid()) { 2813 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString()); 2814 return; 2815 } 2816 2817 // This call could be coming from the PacManager, containing the port of the local 2818 // proxy. If this new proxy matches the global proxy then copy this proxy to the 2819 // global (to get the correct local port), and send a broadcast. 2820 // TODO: Switch PacManager to have its own message to send back rather than 2821 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy. 2822 if ((mGlobalProxy != null) && (proxy != null) 2823 && (!Uri.EMPTY.equals(proxy.getPacFileUrl())) 2824 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) { 2825 mGlobalProxy = proxy; 2826 sendProxyBroadcast(mGlobalProxy); 2827 return; 2828 } 2829 mDefaultProxy = proxy; 2830 2831 if (mGlobalProxy != null) return; 2832 if (!mDefaultProxyDisabled) { 2833 sendProxyBroadcast(proxy); 2834 } 2835 } 2836 } 2837 2838 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy. 2839 // This method gets called when any network changes proxy, but the broadcast only ever contains 2840 // the default proxy (even if it hasn't changed). 2841 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network 2842 // world where an app might be bound to a non-default network. 2843 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) { 2844 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy(); 2845 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy(); 2846 2847 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) { 2848 sendProxyBroadcast(getDefaultProxy()); 2849 } 2850 } 2851 2852 private void handleDeprecatedGlobalHttpProxy() { 2853 String proxy = Settings.Global.getString(mContext.getContentResolver(), 2854 Settings.Global.HTTP_PROXY); 2855 if (!TextUtils.isEmpty(proxy)) { 2856 String data[] = proxy.split(":"); 2857 if (data.length == 0) { 2858 return; 2859 } 2860 2861 String proxyHost = data[0]; 2862 int proxyPort = 8080; 2863 if (data.length > 1) { 2864 try { 2865 proxyPort = Integer.parseInt(data[1]); 2866 } catch (NumberFormatException e) { 2867 return; 2868 } 2869 } 2870 ProxyInfo p = new ProxyInfo(data[0], proxyPort, ""); 2871 setGlobalProxy(p); 2872 } 2873 } 2874 2875 private void sendProxyBroadcast(ProxyInfo proxy) { 2876 if (proxy == null) proxy = new ProxyInfo("", 0, ""); 2877 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return; 2878 if (DBG) log("sending Proxy Broadcast for " + proxy); 2879 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); 2880 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 2881 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 2882 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy); 2883 final long ident = Binder.clearCallingIdentity(); 2884 try { 2885 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 2886 } finally { 2887 Binder.restoreCallingIdentity(ident); 2888 } 2889 } 2890 2891 private static class SettingsObserver extends ContentObserver { 2892 final private HashMap<Uri, Integer> mUriEventMap; 2893 final private Context mContext; 2894 final private Handler mHandler; 2895 2896 SettingsObserver(Context context, Handler handler) { 2897 super(null); 2898 mUriEventMap = new HashMap<Uri, Integer>(); 2899 mContext = context; 2900 mHandler = handler; 2901 } 2902 2903 void observe(Uri uri, int what) { 2904 mUriEventMap.put(uri, what); 2905 final ContentResolver resolver = mContext.getContentResolver(); 2906 resolver.registerContentObserver(uri, false, this); 2907 } 2908 2909 @Override 2910 public void onChange(boolean selfChange) { 2911 Slog.wtf(TAG, "Should never be reached."); 2912 } 2913 2914 @Override 2915 public void onChange(boolean selfChange, Uri uri) { 2916 final Integer what = mUriEventMap.get(uri); 2917 if (what != null) { 2918 mHandler.obtainMessage(what.intValue()).sendToTarget(); 2919 } else { 2920 loge("No matching event to send for URI=" + uri); 2921 } 2922 } 2923 } 2924 2925 private static void log(String s) { 2926 Slog.d(TAG, s); 2927 } 2928 2929 private static void loge(String s) { 2930 Slog.e(TAG, s); 2931 } 2932 2933 private static <T> T checkNotNull(T value, String message) { 2934 if (value == null) { 2935 throw new NullPointerException(message); 2936 } 2937 return value; 2938 } 2939 2940 /** 2941 * Prepare for a VPN application. 2942 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId}, 2943 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required. 2944 * 2945 * @param oldPackage Package name of the application which currently controls VPN, which will 2946 * be replaced. If there is no such application, this should should either be 2947 * {@code null} or {@link VpnConfig.LEGACY_VPN}. 2948 * @param newPackage Package name of the application which should gain control of VPN, or 2949 * {@code null} to disable. 2950 * @param userId User for whom to prepare the new VPN. 2951 * 2952 * @hide 2953 */ 2954 @Override 2955 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage, 2956 int userId) { 2957 enforceCrossUserPermission(userId); 2958 throwIfLockdownEnabled(); 2959 2960 synchronized(mVpns) { 2961 Vpn vpn = mVpns.get(userId); 2962 if (vpn != null) { 2963 return vpn.prepare(oldPackage, newPackage); 2964 } else { 2965 return false; 2966 } 2967 } 2968 } 2969 2970 /** 2971 * Set whether the VPN package has the ability to launch VPNs without user intervention. 2972 * This method is used by system-privileged apps. 2973 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId}, 2974 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required. 2975 * 2976 * @param packageName The package for which authorization state should change. 2977 * @param userId User for whom {@code packageName} is installed. 2978 * @param authorized {@code true} if this app should be able to start a VPN connection without 2979 * explicit user approval, {@code false} if not. 2980 * 2981 * @hide 2982 */ 2983 @Override 2984 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) { 2985 enforceCrossUserPermission(userId); 2986 2987 synchronized(mVpns) { 2988 Vpn vpn = mVpns.get(userId); 2989 if (vpn != null) { 2990 vpn.setPackageAuthorization(packageName, authorized); 2991 } 2992 } 2993 } 2994 2995 /** 2996 * Configure a TUN interface and return its file descriptor. Parameters 2997 * are encoded and opaque to this class. This method is used by VpnBuilder 2998 * and not available in ConnectivityManager. Permissions are checked in 2999 * Vpn class. 3000 * @hide 3001 */ 3002 @Override 3003 public ParcelFileDescriptor establishVpn(VpnConfig config) { 3004 throwIfLockdownEnabled(); 3005 int user = UserHandle.getUserId(Binder.getCallingUid()); 3006 synchronized(mVpns) { 3007 return mVpns.get(user).establish(config); 3008 } 3009 } 3010 3011 /** 3012 * Start legacy VPN, controlling native daemons as needed. Creates a 3013 * secondary thread to perform connection work, returning quickly. 3014 */ 3015 @Override 3016 public void startLegacyVpn(VpnProfile profile) { 3017 throwIfLockdownEnabled(); 3018 final LinkProperties egress = getActiveLinkProperties(); 3019 if (egress == null) { 3020 throw new IllegalStateException("Missing active network connection"); 3021 } 3022 int user = UserHandle.getUserId(Binder.getCallingUid()); 3023 synchronized(mVpns) { 3024 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress); 3025 } 3026 } 3027 3028 /** 3029 * Return the information of the ongoing legacy VPN. This method is used 3030 * by VpnSettings and not available in ConnectivityManager. Permissions 3031 * are checked in Vpn class. 3032 */ 3033 @Override 3034 public LegacyVpnInfo getLegacyVpnInfo(int userId) { 3035 enforceCrossUserPermission(userId); 3036 throwIfLockdownEnabled(); 3037 synchronized(mVpns) { 3038 return mVpns.get(userId).getLegacyVpnInfo(); 3039 } 3040 } 3041 3042 /** 3043 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService 3044 * and not available in ConnectivityManager. 3045 */ 3046 @Override 3047 public VpnInfo[] getAllVpnInfo() { 3048 enforceConnectivityInternalPermission(); 3049 if (mLockdownEnabled) { 3050 return new VpnInfo[0]; 3051 } 3052 3053 synchronized(mVpns) { 3054 List<VpnInfo> infoList = new ArrayList<>(); 3055 for (int i = 0; i < mVpns.size(); i++) { 3056 VpnInfo info = createVpnInfo(mVpns.valueAt(i)); 3057 if (info != null) { 3058 infoList.add(info); 3059 } 3060 } 3061 return infoList.toArray(new VpnInfo[infoList.size()]); 3062 } 3063 } 3064 3065 /** 3066 * @return VPN information for accounting, or null if we can't retrieve all required 3067 * information, e.g primary underlying iface. 3068 */ 3069 @Nullable 3070 private VpnInfo createVpnInfo(Vpn vpn) { 3071 VpnInfo info = vpn.getVpnInfo(); 3072 if (info == null) { 3073 return null; 3074 } 3075 Network[] underlyingNetworks = vpn.getUnderlyingNetworks(); 3076 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret 3077 // the underlyingNetworks list. 3078 if (underlyingNetworks == null) { 3079 NetworkAgentInfo defaultNetwork = getDefaultNetwork(); 3080 if (defaultNetwork != null && defaultNetwork.linkProperties != null) { 3081 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName(); 3082 } 3083 } else if (underlyingNetworks.length > 0) { 3084 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]); 3085 if (linkProperties != null) { 3086 info.primaryUnderlyingIface = linkProperties.getInterfaceName(); 3087 } 3088 } 3089 return info.primaryUnderlyingIface == null ? null : info; 3090 } 3091 3092 /** 3093 * Returns the information of the ongoing VPN for {@code userId}. This method is used by 3094 * VpnDialogs and not available in ConnectivityManager. 3095 * Permissions are checked in Vpn class. 3096 * @hide 3097 */ 3098 @Override 3099 public VpnConfig getVpnConfig(int userId) { 3100 enforceCrossUserPermission(userId); 3101 synchronized(mVpns) { 3102 Vpn vpn = mVpns.get(userId); 3103 if (vpn != null) { 3104 return vpn.getVpnConfig(); 3105 } else { 3106 return null; 3107 } 3108 } 3109 } 3110 3111 @Override 3112 public boolean updateLockdownVpn() { 3113 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 3114 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM"); 3115 return false; 3116 } 3117 3118 // Tear down existing lockdown if profile was removed 3119 mLockdownEnabled = LockdownVpnTracker.isEnabled(); 3120 if (mLockdownEnabled) { 3121 if (!mKeyStore.isUnlocked()) { 3122 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker"); 3123 return false; 3124 } 3125 3126 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN)); 3127 final VpnProfile profile = VpnProfile.decode( 3128 profileName, mKeyStore.get(Credentials.VPN + profileName)); 3129 int user = UserHandle.getUserId(Binder.getCallingUid()); 3130 synchronized(mVpns) { 3131 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user), 3132 profile)); 3133 } 3134 } else { 3135 setLockdownTracker(null); 3136 } 3137 3138 return true; 3139 } 3140 3141 /** 3142 * Internally set new {@link LockdownVpnTracker}, shutting down any existing 3143 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown. 3144 */ 3145 private void setLockdownTracker(LockdownVpnTracker tracker) { 3146 // Shutdown any existing tracker 3147 final LockdownVpnTracker existing = mLockdownTracker; 3148 mLockdownTracker = null; 3149 if (existing != null) { 3150 existing.shutdown(); 3151 } 3152 3153 try { 3154 if (tracker != null) { 3155 mNetd.setFirewallEnabled(true); 3156 mNetd.setFirewallInterfaceRule("lo", true); 3157 mLockdownTracker = tracker; 3158 mLockdownTracker.init(); 3159 } else { 3160 mNetd.setFirewallEnabled(false); 3161 } 3162 } catch (RemoteException e) { 3163 // ignored; NMS lives inside system_server 3164 } 3165 } 3166 3167 private void throwIfLockdownEnabled() { 3168 if (mLockdownEnabled) { 3169 throw new IllegalStateException("Unavailable in lockdown mode"); 3170 } 3171 } 3172 3173 @Override 3174 public int checkMobileProvisioning(int suggestedTimeOutMs) { 3175 // TODO: Remove? Any reason to trigger a provisioning check? 3176 return -1; 3177 } 3178 3179 private static final String NOTIFICATION_ID = "CaptivePortal.Notification"; 3180 private static enum NotificationType { SIGN_IN, NO_INTERNET; }; 3181 3182 private void setProvNotificationVisible(boolean visible, int networkType, String action) { 3183 if (DBG) { 3184 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType 3185 + " action=" + action); 3186 } 3187 Intent intent = new Intent(action); 3188 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); 3189 // Concatenate the range of types onto the range of NetIDs. 3190 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE); 3191 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN, 3192 networkType, null, pendingIntent, false); 3193 } 3194 3195 /** 3196 * Show or hide network provisioning notifications. 3197 * 3198 * We use notifications for two purposes: to notify that a network requires sign in 3199 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access 3200 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a 3201 * particular network we can display the notification type that was most recently requested. 3202 * So for example if a captive portal fails to reply within a few seconds of connecting, we 3203 * might first display NO_INTERNET, and then when the captive portal check completes, display 3204 * SIGN_IN. 3205 * 3206 * @param id an identifier that uniquely identifies this notification. This must match 3207 * between show and hide calls. We use the NetID value but for legacy callers 3208 * we concatenate the range of types with the range of NetIDs. 3209 */ 3210 private void setProvNotificationVisibleIntent(boolean visible, int id, 3211 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent, 3212 boolean highPriority) { 3213 if (DBG) { 3214 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible 3215 + " networkType=" + getNetworkTypeName(networkType) 3216 + " extraInfo=" + extraInfo + " highPriority=" + highPriority); 3217 } 3218 3219 Resources r = Resources.getSystem(); 3220 NotificationManager notificationManager = (NotificationManager) mContext 3221 .getSystemService(Context.NOTIFICATION_SERVICE); 3222 3223 if (visible) { 3224 CharSequence title; 3225 CharSequence details; 3226 int icon; 3227 if (notifyType == NotificationType.NO_INTERNET && 3228 networkType == ConnectivityManager.TYPE_WIFI) { 3229 title = r.getString(R.string.wifi_no_internet, 0); 3230 details = r.getString(R.string.wifi_no_internet_detailed); 3231 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon. 3232 } else if (notifyType == NotificationType.SIGN_IN) { 3233 switch (networkType) { 3234 case ConnectivityManager.TYPE_WIFI: 3235 title = r.getString(R.string.wifi_available_sign_in, 0); 3236 details = r.getString(R.string.network_available_sign_in_detailed, 3237 extraInfo); 3238 icon = R.drawable.stat_notify_wifi_in_range; 3239 break; 3240 case ConnectivityManager.TYPE_MOBILE: 3241 case ConnectivityManager.TYPE_MOBILE_HIPRI: 3242 title = r.getString(R.string.network_available_sign_in, 0); 3243 // TODO: Change this to pull from NetworkInfo once a printable 3244 // name has been added to it 3245 details = mTelephonyManager.getNetworkOperatorName(); 3246 icon = R.drawable.stat_notify_rssi_in_range; 3247 break; 3248 default: 3249 title = r.getString(R.string.network_available_sign_in, 0); 3250 details = r.getString(R.string.network_available_sign_in_detailed, 3251 extraInfo); 3252 icon = R.drawable.stat_notify_rssi_in_range; 3253 break; 3254 } 3255 } else { 3256 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type " 3257 + getNetworkTypeName(networkType)); 3258 return; 3259 } 3260 3261 Notification notification = new Notification.Builder(mContext) 3262 .setWhen(0) 3263 .setSmallIcon(icon) 3264 .setAutoCancel(true) 3265 .setTicker(title) 3266 .setColor(mContext.getColor( 3267 com.android.internal.R.color.system_notification_accent_color)) 3268 .setContentTitle(title) 3269 .setContentText(details) 3270 .setContentIntent(intent) 3271 .setLocalOnly(true) 3272 .setPriority(highPriority ? 3273 Notification.PRIORITY_HIGH : 3274 Notification.PRIORITY_DEFAULT) 3275 .setDefaults(Notification.DEFAULT_ALL) 3276 .setOnlyAlertOnce(true) 3277 .build(); 3278 3279 try { 3280 notificationManager.notify(NOTIFICATION_ID, id, notification); 3281 } catch (NullPointerException npe) { 3282 loge("setNotificationVisible: visible notificationManager npe=" + npe); 3283 npe.printStackTrace(); 3284 } 3285 } else { 3286 try { 3287 notificationManager.cancel(NOTIFICATION_ID, id); 3288 } catch (NullPointerException npe) { 3289 loge("setNotificationVisible: cancel notificationManager npe=" + npe); 3290 npe.printStackTrace(); 3291 } 3292 } 3293 } 3294 3295 /** Location to an updatable file listing carrier provisioning urls. 3296 * An example: 3297 * 3298 * <?xml version="1.0" encoding="utf-8"?> 3299 * <provisioningUrls> 3300 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl> 3301 * </provisioningUrls> 3302 */ 3303 private static final String PROVISIONING_URL_PATH = 3304 "/data/misc/radio/provisioning_urls.xml"; 3305 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH); 3306 3307 /** XML tag for root element. */ 3308 private static final String TAG_PROVISIONING_URLS = "provisioningUrls"; 3309 /** XML tag for individual url */ 3310 private static final String TAG_PROVISIONING_URL = "provisioningUrl"; 3311 /** XML attribute for mcc */ 3312 private static final String ATTR_MCC = "mcc"; 3313 /** XML attribute for mnc */ 3314 private static final String ATTR_MNC = "mnc"; 3315 3316 private String getProvisioningUrlBaseFromFile() { 3317 FileReader fileReader = null; 3318 XmlPullParser parser = null; 3319 Configuration config = mContext.getResources().getConfiguration(); 3320 3321 try { 3322 fileReader = new FileReader(mProvisioningUrlFile); 3323 parser = Xml.newPullParser(); 3324 parser.setInput(fileReader); 3325 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS); 3326 3327 while (true) { 3328 XmlUtils.nextElement(parser); 3329 3330 String element = parser.getName(); 3331 if (element == null) break; 3332 3333 if (element.equals(TAG_PROVISIONING_URL)) { 3334 String mcc = parser.getAttributeValue(null, ATTR_MCC); 3335 try { 3336 if (mcc != null && Integer.parseInt(mcc) == config.mcc) { 3337 String mnc = parser.getAttributeValue(null, ATTR_MNC); 3338 if (mnc != null && Integer.parseInt(mnc) == config.mnc) { 3339 parser.next(); 3340 if (parser.getEventType() == XmlPullParser.TEXT) { 3341 return parser.getText(); 3342 } 3343 } 3344 } 3345 } catch (NumberFormatException e) { 3346 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e); 3347 } 3348 } 3349 } 3350 return null; 3351 } catch (FileNotFoundException e) { 3352 loge("Carrier Provisioning Urls file not found"); 3353 } catch (XmlPullParserException e) { 3354 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e); 3355 } catch (IOException e) { 3356 loge("I/O exception reading Carrier Provisioning Urls file: " + e); 3357 } finally { 3358 if (fileReader != null) { 3359 try { 3360 fileReader.close(); 3361 } catch (IOException e) {} 3362 } 3363 } 3364 return null; 3365 } 3366 3367 @Override 3368 public String getMobileProvisioningUrl() { 3369 enforceConnectivityInternalPermission(); 3370 String url = getProvisioningUrlBaseFromFile(); 3371 if (TextUtils.isEmpty(url)) { 3372 url = mContext.getResources().getString(R.string.mobile_provisioning_url); 3373 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url); 3374 } else { 3375 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url); 3376 } 3377 // populate the iccid, imei and phone number in the provisioning url. 3378 if (!TextUtils.isEmpty(url)) { 3379 String phoneNumber = mTelephonyManager.getLine1Number(); 3380 if (TextUtils.isEmpty(phoneNumber)) { 3381 phoneNumber = "0000000000"; 3382 } 3383 url = String.format(url, 3384 mTelephonyManager.getSimSerialNumber() /* ICCID */, 3385 mTelephonyManager.getDeviceId() /* IMEI */, 3386 phoneNumber /* Phone numer */); 3387 } 3388 3389 return url; 3390 } 3391 3392 @Override 3393 public void setProvisioningNotificationVisible(boolean visible, int networkType, 3394 String action) { 3395 enforceConnectivityInternalPermission(); 3396 final long ident = Binder.clearCallingIdentity(); 3397 try { 3398 setProvNotificationVisible(visible, networkType, action); 3399 } finally { 3400 Binder.restoreCallingIdentity(ident); 3401 } 3402 } 3403 3404 @Override 3405 public void setAirplaneMode(boolean enable) { 3406 enforceConnectivityInternalPermission(); 3407 final long ident = Binder.clearCallingIdentity(); 3408 try { 3409 final ContentResolver cr = mContext.getContentResolver(); 3410 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 3411 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 3412 intent.putExtra("state", enable); 3413 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 3414 } finally { 3415 Binder.restoreCallingIdentity(ident); 3416 } 3417 } 3418 3419 private void onUserStart(int userId) { 3420 synchronized(mVpns) { 3421 Vpn userVpn = mVpns.get(userId); 3422 if (userVpn != null) { 3423 loge("Starting user already has a VPN"); 3424 return; 3425 } 3426 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); 3427 mVpns.put(userId, userVpn); 3428 } 3429 } 3430 3431 private void onUserStop(int userId) { 3432 synchronized(mVpns) { 3433 Vpn userVpn = mVpns.get(userId); 3434 if (userVpn == null) { 3435 loge("Stopping user has no VPN"); 3436 return; 3437 } 3438 mVpns.delete(userId); 3439 } 3440 } 3441 3442 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() { 3443 @Override 3444 public void onReceive(Context context, Intent intent) { 3445 final String action = intent.getAction(); 3446 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 3447 if (userId == UserHandle.USER_NULL) return; 3448 3449 if (Intent.ACTION_USER_STARTING.equals(action)) { 3450 onUserStart(userId); 3451 } else if (Intent.ACTION_USER_STOPPING.equals(action)) { 3452 onUserStop(userId); 3453 } 3454 } 3455 }; 3456 3457 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = 3458 new HashMap<Messenger, NetworkFactoryInfo>(); 3459 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = 3460 new HashMap<NetworkRequest, NetworkRequestInfo>(); 3461 3462 private static class NetworkFactoryInfo { 3463 public final String name; 3464 public final Messenger messenger; 3465 public final AsyncChannel asyncChannel; 3466 3467 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) { 3468 this.name = name; 3469 this.messenger = messenger; 3470 this.asyncChannel = asyncChannel; 3471 } 3472 } 3473 3474 /** 3475 * Tracks info about the requester. 3476 * Also used to notice when the calling process dies so we can self-expire 3477 */ 3478 private class NetworkRequestInfo implements IBinder.DeathRecipient { 3479 static final boolean REQUEST = true; 3480 static final boolean LISTEN = false; 3481 3482 final NetworkRequest request; 3483 final PendingIntent mPendingIntent; 3484 boolean mPendingIntentSent; 3485 private final IBinder mBinder; 3486 final int mPid; 3487 final int mUid; 3488 final Messenger messenger; 3489 final boolean isRequest; 3490 3491 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) { 3492 request = r; 3493 mPendingIntent = pi; 3494 messenger = null; 3495 mBinder = null; 3496 mPid = getCallingPid(); 3497 mUid = getCallingUid(); 3498 this.isRequest = isRequest; 3499 } 3500 3501 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) { 3502 super(); 3503 messenger = m; 3504 request = r; 3505 mBinder = binder; 3506 mPid = getCallingPid(); 3507 mUid = getCallingUid(); 3508 this.isRequest = isRequest; 3509 mPendingIntent = null; 3510 3511 try { 3512 mBinder.linkToDeath(this, 0); 3513 } catch (RemoteException e) { 3514 binderDied(); 3515 } 3516 } 3517 3518 void unlinkDeathRecipient() { 3519 if (mBinder != null) { 3520 mBinder.unlinkToDeath(this, 0); 3521 } 3522 } 3523 3524 public void binderDied() { 3525 log("ConnectivityService NetworkRequestInfo binderDied(" + 3526 request + ", " + mBinder + ")"); 3527 releaseNetworkRequest(request); 3528 } 3529 3530 public String toString() { 3531 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" + 3532 mPid + " for " + request + 3533 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent); 3534 } 3535 } 3536 3537 private void ensureImmutableCapabilities(NetworkCapabilities networkCapabilities) { 3538 if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) { 3539 throw new IllegalArgumentException( 3540 "Cannot request network with NET_CAPABILITY_VALIDATED"); 3541 } 3542 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) { 3543 throw new IllegalArgumentException( 3544 "Cannot request network with NET_CAPABILITY_CAPTIVE_PORTAL"); 3545 } 3546 } 3547 3548 @Override 3549 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities, 3550 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) { 3551 networkCapabilities = new NetworkCapabilities(networkCapabilities); 3552 enforceNetworkRequestPermissions(networkCapabilities); 3553 enforceMeteredApnPolicy(networkCapabilities); 3554 ensureImmutableCapabilities(networkCapabilities); 3555 3556 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) { 3557 throw new IllegalArgumentException("Bad timeout specified"); 3558 } 3559 3560 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType, 3561 nextNetworkRequestId()); 3562 if (DBG) log("requestNetwork for " + networkRequest); 3563 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, 3564 NetworkRequestInfo.REQUEST); 3565 3566 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri)); 3567 if (timeoutMs > 0) { 3568 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST, 3569 nri), timeoutMs); 3570 } 3571 return networkRequest; 3572 } 3573 3574 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) { 3575 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) { 3576 enforceConnectivityInternalPermission(); 3577 } else { 3578 enforceChangePermission(); 3579 } 3580 } 3581 3582 @Override 3583 public boolean requestBandwidthUpdate(Network network) { 3584 enforceAccessPermission(); 3585 NetworkAgentInfo nai = null; 3586 if (network == null) { 3587 return false; 3588 } 3589 synchronized (mNetworkForNetId) { 3590 nai = mNetworkForNetId.get(network.netId); 3591 } 3592 if (nai != null) { 3593 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE); 3594 return true; 3595 } 3596 return false; 3597 } 3598 3599 3600 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) { 3601 // if UID is restricted, don't allow them to bring up metered APNs 3602 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) { 3603 final int uidRules; 3604 final int uid = Binder.getCallingUid(); 3605 synchronized(mRulesLock) { 3606 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL); 3607 } 3608 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) { 3609 // we could silently fail or we can filter the available nets to only give 3610 // them those they have access to. Chose the more useful 3611 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED); 3612 } 3613 } 3614 } 3615 3616 @Override 3617 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities, 3618 PendingIntent operation) { 3619 checkNotNull(operation, "PendingIntent cannot be null."); 3620 networkCapabilities = new NetworkCapabilities(networkCapabilities); 3621 enforceNetworkRequestPermissions(networkCapabilities); 3622 enforceMeteredApnPolicy(networkCapabilities); 3623 ensureImmutableCapabilities(networkCapabilities); 3624 3625 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE, 3626 nextNetworkRequestId()); 3627 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation); 3628 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation, 3629 NetworkRequestInfo.REQUEST); 3630 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT, 3631 nri)); 3632 return networkRequest; 3633 } 3634 3635 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) { 3636 mHandler.sendMessageDelayed( 3637 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, 3638 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs); 3639 } 3640 3641 @Override 3642 public void releasePendingNetworkRequest(PendingIntent operation) { 3643 checkNotNull(operation, "PendingIntent cannot be null."); 3644 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, 3645 getCallingUid(), 0, operation)); 3646 } 3647 3648 // In order to implement the compatibility measure for pre-M apps that call 3649 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly, 3650 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork. 3651 // This ensures it has permission to do so. 3652 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) { 3653 if (nc == null) { 3654 return false; 3655 } 3656 int[] transportTypes = nc.getTransportTypes(); 3657 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) { 3658 return false; 3659 } 3660 try { 3661 mContext.enforceCallingOrSelfPermission( 3662 android.Manifest.permission.ACCESS_WIFI_STATE, 3663 "ConnectivityService"); 3664 } catch (SecurityException e) { 3665 return false; 3666 } 3667 return true; 3668 } 3669 3670 @Override 3671 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities, 3672 Messenger messenger, IBinder binder) { 3673 if (!hasWifiNetworkListenPermission(networkCapabilities)) { 3674 enforceAccessPermission(); 3675 } 3676 3677 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities( 3678 networkCapabilities), TYPE_NONE, nextNetworkRequestId()); 3679 if (DBG) log("listenForNetwork for " + networkRequest); 3680 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, 3681 NetworkRequestInfo.LISTEN); 3682 3683 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 3684 return networkRequest; 3685 } 3686 3687 @Override 3688 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities, 3689 PendingIntent operation) { 3690 checkNotNull(operation, "PendingIntent cannot be null."); 3691 if (!hasWifiNetworkListenPermission(networkCapabilities)) { 3692 enforceAccessPermission(); 3693 } 3694 3695 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities( 3696 networkCapabilities), TYPE_NONE, nextNetworkRequestId()); 3697 if (DBG) log("pendingListenForNetwork for " + networkRequest + " to trigger " + operation); 3698 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation, 3699 NetworkRequestInfo.LISTEN); 3700 3701 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 3702 } 3703 3704 @Override 3705 public void releaseNetworkRequest(NetworkRequest networkRequest) { 3706 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 3707 0, networkRequest)); 3708 } 3709 3710 @Override 3711 public void registerNetworkFactory(Messenger messenger, String name) { 3712 enforceConnectivityInternalPermission(); 3713 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel()); 3714 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi)); 3715 } 3716 3717 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) { 3718 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name); 3719 mNetworkFactoryInfos.put(nfi.messenger, nfi); 3720 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger); 3721 } 3722 3723 @Override 3724 public void unregisterNetworkFactory(Messenger messenger) { 3725 enforceConnectivityInternalPermission(); 3726 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger)); 3727 } 3728 3729 private void handleUnregisterNetworkFactory(Messenger messenger) { 3730 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger); 3731 if (nfi == null) { 3732 loge("Failed to find Messenger in unregisterNetworkFactory"); 3733 return; 3734 } 3735 if (DBG) log("unregisterNetworkFactory for " + nfi.name); 3736 } 3737 3738 /** 3739 * NetworkAgentInfo supporting a request by requestId. 3740 * These have already been vetted (their Capabilities satisfy the request) 3741 * and the are the highest scored network available. 3742 * the are keyed off the Requests requestId. 3743 */ 3744 // TODO: Yikes, this is accessed on multiple threads: add synchronization. 3745 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = 3746 new SparseArray<NetworkAgentInfo>(); 3747 3748 // NOTE: Accessed on multiple threads, must be synchronized on itself. 3749 @GuardedBy("mNetworkForNetId") 3750 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = 3751 new SparseArray<NetworkAgentInfo>(); 3752 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId. 3753 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so 3754 // there may not be a strict 1:1 correlation between the two. 3755 @GuardedBy("mNetworkForNetId") 3756 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray(); 3757 3758 // NetworkAgentInfo keyed off its connecting messenger 3759 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays 3760 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump(). 3761 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = 3762 new HashMap<Messenger, NetworkAgentInfo>(); 3763 3764 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated. 3765 private final NetworkRequest mDefaultRequest; 3766 3767 // Request used to optionally keep mobile data active even when higher 3768 // priority networks like Wi-Fi are active. 3769 private final NetworkRequest mDefaultMobileDataRequest; 3770 3771 private NetworkAgentInfo getDefaultNetwork() { 3772 return mNetworkForRequestId.get(mDefaultRequest.requestId); 3773 } 3774 3775 private boolean isDefaultNetwork(NetworkAgentInfo nai) { 3776 return nai == getDefaultNetwork(); 3777 } 3778 3779 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo, 3780 LinkProperties linkProperties, NetworkCapabilities networkCapabilities, 3781 int currentScore, NetworkMisc networkMisc) { 3782 enforceConnectivityInternalPermission(); 3783 3784 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network 3785 // satisfies mDefaultRequest. 3786 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), 3787 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties( 3788 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore, 3789 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest); 3790 synchronized (this) { 3791 nai.networkMonitor.systemReady = mSystemReady; 3792 } 3793 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network); 3794 if (DBG) log("registerNetworkAgent " + nai); 3795 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai)); 3796 return nai.network.netId; 3797 } 3798 3799 private void handleRegisterNetworkAgent(NetworkAgentInfo na) { 3800 if (VDBG) log("Got NetworkAgent Messenger"); 3801 mNetworkAgentInfos.put(na.messenger, na); 3802 synchronized (mNetworkForNetId) { 3803 mNetworkForNetId.put(na.network.netId, na); 3804 } 3805 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger); 3806 NetworkInfo networkInfo = na.networkInfo; 3807 na.networkInfo = null; 3808 updateNetworkInfo(na, networkInfo); 3809 } 3810 3811 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) { 3812 LinkProperties newLp = networkAgent.linkProperties; 3813 int netId = networkAgent.network.netId; 3814 3815 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before 3816 // we do anything else, make sure its LinkProperties are accurate. 3817 if (networkAgent.clatd != null) { 3818 networkAgent.clatd.fixupLinkProperties(oldLp); 3819 } 3820 3821 updateInterfaces(newLp, oldLp, netId); 3822 updateMtu(newLp, oldLp); 3823 // TODO - figure out what to do for clat 3824// for (LinkProperties lp : newLp.getStackedLinks()) { 3825// updateMtu(lp, null); 3826// } 3827 updateTcpBufferSizes(networkAgent); 3828 3829 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075 3830 // In L, we used it only when the network had Internet access but provided no DNS servers. 3831 // For now, just disable it, and if disabling it doesn't break things, remove it. 3832 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability( 3833 // NET_CAPABILITY_INTERNET); 3834 final boolean useDefaultDns = false; 3835 final boolean flushDns = updateRoutes(newLp, oldLp, netId); 3836 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns); 3837 3838 updateClat(newLp, oldLp, networkAgent); 3839 if (isDefaultNetwork(networkAgent)) { 3840 handleApplyDefaultProxy(newLp.getHttpProxy()); 3841 } else { 3842 updateProxy(newLp, oldLp, networkAgent); 3843 } 3844 // TODO - move this check to cover the whole function 3845 if (!Objects.equals(newLp, oldLp)) { 3846 notifyIfacesChanged(); 3847 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED); 3848 } 3849 } 3850 3851 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) { 3852 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted(); 3853 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai); 3854 3855 if (!wasRunningClat && shouldRunClat) { 3856 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai); 3857 nai.clatd.start(); 3858 } else if (wasRunningClat && !shouldRunClat) { 3859 nai.clatd.stop(); 3860 } 3861 } 3862 3863 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) { 3864 CompareResult<String> interfaceDiff = new CompareResult<String>(); 3865 if (oldLp != null) { 3866 interfaceDiff = oldLp.compareAllInterfaceNames(newLp); 3867 } else if (newLp != null) { 3868 interfaceDiff.added = newLp.getAllInterfaceNames(); 3869 } 3870 for (String iface : interfaceDiff.added) { 3871 try { 3872 if (DBG) log("Adding iface " + iface + " to network " + netId); 3873 mNetd.addInterfaceToNetwork(iface, netId); 3874 } catch (Exception e) { 3875 loge("Exception adding interface: " + e); 3876 } 3877 } 3878 for (String iface : interfaceDiff.removed) { 3879 try { 3880 if (DBG) log("Removing iface " + iface + " from network " + netId); 3881 mNetd.removeInterfaceFromNetwork(iface, netId); 3882 } catch (Exception e) { 3883 loge("Exception removing interface: " + e); 3884 } 3885 } 3886 } 3887 3888 /** 3889 * Have netd update routes from oldLp to newLp. 3890 * @return true if routes changed between oldLp and newLp 3891 */ 3892 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) { 3893 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 3894 if (oldLp != null) { 3895 routeDiff = oldLp.compareAllRoutes(newLp); 3896 } else if (newLp != null) { 3897 routeDiff.added = newLp.getAllRoutes(); 3898 } 3899 3900 // add routes before removing old in case it helps with continuous connectivity 3901 3902 // do this twice, adding non-nexthop routes first, then routes they are dependent on 3903 for (RouteInfo route : routeDiff.added) { 3904 if (route.hasGateway()) continue; 3905 if (DBG) log("Adding Route [" + route + "] to network " + netId); 3906 try { 3907 mNetd.addRoute(netId, route); 3908 } catch (Exception e) { 3909 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) { 3910 loge("Exception in addRoute for non-gateway: " + e); 3911 } 3912 } 3913 } 3914 for (RouteInfo route : routeDiff.added) { 3915 if (route.hasGateway() == false) continue; 3916 if (DBG) log("Adding Route [" + route + "] to network " + netId); 3917 try { 3918 mNetd.addRoute(netId, route); 3919 } catch (Exception e) { 3920 if ((route.getGateway() instanceof Inet4Address) || VDBG) { 3921 loge("Exception in addRoute for gateway: " + e); 3922 } 3923 } 3924 } 3925 3926 for (RouteInfo route : routeDiff.removed) { 3927 if (DBG) log("Removing Route [" + route + "] from network " + netId); 3928 try { 3929 mNetd.removeRoute(netId, route); 3930 } catch (Exception e) { 3931 loge("Exception in removeRoute: " + e); 3932 } 3933 } 3934 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty(); 3935 } 3936 3937 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId, 3938 boolean flush, boolean useDefaultDns) { 3939 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) { 3940 Collection<InetAddress> dnses = newLp.getDnsServers(); 3941 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) { 3942 dnses = new ArrayList(); 3943 dnses.add(mDefaultDns); 3944 if (DBG) { 3945 loge("no dns provided for netId " + netId + ", so using defaults"); 3946 } 3947 } 3948 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses); 3949 try { 3950 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), 3951 newLp.getDomains()); 3952 } catch (Exception e) { 3953 loge("Exception in setDnsServersForNetwork: " + e); 3954 } 3955 final NetworkAgentInfo defaultNai = getDefaultNetwork(); 3956 if (defaultNai != null && defaultNai.network.netId == netId) { 3957 setDefaultDnsSystemProperties(dnses); 3958 } 3959 flushVmDnsCache(); 3960 } else if (flush) { 3961 try { 3962 mNetd.flushNetworkDnsCache(netId); 3963 } catch (Exception e) { 3964 loge("Exception in flushNetworkDnsCache: " + e); 3965 } 3966 flushVmDnsCache(); 3967 } 3968 } 3969 3970 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) { 3971 int last = 0; 3972 for (InetAddress dns : dnses) { 3973 ++last; 3974 String key = "net.dns" + last; 3975 String value = dns.getHostAddress(); 3976 SystemProperties.set(key, value); 3977 } 3978 for (int i = last + 1; i <= mNumDnsEntries; ++i) { 3979 String key = "net.dns" + i; 3980 SystemProperties.set(key, ""); 3981 } 3982 mNumDnsEntries = last; 3983 } 3984 3985 /** 3986 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities} 3987 * augmented with any stateful capabilities implied from {@code networkAgent} 3988 * (e.g., validated status and captive portal status). 3989 * 3990 * @param nai the network having its capabilities updated. 3991 * @param networkCapabilities the new network capabilities. 3992 */ 3993 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) { 3994 // Don't modify caller's NetworkCapabilities. 3995 networkCapabilities = new NetworkCapabilities(networkCapabilities); 3996 if (nai.lastValidated) { 3997 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED); 3998 } else { 3999 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED); 4000 } 4001 if (nai.lastCaptivePortalDetected) { 4002 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL); 4003 } else { 4004 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL); 4005 } 4006 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) { 4007 final int oldScore = nai.getCurrentScore(); 4008 synchronized (nai) { 4009 nai.networkCapabilities = networkCapabilities; 4010 } 4011 rematchAllNetworksAndRequests(nai, oldScore); 4012 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED); 4013 } 4014 } 4015 4016 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) { 4017 for (int i = 0; i < nai.networkRequests.size(); i++) { 4018 NetworkRequest nr = nai.networkRequests.valueAt(i); 4019 // Don't send listening requests to factories. b/17393458 4020 if (!isRequest(nr)) continue; 4021 sendUpdatedScoreToFactories(nr, nai.getCurrentScore()); 4022 } 4023 } 4024 4025 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) { 4026 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString()); 4027 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 4028 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0, 4029 networkRequest); 4030 } 4031 } 4032 4033 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent, 4034 int notificationType) { 4035 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) { 4036 Intent intent = new Intent(); 4037 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network); 4038 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request); 4039 nri.mPendingIntentSent = true; 4040 sendIntent(nri.mPendingIntent, intent); 4041 } 4042 // else not handled 4043 } 4044 4045 private void sendIntent(PendingIntent pendingIntent, Intent intent) { 4046 mPendingIntentWakeLock.acquire(); 4047 try { 4048 if (DBG) log("Sending " + pendingIntent); 4049 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */); 4050 } catch (PendingIntent.CanceledException e) { 4051 if (DBG) log(pendingIntent + " was not sent, it had been canceled."); 4052 mPendingIntentWakeLock.release(); 4053 releasePendingNetworkRequest(pendingIntent); 4054 } 4055 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished() 4056 } 4057 4058 @Override 4059 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, 4060 String resultData, Bundle resultExtras) { 4061 if (DBG) log("Finished sending " + pendingIntent); 4062 mPendingIntentWakeLock.release(); 4063 // Release with a delay so the receiving client has an opportunity to put in its 4064 // own request. 4065 releasePendingNetworkRequestWithDelay(pendingIntent); 4066 } 4067 4068 private void callCallbackForRequest(NetworkRequestInfo nri, 4069 NetworkAgentInfo networkAgent, int notificationType) { 4070 if (nri.messenger == null) return; // Default request has no msgr 4071 Bundle bundle = new Bundle(); 4072 bundle.putParcelable(NetworkRequest.class.getSimpleName(), 4073 new NetworkRequest(nri.request)); 4074 Message msg = Message.obtain(); 4075 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL && 4076 notificationType != ConnectivityManager.CALLBACK_RELEASED) { 4077 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network); 4078 } 4079 switch (notificationType) { 4080 case ConnectivityManager.CALLBACK_LOSING: { 4081 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor 4082 break; 4083 } 4084 case ConnectivityManager.CALLBACK_CAP_CHANGED: { 4085 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(), 4086 new NetworkCapabilities(networkAgent.networkCapabilities)); 4087 break; 4088 } 4089 case ConnectivityManager.CALLBACK_IP_CHANGED: { 4090 bundle.putParcelable(LinkProperties.class.getSimpleName(), 4091 new LinkProperties(networkAgent.linkProperties)); 4092 break; 4093 } 4094 } 4095 msg.what = notificationType; 4096 msg.setData(bundle); 4097 try { 4098 if (VDBG) { 4099 log("sending notification " + notifyTypeToName(notificationType) + 4100 " for " + nri.request); 4101 } 4102 nri.messenger.send(msg); 4103 } catch (RemoteException e) { 4104 // may occur naturally in the race of binder death. 4105 loge("RemoteException caught trying to send a callback msg for " + nri.request); 4106 } 4107 } 4108 4109 private void teardownUnneededNetwork(NetworkAgentInfo nai) { 4110 for (int i = 0; i < nai.networkRequests.size(); i++) { 4111 NetworkRequest nr = nai.networkRequests.valueAt(i); 4112 // Ignore listening requests. 4113 if (!isRequest(nr)) continue; 4114 loge("Dead network still had at least " + nr); 4115 break; 4116 } 4117 nai.asyncChannel.disconnect(); 4118 } 4119 4120 private void handleLingerComplete(NetworkAgentInfo oldNetwork) { 4121 if (oldNetwork == null) { 4122 loge("Unknown NetworkAgentInfo in handleLingerComplete"); 4123 return; 4124 } 4125 if (DBG) log("handleLingerComplete for " + oldNetwork.name()); 4126 teardownUnneededNetwork(oldNetwork); 4127 } 4128 4129 private void makeDefault(NetworkAgentInfo newNetwork) { 4130 if (DBG) log("Switching to new default network: " + newNetwork); 4131 setupDataActivityTracking(newNetwork); 4132 try { 4133 mNetd.setDefaultNetId(newNetwork.network.netId); 4134 } catch (Exception e) { 4135 loge("Exception setting default network :" + e); 4136 } 4137 notifyLockdownVpn(newNetwork); 4138 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy()); 4139 updateTcpBufferSizes(newNetwork); 4140 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers()); 4141 } 4142 4143 // Handles a network appearing or improving its score. 4144 // 4145 // - Evaluates all current NetworkRequests that can be 4146 // satisfied by newNetwork, and reassigns to newNetwork 4147 // any such requests for which newNetwork is the best. 4148 // 4149 // - Lingers any validated Networks that as a result are no longer 4150 // needed. A network is needed if it is the best network for 4151 // one or more NetworkRequests, or if it is a VPN. 4152 // 4153 // - Tears down newNetwork if it just became validated 4154 // but turns out to be unneeded. 4155 // 4156 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated 4157 // networks that have no chance (i.e. even if validated) 4158 // of becoming the highest scoring network. 4159 // 4160 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy, 4161 // it does not remove NetworkRequests that other Networks could better satisfy. 4162 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}. 4163 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests} 4164 // as it performs better by a factor of the number of Networks. 4165 // 4166 // @param newNetwork is the network to be matched against NetworkRequests. 4167 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be 4168 // performed to tear down unvalidated networks that have no chance (i.e. even if 4169 // validated) of becoming the highest scoring network. 4170 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, 4171 ReapUnvalidatedNetworks reapUnvalidatedNetworks) { 4172 if (!newNetwork.created) return; 4173 boolean keep = newNetwork.isVPN(); 4174 boolean isNewDefault = false; 4175 NetworkAgentInfo oldDefaultNetwork = null; 4176 if (DBG) log("rematching " + newNetwork.name()); 4177 // Find and migrate to this Network any NetworkRequests for 4178 // which this network is now the best. 4179 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>(); 4180 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>(); 4181 if (VDBG) log(" network has: " + newNetwork.networkCapabilities); 4182 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 4183 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId); 4184 if (newNetwork == currentNetwork) { 4185 if (VDBG) { 4186 log("Network " + newNetwork.name() + " was already satisfying" + 4187 " request " + nri.request.requestId + ". No change."); 4188 } 4189 keep = true; 4190 continue; 4191 } 4192 4193 // check if it satisfies the NetworkCapabilities 4194 if (VDBG) log(" checking if request is satisfied: " + nri.request); 4195 if (newNetwork.satisfies(nri.request)) { 4196 if (!nri.isRequest) { 4197 // This is not a request, it's a callback listener. 4198 // Add it to newNetwork regardless of score. 4199 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri); 4200 continue; 4201 } 4202 4203 // next check if it's better than any current network we're using for 4204 // this request 4205 if (VDBG) { 4206 log("currentScore = " + 4207 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) + 4208 ", newScore = " + newNetwork.getCurrentScore()); 4209 } 4210 if (currentNetwork == null || 4211 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) { 4212 if (currentNetwork != null) { 4213 if (DBG) log(" accepting network in place of " + currentNetwork.name()); 4214 currentNetwork.networkRequests.remove(nri.request.requestId); 4215 currentNetwork.networkLingered.add(nri.request); 4216 affectedNetworks.add(currentNetwork); 4217 } else { 4218 if (DBG) log(" accepting network in place of null"); 4219 } 4220 unlinger(newNetwork); 4221 mNetworkForRequestId.put(nri.request.requestId, newNetwork); 4222 if (!newNetwork.addRequest(nri.request)) { 4223 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request); 4224 } 4225 addedRequests.add(nri); 4226 keep = true; 4227 // Tell NetworkFactories about the new score, so they can stop 4228 // trying to connect if they know they cannot match it. 4229 // TODO - this could get expensive if we have alot of requests for this 4230 // network. Think about if there is a way to reduce this. Push 4231 // netid->request mapping to each factory? 4232 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore()); 4233 if (mDefaultRequest.requestId == nri.request.requestId) { 4234 isNewDefault = true; 4235 oldDefaultNetwork = currentNetwork; 4236 } 4237 } 4238 } 4239 } 4240 // Linger any networks that are no longer needed. 4241 for (NetworkAgentInfo nai : affectedNetworks) { 4242 if (nai.lingering) { 4243 // Already lingered. Nothing to do. This can only happen if "nai" is in 4244 // "affectedNetworks" twice. The reasoning being that to get added to 4245 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest 4246 // (i.e. not lingered) so it could have only been lingered by this loop. 4247 // unneeded(nai) will be false and we'll call unlinger() below which would 4248 // be bad, so handle it here. 4249 } else if (unneeded(nai)) { 4250 linger(nai); 4251 } else { 4252 // Clear nai.networkLingered we might have added above. 4253 unlinger(nai); 4254 } 4255 } 4256 if (keep) { 4257 if (isNewDefault) { 4258 // Notify system services that this network is up. 4259 makeDefault(newNetwork); 4260 synchronized (ConnectivityService.this) { 4261 // have a new default network, release the transition wakelock in 4262 // a second if it's held. The second pause is to allow apps 4263 // to reconnect over the new network 4264 if (mNetTransitionWakeLock.isHeld()) { 4265 mHandler.sendMessageDelayed(mHandler.obtainMessage( 4266 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 4267 mNetTransitionWakeLockSerialNumber, 0), 4268 1000); 4269 } 4270 } 4271 } 4272 4273 // do this after the default net is switched, but 4274 // before LegacyTypeTracker sends legacy broadcasts 4275 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri); 4276 4277 if (isNewDefault) { 4278 // Maintain the illusion: since the legacy API only 4279 // understands one network at a time, we must pretend 4280 // that the current default network disconnected before 4281 // the new one connected. 4282 if (oldDefaultNetwork != null) { 4283 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(), 4284 oldDefaultNetwork, true); 4285 } 4286 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0; 4287 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork); 4288 notifyLockdownVpn(newNetwork); 4289 } 4290 4291 // Notify battery stats service about this network, both the normal 4292 // interface and any stacked links. 4293 // TODO: Avoid redoing this; this must only be done once when a network comes online. 4294 try { 4295 final IBatteryStats bs = BatteryStatsService.getService(); 4296 final int type = newNetwork.networkInfo.getType(); 4297 4298 final String baseIface = newNetwork.linkProperties.getInterfaceName(); 4299 bs.noteNetworkInterfaceType(baseIface, type); 4300 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) { 4301 final String stackedIface = stacked.getInterfaceName(); 4302 bs.noteNetworkInterfaceType(stackedIface, type); 4303 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface); 4304 } 4305 } catch (RemoteException ignored) { 4306 } 4307 4308 // This has to happen after the notifyNetworkCallbacks as that tickles each 4309 // ConnectivityManager instance so that legacy requests correctly bind dns 4310 // requests to this network. The legacy users are listening for this bcast 4311 // and will generally do a dns request so they can ensureRouteToHost and if 4312 // they do that before the callbacks happen they'll use the default network. 4313 // 4314 // TODO: Is there still a race here? We send the broadcast 4315 // after sending the callback, but if the app can receive the 4316 // broadcast before the callback, it might still break. 4317 // 4318 // This *does* introduce a race where if the user uses the new api 4319 // (notification callbacks) and then uses the old api (getNetworkInfo(type)) 4320 // they may get old info. Reverse this after the old startUsing api is removed. 4321 // This is on top of the multiple intent sequencing referenced in the todo above. 4322 for (int i = 0; i < newNetwork.networkRequests.size(); i++) { 4323 NetworkRequest nr = newNetwork.networkRequests.valueAt(i); 4324 if (nr.legacyType != TYPE_NONE && isRequest(nr)) { 4325 // legacy type tracker filters out repeat adds 4326 mLegacyTypeTracker.add(nr.legacyType, newNetwork); 4327 } 4328 } 4329 4330 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above, 4331 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest 4332 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the 4333 // newNetwork to the tracker explicitly (it's a no-op if it has already been added). 4334 if (newNetwork.isVPN()) { 4335 mLegacyTypeTracker.add(TYPE_VPN, newNetwork); 4336 } 4337 } 4338 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) { 4339 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 4340 if (unneeded(nai)) { 4341 if (DBG) log("Reaping " + nai.name()); 4342 teardownUnneededNetwork(nai); 4343 } 4344 } 4345 } 4346 } 4347 4348 /** 4349 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks 4350 * being disconnected. 4351 * @param changed If only one Network's score or capabilities have been modified since the last 4352 * time this function was called, pass this Network in this argument, otherwise pass 4353 * null. 4354 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not 4355 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via 4356 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if 4357 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a 4358 * network's score. 4359 */ 4360 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) { 4361 // TODO: This may get slow. The "changed" parameter is provided for future optimization 4362 // to avoid the slowness. It is not simply enough to process just "changed", for 4363 // example in the case where "changed"'s score decreases and another network should begin 4364 // satifying a NetworkRequest that "changed" currently satisfies. 4365 4366 // Optimization: Only reprocess "changed" if its score improved. This is safe because it 4367 // can only add more NetworkRequests satisfied by "changed", and this is exactly what 4368 // rematchNetworkAndRequests() handles. 4369 if (changed != null && oldScore < changed.getCurrentScore()) { 4370 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP); 4371 } else { 4372 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray( 4373 new NetworkAgentInfo[mNetworkAgentInfos.size()]); 4374 // Rematch higher scoring networks first to prevent requests first matching a lower 4375 // scoring network and then a higher scoring network, which could produce multiple 4376 // callbacks and inadvertently unlinger networks. 4377 Arrays.sort(nais); 4378 for (NetworkAgentInfo nai : nais) { 4379 rematchNetworkAndRequests(nai, 4380 // Only reap the last time through the loop. Reaping before all rematching 4381 // is complete could incorrectly teardown a network that hasn't yet been 4382 // rematched. 4383 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP 4384 : ReapUnvalidatedNetworks.REAP); 4385 } 4386 } 4387 } 4388 4389 private void updateInetCondition(NetworkAgentInfo nai) { 4390 // Don't bother updating until we've graduated to validated at least once. 4391 if (!nai.everValidated) return; 4392 // For now only update icons for default connection. 4393 // TODO: Update WiFi and cellular icons separately. b/17237507 4394 if (!isDefaultNetwork(nai)) return; 4395 4396 int newInetCondition = nai.lastValidated ? 100 : 0; 4397 // Don't repeat publish. 4398 if (newInetCondition == mDefaultInetConditionPublished) return; 4399 4400 mDefaultInetConditionPublished = newInetCondition; 4401 sendInetConditionBroadcast(nai.networkInfo); 4402 } 4403 4404 private void notifyLockdownVpn(NetworkAgentInfo nai) { 4405 if (mLockdownTracker != null) { 4406 if (nai != null && nai.isVPN()) { 4407 mLockdownTracker.onVpnStateChanged(nai.networkInfo); 4408 } else { 4409 mLockdownTracker.onNetworkInfoChanged(); 4410 } 4411 } 4412 } 4413 4414 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) { 4415 NetworkInfo.State state = newInfo.getState(); 4416 NetworkInfo oldInfo = null; 4417 final int oldScore = networkAgent.getCurrentScore(); 4418 synchronized (networkAgent) { 4419 oldInfo = networkAgent.networkInfo; 4420 networkAgent.networkInfo = newInfo; 4421 } 4422 notifyLockdownVpn(networkAgent); 4423 4424 if (oldInfo != null && oldInfo.getState() == state) { 4425 if (VDBG) log("ignoring duplicate network state non-change"); 4426 return; 4427 } 4428 if (DBG) { 4429 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " + 4430 (oldInfo == null ? "null" : oldInfo.getState()) + 4431 " to " + state); 4432 } 4433 4434 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) { 4435 try { 4436 // This should never fail. Specifying an already in use NetID will cause failure. 4437 if (networkAgent.isVPN()) { 4438 mNetd.createVirtualNetwork(networkAgent.network.netId, 4439 !networkAgent.linkProperties.getDnsServers().isEmpty(), 4440 (networkAgent.networkMisc == null || 4441 !networkAgent.networkMisc.allowBypass)); 4442 } else { 4443 mNetd.createPhysicalNetwork(networkAgent.network.netId); 4444 } 4445 } catch (Exception e) { 4446 loge("Error creating network " + networkAgent.network.netId + ": " 4447 + e.getMessage()); 4448 return; 4449 } 4450 networkAgent.created = true; 4451 updateLinkProperties(networkAgent, null); 4452 notifyIfacesChanged(); 4453 4454 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 4455 scheduleUnvalidatedPrompt(networkAgent); 4456 4457 if (networkAgent.isVPN()) { 4458 // Temporarily disable the default proxy (not global). 4459 synchronized (mProxyLock) { 4460 if (!mDefaultProxyDisabled) { 4461 mDefaultProxyDisabled = true; 4462 if (mGlobalProxy == null && mDefaultProxy != null) { 4463 sendProxyBroadcast(null); 4464 } 4465 } 4466 } 4467 // TODO: support proxy per network. 4468 } 4469 4470 // Consider network even though it is not yet validated. 4471 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP); 4472 4473 // This has to happen after matching the requests, because callbacks are just requests. 4474 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK); 4475 } else if (state == NetworkInfo.State.DISCONNECTED) { 4476 networkAgent.asyncChannel.disconnect(); 4477 if (networkAgent.isVPN()) { 4478 synchronized (mProxyLock) { 4479 if (mDefaultProxyDisabled) { 4480 mDefaultProxyDisabled = false; 4481 if (mGlobalProxy == null && mDefaultProxy != null) { 4482 sendProxyBroadcast(mDefaultProxy); 4483 } 4484 } 4485 } 4486 } 4487 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) || 4488 state == NetworkInfo.State.SUSPENDED) { 4489 // going into or coming out of SUSPEND: rescore and notify 4490 if (networkAgent.getCurrentScore() != oldScore) { 4491 rematchAllNetworksAndRequests(networkAgent, oldScore); 4492 } 4493 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ? 4494 ConnectivityManager.CALLBACK_SUSPENDED : 4495 ConnectivityManager.CALLBACK_RESUMED)); 4496 mLegacyTypeTracker.update(networkAgent); 4497 } 4498 } 4499 4500 private void updateNetworkScore(NetworkAgentInfo nai, int score) { 4501 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score); 4502 if (score < 0) { 4503 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score + 4504 "). Bumping score to min of 0"); 4505 score = 0; 4506 } 4507 4508 final int oldScore = nai.getCurrentScore(); 4509 nai.setCurrentScore(score); 4510 4511 rematchAllNetworksAndRequests(nai, oldScore); 4512 4513 sendUpdatedScoreToFactories(nai); 4514 } 4515 4516 // notify only this one new request of the current state 4517 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) { 4518 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE; 4519 // TODO - read state from monitor to decide what to send. 4520// if (nai.networkMonitor.isLingering()) { 4521// notifyType = NetworkCallbacks.LOSING; 4522// } else if (nai.networkMonitor.isEvaluating()) { 4523// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType); 4524// } 4525 if (nri.mPendingIntent == null) { 4526 callCallbackForRequest(nri, nai, notifyType); 4527 } else { 4528 sendPendingIntentForRequest(nri, nai, notifyType); 4529 } 4530 } 4531 4532 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) { 4533 // The NetworkInfo we actually send out has no bearing on the real 4534 // state of affairs. For example, if the default connection is mobile, 4535 // and a request for HIPRI has just gone away, we need to pretend that 4536 // HIPRI has just disconnected. So we need to set the type to HIPRI and 4537 // the state to DISCONNECTED, even though the network is of type MOBILE 4538 // and is still connected. 4539 NetworkInfo info = new NetworkInfo(nai.networkInfo); 4540 info.setType(type); 4541 if (state != DetailedState.DISCONNECTED) { 4542 info.setDetailedState(state, null, info.getExtraInfo()); 4543 sendConnectedBroadcast(info); 4544 } else { 4545 info.setDetailedState(state, info.getReason(), info.getExtraInfo()); 4546 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 4547 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 4548 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 4549 if (info.isFailover()) { 4550 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 4551 nai.networkInfo.setFailover(false); 4552 } 4553 if (info.getReason() != null) { 4554 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 4555 } 4556 if (info.getExtraInfo() != null) { 4557 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo()); 4558 } 4559 NetworkAgentInfo newDefaultAgent = null; 4560 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 4561 newDefaultAgent = getDefaultNetwork(); 4562 if (newDefaultAgent != null) { 4563 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, 4564 newDefaultAgent.networkInfo); 4565 } else { 4566 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 4567 } 4568 } 4569 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, 4570 mDefaultInetConditionPublished); 4571 sendStickyBroadcast(intent); 4572 if (newDefaultAgent != null) { 4573 sendConnectedBroadcast(newDefaultAgent.networkInfo); 4574 } 4575 } 4576 } 4577 4578 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) { 4579 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name()); 4580 for (int i = 0; i < networkAgent.networkRequests.size(); i++) { 4581 NetworkRequest nr = networkAgent.networkRequests.valueAt(i); 4582 NetworkRequestInfo nri = mNetworkRequests.get(nr); 4583 if (VDBG) log(" sending notification for " + nr); 4584 if (nri.mPendingIntent == null) { 4585 callCallbackForRequest(nri, networkAgent, notifyType); 4586 } else { 4587 sendPendingIntentForRequest(nri, networkAgent, notifyType); 4588 } 4589 } 4590 } 4591 4592 private String notifyTypeToName(int notifyType) { 4593 switch (notifyType) { 4594 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK"; 4595 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE"; 4596 case ConnectivityManager.CALLBACK_LOSING: return "LOSING"; 4597 case ConnectivityManager.CALLBACK_LOST: return "LOST"; 4598 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE"; 4599 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED"; 4600 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED"; 4601 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED"; 4602 } 4603 return "UNKNOWN"; 4604 } 4605 4606 /** 4607 * Notify other system services that set of active ifaces has changed. 4608 */ 4609 private void notifyIfacesChanged() { 4610 try { 4611 mStatsService.forceUpdateIfaces(); 4612 } catch (Exception ignored) { 4613 } 4614 } 4615 4616 @Override 4617 public boolean addVpnAddress(String address, int prefixLength) { 4618 throwIfLockdownEnabled(); 4619 int user = UserHandle.getUserId(Binder.getCallingUid()); 4620 synchronized (mVpns) { 4621 return mVpns.get(user).addAddress(address, prefixLength); 4622 } 4623 } 4624 4625 @Override 4626 public boolean removeVpnAddress(String address, int prefixLength) { 4627 throwIfLockdownEnabled(); 4628 int user = UserHandle.getUserId(Binder.getCallingUid()); 4629 synchronized (mVpns) { 4630 return mVpns.get(user).removeAddress(address, prefixLength); 4631 } 4632 } 4633 4634 @Override 4635 public boolean setUnderlyingNetworksForVpn(Network[] networks) { 4636 throwIfLockdownEnabled(); 4637 int user = UserHandle.getUserId(Binder.getCallingUid()); 4638 boolean success; 4639 synchronized (mVpns) { 4640 success = mVpns.get(user).setUnderlyingNetworks(networks); 4641 } 4642 if (success) { 4643 notifyIfacesChanged(); 4644 } 4645 return success; 4646 } 4647 4648 @Override 4649 public void factoryReset() { 4650 enforceConnectivityInternalPermission(); 4651 4652 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) { 4653 return; 4654 } 4655 4656 final int userId = UserHandle.getCallingUserId(); 4657 4658 // Turn airplane mode off 4659 setAirplaneMode(false); 4660 4661 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) { 4662 // Untether 4663 for (String tether : getTetheredIfaces()) { 4664 untether(tether); 4665 } 4666 } 4667 4668 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) { 4669 // Turn VPN off 4670 VpnConfig vpnConfig = getVpnConfig(userId); 4671 if (vpnConfig != null) { 4672 if (vpnConfig.legacy) { 4673 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId); 4674 } else { 4675 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections 4676 // in the future without user intervention. 4677 setVpnPackageAuthorization(vpnConfig.user, userId, false); 4678 4679 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId); 4680 } 4681 } 4682 } 4683 } 4684} 4685