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