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