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