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