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