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