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