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