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