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