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