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