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