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