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