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