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