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