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