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