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