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