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