ConnectivityService.java revision 3e0e3bc617c4fd0e03b88ae04a618381b20a383c
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_MMS; 27import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL; 28import static android.net.ConnectivityManager.TYPE_MOBILE_DUN; 29import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA; 30import static android.net.ConnectivityManager.TYPE_MOBILE_IMS; 31import static android.net.ConnectivityManager.TYPE_MOBILE_CBS; 32import static android.net.ConnectivityManager.TYPE_MOBILE_IA; 33import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI; 34import static android.net.ConnectivityManager.TYPE_NONE; 35import static android.net.ConnectivityManager.TYPE_WIFI; 36import static android.net.ConnectivityManager.TYPE_WIMAX; 37import static android.net.ConnectivityManager.TYPE_PROXY; 38import static android.net.ConnectivityManager.getNetworkTypeName; 39import static android.net.ConnectivityManager.isNetworkTypeValid; 40import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL; 41import static android.net.NetworkPolicyManager.RULE_REJECT_METERED; 42 43import android.app.AlarmManager; 44import android.app.AppOpsManager; 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.ApplicationInfo; 56import android.content.pm.PackageManager; 57import android.content.pm.PackageManager.NameNotFoundException; 58import android.content.res.Configuration; 59import android.content.res.Resources; 60import android.database.ContentObserver; 61import android.net.CaptivePortalTracker; 62import android.net.ConnectivityManager; 63import android.net.DummyDataStateTracker; 64import android.net.IConnectivityManager; 65import android.net.INetworkManagementEventObserver; 66import android.net.INetworkPolicyListener; 67import android.net.INetworkPolicyManager; 68import android.net.INetworkStatsService; 69import android.net.LinkAddress; 70import android.net.LinkProperties; 71import android.net.LinkProperties.CompareResult; 72import android.net.LinkQualityInfo; 73import android.net.MobileDataStateTracker; 74import android.net.Network; 75import android.net.NetworkAgent; 76import android.net.NetworkCapabilities; 77import android.net.NetworkConfig; 78import android.net.NetworkInfo; 79import android.net.NetworkInfo.DetailedState; 80import android.net.NetworkFactory; 81import android.net.NetworkQuotaInfo; 82import android.net.NetworkRequest; 83import android.net.NetworkState; 84import android.net.NetworkStateTracker; 85import android.net.NetworkUtils; 86import android.net.Proxy; 87import android.net.ProxyDataTracker; 88import android.net.ProxyInfo; 89import android.net.RouteInfo; 90import android.net.SamplingDataTracker; 91import android.net.Uri; 92import android.net.wimax.WimaxManagerConstants; 93import android.os.AsyncTask; 94import android.os.Binder; 95import android.os.Build; 96import android.os.FileUtils; 97import android.os.Handler; 98import android.os.HandlerThread; 99import android.os.IBinder; 100import android.os.INetworkManagementService; 101import android.os.Looper; 102import android.os.Message; 103import android.os.Messenger; 104import android.os.ParcelFileDescriptor; 105import android.os.PowerManager; 106import android.os.Process; 107import android.os.RemoteException; 108import android.os.ServiceManager; 109import android.os.SystemClock; 110import android.os.SystemProperties; 111import android.os.UserHandle; 112import android.provider.Settings; 113import android.security.Credentials; 114import android.security.KeyStore; 115import android.telephony.TelephonyManager; 116import android.text.TextUtils; 117import android.util.Slog; 118import android.util.SparseArray; 119import android.util.SparseIntArray; 120import android.util.Xml; 121 122import com.android.internal.R; 123import com.android.internal.annotations.GuardedBy; 124import com.android.internal.net.LegacyVpnInfo; 125import com.android.internal.net.VpnConfig; 126import com.android.internal.net.VpnProfile; 127import com.android.internal.telephony.DctConstants; 128import com.android.internal.telephony.Phone; 129import com.android.internal.telephony.PhoneConstants; 130import com.android.internal.telephony.TelephonyIntents; 131import com.android.internal.util.AsyncChannel; 132import com.android.internal.util.IndentingPrintWriter; 133import com.android.internal.util.XmlUtils; 134import com.android.server.am.BatteryStatsService; 135import com.android.server.connectivity.DataConnectionStats; 136import com.android.server.connectivity.Nat464Xlat; 137import com.android.server.connectivity.NetworkAgentInfo; 138import com.android.server.connectivity.NetworkMonitor; 139import com.android.server.connectivity.PacManager; 140import com.android.server.connectivity.Tethering; 141import com.android.server.connectivity.Vpn; 142import com.android.server.net.BaseNetworkObserver; 143import com.android.server.net.LockdownVpnTracker; 144import com.google.android.collect.Lists; 145import com.google.android.collect.Sets; 146 147import dalvik.system.DexClassLoader; 148 149import org.xmlpull.v1.XmlPullParser; 150import org.xmlpull.v1.XmlPullParserException; 151 152import java.io.File; 153import java.io.FileDescriptor; 154import java.io.FileNotFoundException; 155import java.io.FileReader; 156import java.io.IOException; 157import java.io.PrintWriter; 158import java.lang.reflect.Constructor; 159import java.net.HttpURLConnection; 160import java.net.Inet4Address; 161import java.net.Inet6Address; 162import java.net.InetAddress; 163import java.net.URL; 164import java.net.UnknownHostException; 165import java.util.ArrayList; 166import java.util.Arrays; 167import java.util.Collection; 168import java.util.GregorianCalendar; 169import java.util.HashMap; 170import java.util.HashSet; 171import java.util.List; 172import java.util.Map; 173import java.util.Random; 174import java.util.concurrent.atomic.AtomicBoolean; 175import java.util.concurrent.atomic.AtomicInteger; 176 177import javax.net.ssl.HostnameVerifier; 178import javax.net.ssl.HttpsURLConnection; 179import javax.net.ssl.SSLSession; 180 181import static android.net.ConnectivityManager.INVALID_NET_ID; 182 183/** 184 * @hide 185 */ 186public class ConnectivityService extends IConnectivityManager.Stub { 187 private static final String TAG = "ConnectivityService"; 188 189 private static final boolean DBG = true; 190 private static final boolean VDBG = true; // STOPSHIP 191 192 // network sampling debugging 193 private static final boolean SAMPLE_DBG = false; 194 195 private static final boolean LOGD_RULES = false; 196 197 // TODO: create better separation between radio types and network types 198 199 // how long to wait before switching back to a radio's default network 200 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000; 201 // system property that can override the above value 202 private static final String NETWORK_RESTORE_DELAY_PROP_NAME = 203 "android.telephony.apn-restore"; 204 205 // Default value if FAIL_FAST_TIME_MS is not set 206 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000; 207 // system property that can override DEFAULT_FAIL_FAST_TIME_MS 208 private static final String FAIL_FAST_TIME_MS = 209 "persist.radio.fail_fast_time_ms"; 210 211 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED = 212 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED"; 213 214 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0; 215 216 private PendingIntent mSampleIntervalElapsedIntent; 217 218 // Set network sampling interval at 12 minutes, this way, even if the timers get 219 // aggregated, it will fire at around 15 minutes, which should allow us to 220 // aggregate this timer with other timers (specially the socket keep alive timers) 221 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 12 * 60); 222 223 // start network sampling a minute after booting ... 224 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 60); 225 226 AlarmManager mAlarmManager; 227 228 // used in recursive route setting to add gateways for the host for which 229 // a host route was requested. 230 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10; 231 232 private Tethering mTethering; 233 234 private KeyStore mKeyStore; 235 236 @GuardedBy("mVpns") 237 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>(); 238 private VpnCallback mVpnCallback = new VpnCallback(); 239 240 private boolean mLockdownEnabled; 241 private LockdownVpnTracker mLockdownTracker; 242 243 private Nat464Xlat mClat; 244 245 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */ 246 private Object mRulesLock = new Object(); 247 /** Currently active network rules by UID. */ 248 private SparseIntArray mUidRules = new SparseIntArray(); 249 /** Set of ifaces that are costly. */ 250 private HashSet<String> mMeteredIfaces = Sets.newHashSet(); 251 252 /** 253 * Sometimes we want to refer to the individual network state 254 * trackers separately, and sometimes we just want to treat them 255 * abstractly. 256 */ 257 private NetworkStateTracker mNetTrackers[]; 258 259 /* Handles captive portal check on a network */ 260 private CaptivePortalTracker mCaptivePortalTracker; 261 262 /** 263 * The link properties that define the current links 264 */ 265 private LinkProperties mCurrentLinkProperties[]; 266 267 /** 268 * A per Net list of the PID's that requested access to the net 269 * used both as a refcount and for per-PID DNS selection 270 */ 271 private List<Integer> mNetRequestersPids[]; 272 273 // priority order of the nettrackers 274 // (excluding dynamically set mNetworkPreference) 275 // TODO - move mNetworkTypePreference into this 276 private int[] mPriorityList; 277 278 private Context mContext; 279 private int mNetworkPreference; 280 private int mActiveDefaultNetwork = -1; 281 // 0 is full bad, 100 is full good 282 private int mDefaultInetCondition = 0; 283 private int mDefaultInetConditionPublished = 0; 284 private boolean mInetConditionChangeInFlight = false; 285 private int mDefaultConnectionSequence = 0; 286 287 private Object mDnsLock = new Object(); 288 private int mNumDnsEntries; 289 290 private boolean mTestMode; 291 private static ConnectivityService sServiceInstance; 292 293 private INetworkManagementService mNetd; 294 private INetworkPolicyManager mPolicyManager; 295 296 private static final int ENABLED = 1; 297 private static final int DISABLED = 0; 298 299 private static final boolean ADD = true; 300 private static final boolean REMOVE = false; 301 302 private static final boolean TO_DEFAULT_TABLE = true; 303 private static final boolean TO_SECONDARY_TABLE = false; 304 305 private static final boolean EXEMPT = true; 306 private static final boolean UNEXEMPT = false; 307 308 /** 309 * used internally as a delayed event to make us switch back to the 310 * default network 311 */ 312 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1; 313 314 /** 315 * used internally to change our mobile data enabled flag 316 */ 317 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2; 318 319 /** 320 * used internally to synchronize inet condition reports 321 * arg1 = networkType 322 * arg2 = condition (0 bad, 100 good) 323 */ 324 private static final int EVENT_INET_CONDITION_CHANGE = 4; 325 326 /** 327 * used internally to mark the end of inet condition hold periods 328 * arg1 = networkType 329 */ 330 private static final int EVENT_INET_CONDITION_HOLD_END = 5; 331 332 /** 333 * used internally to clear a wakelock when transitioning 334 * from one net to another 335 */ 336 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8; 337 338 /** 339 * used internally to reload global proxy settings 340 */ 341 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9; 342 343 /** 344 * used internally to set external dependency met/unmet 345 * arg1 = ENABLED (met) or DISABLED (unmet) 346 * arg2 = NetworkType 347 */ 348 private static final int EVENT_SET_DEPENDENCY_MET = 10; 349 350 /** 351 * used internally to send a sticky broadcast delayed. 352 */ 353 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11; 354 355 /** 356 * Used internally to 357 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}. 358 */ 359 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12; 360 361 private static final int EVENT_VPN_STATE_CHANGED = 13; 362 363 /** 364 * Used internally to disable fail fast of mobile data 365 */ 366 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14; 367 368 /** 369 * used internally to indicate that data sampling interval is up 370 */ 371 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15; 372 373 /** 374 * PAC manager has received new port. 375 */ 376 private static final int EVENT_PROXY_HAS_CHANGED = 16; 377 378 /** 379 * used internally when registering NetworkFactories 380 * obj = NetworkFactoryInfo 381 */ 382 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17; 383 384 /** 385 * used internally when registering NetworkAgents 386 * obj = Messenger 387 */ 388 private static final int EVENT_REGISTER_NETWORK_AGENT = 18; 389 390 /** 391 * used to add a network request 392 * includes a NetworkRequestInfo 393 */ 394 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19; 395 396 /** 397 * indicates a timeout period is over - check if we had a network yet or not 398 * and if not, call the timeout calback (but leave the request live until they 399 * cancel it. 400 * includes a NetworkRequestInfo 401 */ 402 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20; 403 404 /** 405 * used to add a network listener - no request 406 * includes a NetworkRequestInfo 407 */ 408 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21; 409 410 /** 411 * used to remove a network request, either a listener or a real request 412 * arg1 = UID of caller 413 * obj = NetworkRequest 414 */ 415 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22; 416 417 /** 418 * used internally when registering NetworkFactories 419 * obj = Messenger 420 */ 421 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23; 422 423 424 /** Handler used for internal events. */ 425 final private InternalHandler mHandler; 426 /** Handler used for incoming {@link NetworkStateTracker} events. */ 427 final private NetworkStateTrackerHandler mTrackerHandler; 428 429 // list of DeathRecipients used to make sure features are turned off when 430 // a process dies 431 private List<FeatureUser> mFeatureUsers; 432 433 private boolean mSystemReady; 434 private Intent mInitialBroadcast; 435 436 private PowerManager.WakeLock mNetTransitionWakeLock; 437 private String mNetTransitionWakeLockCausedBy = ""; 438 private int mNetTransitionWakeLockSerialNumber; 439 private int mNetTransitionWakeLockTimeout; 440 441 private InetAddress mDefaultDns; 442 443 // Lock for protecting access to mAddedRoutes and mExemptAddresses 444 private final Object mRoutesLock = new Object(); 445 446 // this collection is used to refcount the added routes - if there are none left 447 // it's time to remove the route from the route table 448 @GuardedBy("mRoutesLock") 449 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>(); 450 451 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions 452 // used to handle cleanup of exempt rules 453 @GuardedBy("mRoutesLock") 454 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>(); 455 456 // used in DBG mode to track inet condition reports 457 private static final int INET_CONDITION_LOG_MAX_SIZE = 15; 458 private ArrayList mInetLog; 459 460 // track the current default http proxy - tell the world if we get a new one (real change) 461 private ProxyInfo mDefaultProxy = null; 462 private Object mProxyLock = new Object(); 463 private boolean mDefaultProxyDisabled = false; 464 465 // track the global proxy. 466 private ProxyInfo mGlobalProxy = null; 467 468 private PacManager mPacManager = null; 469 470 private SettingsObserver mSettingsObserver; 471 472 private AppOpsManager mAppOpsManager; 473 474 NetworkConfig[] mNetConfigs; 475 int mNetworksDefined; 476 477 private static class RadioAttributes { 478 public int mSimultaneity; 479 public int mType; 480 public RadioAttributes(String init) { 481 String fragments[] = init.split(","); 482 mType = Integer.parseInt(fragments[0]); 483 mSimultaneity = Integer.parseInt(fragments[1]); 484 } 485 } 486 RadioAttributes[] mRadioAttributes; 487 488 // the set of network types that can only be enabled by system/sig apps 489 List mProtectedNetworks; 490 491 private DataConnectionStats mDataConnectionStats; 492 493 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0); 494 495 TelephonyManager mTelephonyManager; 496 497 // sequence number for Networks 498 private final static int MIN_NET_ID = 10; // some reserved marks 499 private final static int MAX_NET_ID = 65535; 500 private int mNextNetId = MIN_NET_ID; 501 502 // sequence number of NetworkRequests 503 private int mNextNetworkRequestId = 1; 504 505 private static final int UID_UNUSED = -1; 506 507 /** 508 * Implements support for the legacy "one network per network type" model. 509 * 510 * We used to have a static array of NetworkStateTrackers, one for each 511 * network type, but that doesn't work any more now that we can have, 512 * for example, more that one wifi network. This class stores all the 513 * NetworkAgentInfo objects that support a given type, but the legacy 514 * API will only see the first one. 515 * 516 * It serves two main purposes: 517 * 518 * 1. Provide information about "the network for a given type" (since this 519 * API only supports one). 520 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if 521 * the first network for a given type changes, or if the default network 522 * changes. 523 */ 524 private class LegacyTypeTracker { 525 /** 526 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS). 527 * Each list holds references to all NetworkAgentInfos that are used to 528 * satisfy requests for that network type. 529 * 530 * This array is built out at startup such that an unsupported network 531 * doesn't get an ArrayList instance, making this a tristate: 532 * unsupported, supported but not active and active. 533 * 534 * The actual lists are populated when we scan the network types that 535 * are supported on this device. 536 */ 537 private ArrayList<NetworkAgentInfo> mTypeLists[]; 538 539 public LegacyTypeTracker() { 540 mTypeLists = (ArrayList<NetworkAgentInfo>[]) 541 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1]; 542 } 543 544 public void addSupportedType(int type) { 545 if (mTypeLists[type] != null) { 546 throw new IllegalStateException( 547 "legacy list for type " + type + "already initialized"); 548 } 549 mTypeLists[type] = new ArrayList<NetworkAgentInfo>(); 550 } 551 552 private boolean isDefaultNetwork(NetworkAgentInfo nai) { 553 return mNetworkForRequestId.get(mDefaultRequest.requestId) == nai; 554 } 555 556 public boolean isTypeSupported(int type) { 557 return isNetworkTypeValid(type) && mTypeLists[type] != null; 558 } 559 560 public NetworkAgentInfo getNetworkForType(int type) { 561 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) { 562 return mTypeLists[type].get(0); 563 } else { 564 return null; 565 } 566 } 567 568 public void add(int type, NetworkAgentInfo nai) { 569 if (!isTypeSupported(type)) { 570 return; // Invalid network type. 571 } 572 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type); 573 574 ArrayList<NetworkAgentInfo> list = mTypeLists[type]; 575 if (list.contains(nai)) { 576 loge("Attempting to register duplicate agent for type " + type + ": " + nai); 577 return; 578 } 579 580 if (list.isEmpty() || isDefaultNetwork(nai)) { 581 if (VDBG) log("Sending connected broadcast for type " + type + 582 "isDefaultNetwork=" + isDefaultNetwork(nai)); 583 sendLegacyNetworkBroadcast(nai, true, type); 584 } 585 list.add(nai); 586 } 587 588 public void remove(NetworkAgentInfo nai) { 589 if (VDBG) log("Removing agent " + nai); 590 for (int type = 0; type < mTypeLists.length; type++) { 591 ArrayList<NetworkAgentInfo> list = mTypeLists[type]; 592 if (list == null || list.isEmpty()) { 593 continue; 594 } 595 596 boolean wasFirstNetwork = false; 597 if (list.get(0).equals(nai)) { 598 // This network was the first in the list. Send broadcast. 599 wasFirstNetwork = true; 600 } 601 list.remove(nai); 602 603 if (wasFirstNetwork || isDefaultNetwork(nai)) { 604 if (VDBG) log("Sending disconnected broadcast for type " + type + 605 "isDefaultNetwork=" + isDefaultNetwork(nai)); 606 sendLegacyNetworkBroadcast(nai, false, type); 607 } 608 609 if (!list.isEmpty() && wasFirstNetwork) { 610 if (VDBG) log("Other network available for type " + type + 611 ", sending connected broadcast"); 612 sendLegacyNetworkBroadcast(list.get(0), false, type); 613 } 614 } 615 } 616 } 617 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(); 618 619 public ConnectivityService(Context context, INetworkManagementService netd, 620 INetworkStatsService statsService, INetworkPolicyManager policyManager) { 621 // Currently, omitting a NetworkFactory will create one internally 622 // TODO: create here when we have cleaner WiMAX support 623 this(context, netd, statsService, policyManager, null); 624 } 625 626 public ConnectivityService(Context context, INetworkManagementService netManager, 627 INetworkStatsService statsService, INetworkPolicyManager policyManager, 628 NetworkFactory netFactory) { 629 if (DBG) log("ConnectivityService starting up"); 630 631 NetworkCapabilities netCap = new NetworkCapabilities(); 632 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); 633 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED); 634 mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId()); 635 NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(), 636 NetworkRequestInfo.REQUEST); 637 mNetworkRequests.put(mDefaultRequest, nri); 638 639 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread"); 640 handlerThread.start(); 641 mHandler = new InternalHandler(handlerThread.getLooper()); 642 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper()); 643 644 if (netFactory == null) { 645 netFactory = new DefaultNetworkFactory(context, mTrackerHandler); 646 } 647 648 // setup our unique device name 649 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) { 650 String id = Settings.Secure.getString(context.getContentResolver(), 651 Settings.Secure.ANDROID_ID); 652 if (id != null && id.length() > 0) { 653 String name = new String("android-").concat(id); 654 SystemProperties.set("net.hostname", name); 655 } 656 } 657 658 // read our default dns server ip 659 String dns = Settings.Global.getString(context.getContentResolver(), 660 Settings.Global.DEFAULT_DNS_SERVER); 661 if (dns == null || dns.length() == 0) { 662 dns = context.getResources().getString( 663 com.android.internal.R.string.config_default_dns_server); 664 } 665 try { 666 mDefaultDns = NetworkUtils.numericToInetAddress(dns); 667 } catch (IllegalArgumentException e) { 668 loge("Error setting defaultDns using " + dns); 669 } 670 671 mContext = checkNotNull(context, "missing Context"); 672 mNetd = checkNotNull(netManager, "missing INetworkManagementService"); 673 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager"); 674 mKeyStore = KeyStore.getInstance(); 675 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 676 677 try { 678 mPolicyManager.registerListener(mPolicyListener); 679 } catch (RemoteException e) { 680 // ouch, no rules updates means some processes may never get network 681 loge("unable to register INetworkPolicyListener" + e.toString()); 682 } 683 684 final PowerManager powerManager = (PowerManager) context.getSystemService( 685 Context.POWER_SERVICE); 686 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); 687 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger( 688 com.android.internal.R.integer.config_networkTransitionTimeout); 689 690 mNetTrackers = new NetworkStateTracker[ 691 ConnectivityManager.MAX_NETWORK_TYPE+1]; 692 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1]; 693 694 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1]; 695 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1]; 696 697 // Load device network attributes from resources 698 String[] raStrings = context.getResources().getStringArray( 699 com.android.internal.R.array.radioAttributes); 700 for (String raString : raStrings) { 701 RadioAttributes r = new RadioAttributes(raString); 702 if (VDBG) log("raString=" + raString + " r=" + r); 703 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) { 704 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType); 705 continue; 706 } 707 if (mRadioAttributes[r.mType] != null) { 708 loge("Error in radioAttributes - ignoring attempt to redefine type " + 709 r.mType); 710 continue; 711 } 712 mRadioAttributes[r.mType] = r; 713 } 714 715 // TODO: What is the "correct" way to do determine if this is a wifi only device? 716 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false); 717 log("wifiOnly=" + wifiOnly); 718 String[] naStrings = context.getResources().getStringArray( 719 com.android.internal.R.array.networkAttributes); 720 for (String naString : naStrings) { 721 try { 722 NetworkConfig n = new NetworkConfig(naString); 723 if (VDBG) log("naString=" + naString + " config=" + n); 724 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) { 725 loge("Error in networkAttributes - ignoring attempt to define type " + 726 n.type); 727 continue; 728 } 729 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) { 730 log("networkAttributes - ignoring mobile as this dev is wifiOnly " + 731 n.type); 732 continue; 733 } 734 if (mNetConfigs[n.type] != null) { 735 loge("Error in networkAttributes - ignoring attempt to redefine type " + 736 n.type); 737 continue; 738 } 739 if (mRadioAttributes[n.radio] == null) { 740 loge("Error in networkAttributes - ignoring attempt to use undefined " + 741 "radio " + n.radio + " in network type " + n.type); 742 continue; 743 } 744 mLegacyTypeTracker.addSupportedType(n.type); 745 746 mNetConfigs[n.type] = n; 747 mNetworksDefined++; 748 } catch(Exception e) { 749 // ignore it - leave the entry null 750 } 751 } 752 if (VDBG) log("mNetworksDefined=" + mNetworksDefined); 753 754 mProtectedNetworks = new ArrayList<Integer>(); 755 int[] protectedNetworks = context.getResources().getIntArray( 756 com.android.internal.R.array.config_protectedNetworks); 757 for (int p : protectedNetworks) { 758 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) { 759 mProtectedNetworks.add(p); 760 } else { 761 if (DBG) loge("Ignoring protectedNetwork " + p); 762 } 763 } 764 765 // high priority first 766 mPriorityList = new int[mNetworksDefined]; 767 { 768 int insertionPoint = mNetworksDefined-1; 769 int currentLowest = 0; 770 int nextLowest = 0; 771 while (insertionPoint > -1) { 772 for (NetworkConfig na : mNetConfigs) { 773 if (na == null) continue; 774 if (na.priority < currentLowest) continue; 775 if (na.priority > currentLowest) { 776 if (na.priority < nextLowest || nextLowest == 0) { 777 nextLowest = na.priority; 778 } 779 continue; 780 } 781 mPriorityList[insertionPoint--] = na.type; 782 } 783 currentLowest = nextLowest; 784 nextLowest = 0; 785 } 786 } 787 788 mNetRequestersPids = 789 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1]; 790 for (int i : mPriorityList) { 791 mNetRequestersPids[i] = new ArrayList<Integer>(); 792 } 793 794 mFeatureUsers = new ArrayList<FeatureUser>(); 795 796 mTestMode = SystemProperties.get("cm.test.mode").equals("true") 797 && SystemProperties.get("ro.build.type").equals("eng"); 798 799 // Create and start trackers for hard-coded networks 800 for (int targetNetworkType : mPriorityList) { 801 final NetworkConfig config = mNetConfigs[targetNetworkType]; 802 final NetworkStateTracker tracker; 803 try { 804 tracker = netFactory.createTracker(targetNetworkType, config); 805 mNetTrackers[targetNetworkType] = tracker; 806 } catch (IllegalArgumentException e) { 807 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType) 808 + " tracker: " + e); 809 continue; 810 } 811 812 tracker.startMonitoring(context, mTrackerHandler); 813 if (config.isDefault()) { 814 tracker.reconnect(); 815 } 816 } 817 818 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper()); 819 820 //set up the listener for user state for creating user VPNs 821 IntentFilter intentFilter = new IntentFilter(); 822 intentFilter.addAction(Intent.ACTION_USER_STARTING); 823 intentFilter.addAction(Intent.ACTION_USER_STOPPING); 824 mContext.registerReceiverAsUser( 825 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null); 826 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler); 827 828 try { 829 mNetd.registerObserver(mTethering); 830 mNetd.registerObserver(mDataActivityObserver); 831 mNetd.registerObserver(mClat); 832 } catch (RemoteException e) { 833 loge("Error registering observer :" + e); 834 } 835 836 if (DBG) { 837 mInetLog = new ArrayList(); 838 } 839 840 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY); 841 mSettingsObserver.observe(mContext); 842 843 mDataConnectionStats = new DataConnectionStats(mContext); 844 mDataConnectionStats.startMonitoring(); 845 846 // start network sampling .. 847 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null); 848 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext, 849 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0); 850 851 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE); 852 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent); 853 854 IntentFilter filter = new IntentFilter(); 855 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED); 856 mContext.registerReceiver( 857 new BroadcastReceiver() { 858 @Override 859 public void onReceive(Context context, Intent intent) { 860 String action = intent.getAction(); 861 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) { 862 mHandler.sendMessage(mHandler.obtainMessage 863 (EVENT_SAMPLE_INTERVAL_ELAPSED)); 864 } 865 } 866 }, 867 new IntentFilter(filter)); 868 869 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED); 870 871 filter = new IntentFilter(); 872 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION); 873 mContext.registerReceiver(mProvisioningReceiver, filter); 874 875 mAppOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); 876 } 877 878 private synchronized int nextNetworkRequestId() { 879 return mNextNetworkRequestId++; 880 } 881 882 private synchronized int nextNetId() { 883 int netId = mNextNetId; 884 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID; 885 return netId; 886 } 887 888 /** 889 * Factory that creates {@link NetworkStateTracker} instances using given 890 * {@link NetworkConfig}. 891 * 892 * TODO - this is obsolete and will be deleted. It's replaced by the 893 * registerNetworkFactory call and protocol. 894 * @Deprecated in favor of registerNetworkFactory dynamic bindings 895 */ 896 public interface NetworkFactory { 897 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config); 898 } 899 900 private static class DefaultNetworkFactory implements NetworkFactory { 901 private final Context mContext; 902 private final Handler mTrackerHandler; 903 904 public DefaultNetworkFactory(Context context, Handler trackerHandler) { 905 mContext = context; 906 mTrackerHandler = trackerHandler; 907 } 908 909 @Override 910 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) { 911 switch (config.radio) { 912 case TYPE_DUMMY: 913 return new DummyDataStateTracker(targetNetworkType, config.name); 914 case TYPE_WIMAX: 915 return makeWimaxStateTracker(mContext, mTrackerHandler); 916 case TYPE_PROXY: 917 return new ProxyDataTracker(); 918 default: 919 throw new IllegalArgumentException( 920 "Trying to create a NetworkStateTracker for an unknown radio type: " 921 + config.radio); 922 } 923 } 924 } 925 926 /** 927 * Loads external WiMAX library and registers as system service, returning a 928 * {@link NetworkStateTracker} for WiMAX. Caller is still responsible for 929 * invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}. 930 */ 931 private static NetworkStateTracker makeWimaxStateTracker( 932 Context context, Handler trackerHandler) { 933 // Initialize Wimax 934 DexClassLoader wimaxClassLoader; 935 Class wimaxStateTrackerClass = null; 936 Class wimaxServiceClass = null; 937 Class wimaxManagerClass; 938 String wimaxJarLocation; 939 String wimaxLibLocation; 940 String wimaxManagerClassName; 941 String wimaxServiceClassName; 942 String wimaxStateTrackerClassName; 943 944 NetworkStateTracker wimaxStateTracker = null; 945 946 boolean isWimaxEnabled = context.getResources().getBoolean( 947 com.android.internal.R.bool.config_wimaxEnabled); 948 949 if (isWimaxEnabled) { 950 try { 951 wimaxJarLocation = context.getResources().getString( 952 com.android.internal.R.string.config_wimaxServiceJarLocation); 953 wimaxLibLocation = context.getResources().getString( 954 com.android.internal.R.string.config_wimaxNativeLibLocation); 955 wimaxManagerClassName = context.getResources().getString( 956 com.android.internal.R.string.config_wimaxManagerClassname); 957 wimaxServiceClassName = context.getResources().getString( 958 com.android.internal.R.string.config_wimaxServiceClassname); 959 wimaxStateTrackerClassName = context.getResources().getString( 960 com.android.internal.R.string.config_wimaxStateTrackerClassname); 961 962 if (DBG) log("wimaxJarLocation: " + wimaxJarLocation); 963 wimaxClassLoader = new DexClassLoader(wimaxJarLocation, 964 new ContextWrapper(context).getCacheDir().getAbsolutePath(), 965 wimaxLibLocation, ClassLoader.getSystemClassLoader()); 966 967 try { 968 wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName); 969 wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName); 970 wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName); 971 } catch (ClassNotFoundException ex) { 972 loge("Exception finding Wimax classes: " + ex.toString()); 973 return null; 974 } 975 } catch(Resources.NotFoundException ex) { 976 loge("Wimax Resources does not exist!!! "); 977 return null; 978 } 979 980 try { 981 if (DBG) log("Starting Wimax Service... "); 982 983 Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor 984 (new Class[] {Context.class, Handler.class}); 985 wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance( 986 context, trackerHandler); 987 988 Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor 989 (new Class[] {Context.class, wimaxStateTrackerClass}); 990 wmxSrvConst.setAccessible(true); 991 IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker); 992 wmxSrvConst.setAccessible(false); 993 994 ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker); 995 996 } catch(Exception ex) { 997 loge("Exception creating Wimax classes: " + ex.toString()); 998 return null; 999 } 1000 } else { 1001 loge("Wimax is not enabled or not added to the network attributes!!! "); 1002 return null; 1003 } 1004 1005 return wimaxStateTracker; 1006 } 1007 1008 private int getConnectivityChangeDelay() { 1009 final ContentResolver cr = mContext.getContentResolver(); 1010 1011 /** Check system properties for the default value then use secure settings value, if any. */ 1012 int defaultDelay = SystemProperties.getInt( 1013 "conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY, 1014 ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT); 1015 return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY, 1016 defaultDelay); 1017 } 1018 1019 private boolean teardown(NetworkStateTracker netTracker) { 1020 if (netTracker.teardown()) { 1021 netTracker.setTeardownRequested(true); 1022 return true; 1023 } else { 1024 return false; 1025 } 1026 } 1027 1028 /** 1029 * Check if UID should be blocked from using the network represented by the 1030 * given {@link NetworkStateTracker}. 1031 */ 1032 private boolean isNetworkBlocked(int networkType, int uid) { 1033 final boolean networkCostly; 1034 final int uidRules; 1035 1036 LinkProperties lp = getLinkPropertiesForType(networkType); 1037 final String iface = (lp == null ? "" : lp.getInterfaceName()); 1038 synchronized (mRulesLock) { 1039 networkCostly = mMeteredIfaces.contains(iface); 1040 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL); 1041 } 1042 1043 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) { 1044 return true; 1045 } 1046 1047 // no restrictive rules; network is visible 1048 return false; 1049 } 1050 1051 /** 1052 * Return a filtered {@link NetworkInfo}, potentially marked 1053 * {@link DetailedState#BLOCKED} based on 1054 * {@link #isNetworkBlocked}. 1055 */ 1056 private NetworkInfo getFilteredNetworkInfo(int networkType, int uid) { 1057 NetworkInfo info = getNetworkInfoForType(networkType); 1058 if (isNetworkBlocked(networkType, uid)) { 1059 // network is blocked; clone and override state 1060 info = new NetworkInfo(info); 1061 info.setDetailedState(DetailedState.BLOCKED, null, null); 1062 } 1063 if (mLockdownTracker != null) { 1064 info = mLockdownTracker.augmentNetworkInfo(info); 1065 } 1066 return info; 1067 } 1068 1069 /** 1070 * Return NetworkInfo for the active (i.e., connected) network interface. 1071 * It is assumed that at most one network is active at a time. If more 1072 * than one is active, it is indeterminate which will be returned. 1073 * @return the info for the active network, or {@code null} if none is 1074 * active 1075 */ 1076 @Override 1077 public NetworkInfo getActiveNetworkInfo() { 1078 enforceAccessPermission(); 1079 final int uid = Binder.getCallingUid(); 1080 return getNetworkInfo(mActiveDefaultNetwork, uid); 1081 } 1082 1083 // only called when the default request is satisfied 1084 private void updateActiveDefaultNetwork(NetworkAgentInfo nai) { 1085 if (nai != null) { 1086 mActiveDefaultNetwork = nai.networkInfo.getType(); 1087 } else { 1088 mActiveDefaultNetwork = TYPE_NONE; 1089 } 1090 } 1091 1092 /** 1093 * Find the first Provisioning network. 1094 * 1095 * @return NetworkInfo or null if none. 1096 */ 1097 private NetworkInfo getProvisioningNetworkInfo() { 1098 enforceAccessPermission(); 1099 1100 // Find the first Provisioning Network 1101 NetworkInfo provNi = null; 1102 for (NetworkInfo ni : getAllNetworkInfo()) { 1103 if (ni.isConnectedToProvisioningNetwork()) { 1104 provNi = ni; 1105 break; 1106 } 1107 } 1108 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi); 1109 return provNi; 1110 } 1111 1112 /** 1113 * Find the first Provisioning network or the ActiveDefaultNetwork 1114 * if there is no Provisioning network 1115 * 1116 * @return NetworkInfo or null if none. 1117 */ 1118 @Override 1119 public NetworkInfo getProvisioningOrActiveNetworkInfo() { 1120 enforceAccessPermission(); 1121 1122 NetworkInfo provNi = getProvisioningNetworkInfo(); 1123 if (provNi == null) { 1124 final int uid = Binder.getCallingUid(); 1125 provNi = getNetworkInfo(mActiveDefaultNetwork, uid); 1126 } 1127 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi); 1128 return provNi; 1129 } 1130 1131 public NetworkInfo getActiveNetworkInfoUnfiltered() { 1132 enforceAccessPermission(); 1133 if (isNetworkTypeValid(mActiveDefaultNetwork)) { 1134 return getNetworkInfoForType(mActiveDefaultNetwork); 1135 } 1136 return null; 1137 } 1138 1139 @Override 1140 public NetworkInfo getActiveNetworkInfoForUid(int uid) { 1141 enforceConnectivityInternalPermission(); 1142 return getNetworkInfo(mActiveDefaultNetwork, uid); 1143 } 1144 1145 @Override 1146 public NetworkInfo getNetworkInfo(int networkType) { 1147 enforceAccessPermission(); 1148 final int uid = Binder.getCallingUid(); 1149 return getNetworkInfo(networkType, uid); 1150 } 1151 1152 private NetworkInfo getNetworkInfo(int networkType, int uid) { 1153 NetworkInfo info = null; 1154 if (isNetworkTypeValid(networkType)) { 1155 if (getNetworkInfoForType(networkType) != null) { 1156 info = getFilteredNetworkInfo(networkType, uid); 1157 } 1158 } 1159 return info; 1160 } 1161 1162 @Override 1163 public NetworkInfo[] getAllNetworkInfo() { 1164 enforceAccessPermission(); 1165 final int uid = Binder.getCallingUid(); 1166 final ArrayList<NetworkInfo> result = Lists.newArrayList(); 1167 synchronized (mRulesLock) { 1168 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE; 1169 networkType++) { 1170 if (getNetworkInfoForType(networkType) != null) { 1171 result.add(getFilteredNetworkInfo(networkType, uid)); 1172 } 1173 } 1174 } 1175 return result.toArray(new NetworkInfo[result.size()]); 1176 } 1177 1178 @Override 1179 public boolean isNetworkSupported(int networkType) { 1180 enforceAccessPermission(); 1181 return (isNetworkTypeValid(networkType) && (getNetworkInfoForType(networkType) != null)); 1182 } 1183 1184 /** 1185 * Return LinkProperties for the active (i.e., connected) default 1186 * network interface. It is assumed that at most one default network 1187 * is active at a time. If more than one is active, it is indeterminate 1188 * which will be returned. 1189 * @return the ip properties for the active network, or {@code null} if 1190 * none is active 1191 */ 1192 @Override 1193 public LinkProperties getActiveLinkProperties() { 1194 return getLinkPropertiesForType(mActiveDefaultNetwork); 1195 } 1196 1197 @Override 1198 public LinkProperties getLinkPropertiesForType(int networkType) { 1199 enforceAccessPermission(); 1200 if (isNetworkTypeValid(networkType)) { 1201 return getLinkPropertiesForTypeInternal(networkType); 1202 } 1203 return null; 1204 } 1205 1206 // TODO - this should be ALL networks 1207 @Override 1208 public LinkProperties getLinkProperties(Network network) { 1209 enforceAccessPermission(); 1210 NetworkAgentInfo nai = mNetworkForNetId.get(network.netId); 1211 if (nai != null) return new LinkProperties(nai.linkProperties); 1212 return null; 1213 } 1214 1215 @Override 1216 public NetworkCapabilities getNetworkCapabilities(Network network) { 1217 enforceAccessPermission(); 1218 NetworkAgentInfo nai = mNetworkForNetId.get(network.netId); 1219 if (nai != null) return new NetworkCapabilities(nai.networkCapabilities); 1220 return null; 1221 } 1222 1223 @Override 1224 public NetworkState[] getAllNetworkState() { 1225 enforceAccessPermission(); 1226 final int uid = Binder.getCallingUid(); 1227 final ArrayList<NetworkState> result = Lists.newArrayList(); 1228 synchronized (mRulesLock) { 1229 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE; 1230 networkType++) { 1231 if (getNetworkInfoForType(networkType) != null) { 1232 final NetworkInfo info = getFilteredNetworkInfo(networkType, uid); 1233 final LinkProperties lp = getLinkPropertiesForTypeInternal(networkType); 1234 final NetworkCapabilities netcap = getNetworkCapabilitiesForType(networkType); 1235 result.add(new NetworkState(info, lp, netcap)); 1236 } 1237 } 1238 } 1239 return result.toArray(new NetworkState[result.size()]); 1240 } 1241 1242 private NetworkState getNetworkStateUnchecked(int networkType) { 1243 if (isNetworkTypeValid(networkType)) { 1244 NetworkInfo info = getNetworkInfoForType(networkType); 1245 if (info != null) { 1246 return new NetworkState(info, 1247 getLinkPropertiesForTypeInternal(networkType), 1248 getNetworkCapabilitiesForType(networkType)); 1249 } 1250 } 1251 return null; 1252 } 1253 1254 @Override 1255 public NetworkQuotaInfo getActiveNetworkQuotaInfo() { 1256 enforceAccessPermission(); 1257 1258 final long token = Binder.clearCallingIdentity(); 1259 try { 1260 final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork); 1261 if (state != null) { 1262 try { 1263 return mPolicyManager.getNetworkQuotaInfo(state); 1264 } catch (RemoteException e) { 1265 } 1266 } 1267 return null; 1268 } finally { 1269 Binder.restoreCallingIdentity(token); 1270 } 1271 } 1272 1273 @Override 1274 public boolean isActiveNetworkMetered() { 1275 enforceAccessPermission(); 1276 final long token = Binder.clearCallingIdentity(); 1277 try { 1278 return isNetworkMeteredUnchecked(mActiveDefaultNetwork); 1279 } finally { 1280 Binder.restoreCallingIdentity(token); 1281 } 1282 } 1283 1284 private boolean isNetworkMeteredUnchecked(int networkType) { 1285 final NetworkState state = getNetworkStateUnchecked(networkType); 1286 if (state != null) { 1287 try { 1288 return mPolicyManager.isNetworkMetered(state); 1289 } catch (RemoteException e) { 1290 } 1291 } 1292 return false; 1293 } 1294 1295 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() { 1296 @Override 1297 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) { 1298 int deviceType = Integer.parseInt(label); 1299 sendDataActivityBroadcast(deviceType, active, tsNanos); 1300 } 1301 }; 1302 1303 /** 1304 * Used to notice when the calling process dies so we can self-expire 1305 * 1306 * Also used to know if the process has cleaned up after itself when 1307 * our auto-expire timer goes off. The timer has a link to an object. 1308 * 1309 */ 1310 private class FeatureUser implements IBinder.DeathRecipient { 1311 int mNetworkType; 1312 String mFeature; 1313 IBinder mBinder; 1314 int mPid; 1315 int mUid; 1316 long mCreateTime; 1317 1318 FeatureUser(int type, String feature, IBinder binder) { 1319 super(); 1320 mNetworkType = type; 1321 mFeature = feature; 1322 mBinder = binder; 1323 mPid = getCallingPid(); 1324 mUid = getCallingUid(); 1325 mCreateTime = System.currentTimeMillis(); 1326 1327 try { 1328 mBinder.linkToDeath(this, 0); 1329 } catch (RemoteException e) { 1330 binderDied(); 1331 } 1332 } 1333 1334 void unlinkDeathRecipient() { 1335 mBinder.unlinkToDeath(this, 0); 1336 } 1337 1338 public void binderDied() { 1339 log("ConnectivityService FeatureUser binderDied(" + 1340 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " + 1341 (System.currentTimeMillis() - mCreateTime) + " mSec ago"); 1342 stopUsingNetworkFeature(this, false); 1343 } 1344 1345 public void expire() { 1346 if (VDBG) { 1347 log("ConnectivityService FeatureUser expire(" + 1348 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " + 1349 (System.currentTimeMillis() - mCreateTime) + " mSec ago"); 1350 } 1351 stopUsingNetworkFeature(this, false); 1352 } 1353 1354 public boolean isSameUser(FeatureUser u) { 1355 if (u == null) return false; 1356 1357 return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature); 1358 } 1359 1360 public boolean isSameUser(int pid, int uid, int networkType, String feature) { 1361 if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) && 1362 TextUtils.equals(mFeature, feature)) { 1363 return true; 1364 } 1365 return false; 1366 } 1367 1368 public String toString() { 1369 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " + 1370 (System.currentTimeMillis() - mCreateTime) + " mSec ago"; 1371 } 1372 } 1373 1374 // javadoc from interface 1375 public int startUsingNetworkFeature(int networkType, String feature, 1376 IBinder binder) { 1377 long startTime = 0; 1378 if (DBG) { 1379 startTime = SystemClock.elapsedRealtime(); 1380 } 1381 if (VDBG) { 1382 log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid=" 1383 + Binder.getCallingUid()); 1384 } 1385 enforceChangePermission(); 1386 try { 1387 if (!ConnectivityManager.isNetworkTypeValid(networkType) || 1388 mNetConfigs[networkType] == null) { 1389 return PhoneConstants.APN_REQUEST_FAILED; 1390 } 1391 1392 FeatureUser f = new FeatureUser(networkType, feature, binder); 1393 1394 // TODO - move this into individual networktrackers 1395 int usedNetworkType = convertFeatureToNetworkType(networkType, feature); 1396 1397 if (mLockdownEnabled) { 1398 // Since carrier APNs usually aren't available from VPN 1399 // endpoint, mark them as unavailable. 1400 return PhoneConstants.APN_TYPE_NOT_AVAILABLE; 1401 } 1402 1403 if (mProtectedNetworks.contains(usedNetworkType)) { 1404 enforceConnectivityInternalPermission(); 1405 } 1406 1407 // if UID is restricted, don't allow them to bring up metered APNs 1408 final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType); 1409 final int uidRules; 1410 synchronized (mRulesLock) { 1411 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL); 1412 } 1413 if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) { 1414 return PhoneConstants.APN_REQUEST_FAILED; 1415 } 1416 1417 NetworkStateTracker network = mNetTrackers[usedNetworkType]; 1418 if (network != null) { 1419 Integer currentPid = new Integer(getCallingPid()); 1420 if (usedNetworkType != networkType) { 1421 NetworkInfo ni = network.getNetworkInfo(); 1422 1423 if (ni.isAvailable() == false) { 1424 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) { 1425 if (DBG) log("special network not available ni=" + ni.getTypeName()); 1426 return PhoneConstants.APN_TYPE_NOT_AVAILABLE; 1427 } else { 1428 // else make the attempt anyway - probably giving REQUEST_STARTED below 1429 if (DBG) { 1430 log("special network not available, but try anyway ni=" + 1431 ni.getTypeName()); 1432 } 1433 } 1434 } 1435 1436 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType); 1437 1438 synchronized(this) { 1439 boolean addToList = true; 1440 if (restoreTimer < 0) { 1441 // In case there is no timer is specified for the feature, 1442 // make sure we don't add duplicate entry with the same request. 1443 for (FeatureUser u : mFeatureUsers) { 1444 if (u.isSameUser(f)) { 1445 // Duplicate user is found. Do not add. 1446 addToList = false; 1447 break; 1448 } 1449 } 1450 } 1451 1452 if (addToList) mFeatureUsers.add(f); 1453 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) { 1454 // this gets used for per-pid dns when connected 1455 mNetRequestersPids[usedNetworkType].add(currentPid); 1456 } 1457 } 1458 1459 if (restoreTimer >= 0) { 1460 mHandler.sendMessageDelayed(mHandler.obtainMessage( 1461 EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer); 1462 } 1463 1464 if ((ni.isConnectedOrConnecting() == true) && 1465 !network.isTeardownRequested()) { 1466 if (ni.isConnected() == true) { 1467 final long token = Binder.clearCallingIdentity(); 1468 try { 1469 // add the pid-specific dns 1470 handleDnsConfigurationChange(usedNetworkType); 1471 if (VDBG) log("special network already active"); 1472 } finally { 1473 Binder.restoreCallingIdentity(token); 1474 } 1475 return PhoneConstants.APN_ALREADY_ACTIVE; 1476 } 1477 if (VDBG) log("special network already connecting"); 1478 return PhoneConstants.APN_REQUEST_STARTED; 1479 } 1480 1481 // check if the radio in play can make another contact 1482 // assume if cannot for now 1483 1484 if (DBG) { 1485 log("startUsingNetworkFeature reconnecting to " + networkType + ": " + 1486 feature); 1487 } 1488 if (network.reconnect()) { 1489 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED"); 1490 return PhoneConstants.APN_REQUEST_STARTED; 1491 } else { 1492 if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED"); 1493 return PhoneConstants.APN_REQUEST_FAILED; 1494 } 1495 } else { 1496 // need to remember this unsupported request so we respond appropriately on stop 1497 synchronized(this) { 1498 mFeatureUsers.add(f); 1499 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) { 1500 // this gets used for per-pid dns when connected 1501 mNetRequestersPids[usedNetworkType].add(currentPid); 1502 } 1503 } 1504 if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature."); 1505 return -1; 1506 } 1507 } 1508 if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE"); 1509 return PhoneConstants.APN_TYPE_NOT_AVAILABLE; 1510 } finally { 1511 if (DBG) { 1512 final long execTime = SystemClock.elapsedRealtime() - startTime; 1513 if (execTime > 250) { 1514 loge("startUsingNetworkFeature took too long: " + execTime + "ms"); 1515 } else { 1516 if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms"); 1517 } 1518 } 1519 } 1520 } 1521 1522 // javadoc from interface 1523 public int stopUsingNetworkFeature(int networkType, String feature) { 1524 enforceChangePermission(); 1525 1526 int pid = getCallingPid(); 1527 int uid = getCallingUid(); 1528 1529 FeatureUser u = null; 1530 boolean found = false; 1531 1532 synchronized(this) { 1533 for (FeatureUser x : mFeatureUsers) { 1534 if (x.isSameUser(pid, uid, networkType, feature)) { 1535 u = x; 1536 found = true; 1537 break; 1538 } 1539 } 1540 } 1541 if (found && u != null) { 1542 if (VDBG) log("stopUsingNetworkFeature: X"); 1543 // stop regardless of how many other time this proc had called start 1544 return stopUsingNetworkFeature(u, true); 1545 } else { 1546 // none found! 1547 if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring"); 1548 return 1; 1549 } 1550 } 1551 1552 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) { 1553 int networkType = u.mNetworkType; 1554 String feature = u.mFeature; 1555 int pid = u.mPid; 1556 int uid = u.mUid; 1557 1558 NetworkStateTracker tracker = null; 1559 boolean callTeardown = false; // used to carry our decision outside of sync block 1560 1561 if (VDBG) { 1562 log("stopUsingNetworkFeature: net " + networkType + ": " + feature); 1563 } 1564 1565 if (!ConnectivityManager.isNetworkTypeValid(networkType)) { 1566 if (DBG) { 1567 log("stopUsingNetworkFeature: net " + networkType + ": " + feature + 1568 ", net is invalid"); 1569 } 1570 return -1; 1571 } 1572 1573 // need to link the mFeatureUsers list with the mNetRequestersPids state in this 1574 // sync block 1575 synchronized(this) { 1576 // check if this process still has an outstanding start request 1577 if (!mFeatureUsers.contains(u)) { 1578 if (VDBG) { 1579 log("stopUsingNetworkFeature: this process has no outstanding requests" + 1580 ", ignoring"); 1581 } 1582 return 1; 1583 } 1584 u.unlinkDeathRecipient(); 1585 mFeatureUsers.remove(mFeatureUsers.indexOf(u)); 1586 // If we care about duplicate requests, check for that here. 1587 // 1588 // This is done to support the extension of a request - the app 1589 // can request we start the network feature again and renew the 1590 // auto-shutoff delay. Normal "stop" calls from the app though 1591 // do not pay attention to duplicate requests - in effect the 1592 // API does not refcount and a single stop will counter multiple starts. 1593 if (ignoreDups == false) { 1594 for (FeatureUser x : mFeatureUsers) { 1595 if (x.isSameUser(u)) { 1596 if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring"); 1597 return 1; 1598 } 1599 } 1600 } 1601 1602 // TODO - move to individual network trackers 1603 int usedNetworkType = convertFeatureToNetworkType(networkType, feature); 1604 1605 tracker = mNetTrackers[usedNetworkType]; 1606 if (tracker == null) { 1607 if (DBG) { 1608 log("stopUsingNetworkFeature: net " + networkType + ": " + feature + 1609 " no known tracker for used net type " + usedNetworkType); 1610 } 1611 return -1; 1612 } 1613 if (usedNetworkType != networkType) { 1614 Integer currentPid = new Integer(pid); 1615 mNetRequestersPids[usedNetworkType].remove(currentPid); 1616 1617 final long token = Binder.clearCallingIdentity(); 1618 try { 1619 reassessPidDns(pid, true); 1620 } finally { 1621 Binder.restoreCallingIdentity(token); 1622 } 1623 flushVmDnsCache(); 1624 if (mNetRequestersPids[usedNetworkType].size() != 0) { 1625 if (VDBG) { 1626 log("stopUsingNetworkFeature: net " + networkType + ": " + feature + 1627 " others still using it"); 1628 } 1629 return 1; 1630 } 1631 callTeardown = true; 1632 } else { 1633 if (DBG) { 1634 log("stopUsingNetworkFeature: net " + networkType + ": " + feature + 1635 " not a known feature - dropping"); 1636 } 1637 } 1638 } 1639 1640 if (callTeardown) { 1641 if (DBG) { 1642 log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature); 1643 } 1644 tracker.teardown(); 1645 return 1; 1646 } else { 1647 return -1; 1648 } 1649 } 1650 1651 /** 1652 * Check if the address falls into any of currently running VPN's route's. 1653 */ 1654 private boolean isAddressUnderVpn(InetAddress address) { 1655 synchronized (mVpns) { 1656 synchronized (mRoutesLock) { 1657 int uid = UserHandle.getCallingUserId(); 1658 Vpn vpn = mVpns.get(uid); 1659 if (vpn == null) { 1660 return false; 1661 } 1662 1663 // Check if an exemption exists for this address. 1664 for (LinkAddress destination : mExemptAddresses) { 1665 if (!NetworkUtils.addressTypeMatches(address, destination.getAddress())) { 1666 continue; 1667 } 1668 1669 int prefix = destination.getPrefixLength(); 1670 InetAddress addrMasked = NetworkUtils.getNetworkPart(address, prefix); 1671 InetAddress destMasked = NetworkUtils.getNetworkPart(destination.getAddress(), 1672 prefix); 1673 1674 if (addrMasked.equals(destMasked)) { 1675 return false; 1676 } 1677 } 1678 1679 // Finally check if the address is covered by the VPN. 1680 return vpn.isAddressCovered(address); 1681 } 1682 } 1683 } 1684 1685 /** 1686 * @deprecated use requestRouteToHostAddress instead 1687 * 1688 * Ensure that a network route exists to deliver traffic to the specified 1689 * host via the specified network interface. 1690 * @param networkType the type of the network over which traffic to the 1691 * specified host is to be routed 1692 * @param hostAddress the IP address of the host to which the route is 1693 * desired 1694 * @return {@code true} on success, {@code false} on failure 1695 */ 1696 public boolean requestRouteToHost(int networkType, int hostAddress, String packageName) { 1697 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress); 1698 1699 if (inetAddress == null) { 1700 return false; 1701 } 1702 1703 return requestRouteToHostAddress(networkType, inetAddress.getAddress(), packageName); 1704 } 1705 1706 /** 1707 * Ensure that a network route exists to deliver traffic to the specified 1708 * host via the specified network interface. 1709 * @param networkType the type of the network over which traffic to the 1710 * specified host is to be routed 1711 * @param hostAddress the IP address of the host to which the route is 1712 * desired 1713 * @return {@code true} on success, {@code false} on failure 1714 */ 1715 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress, 1716 String packageName) { 1717 enforceChangePermission(); 1718 if (mProtectedNetworks.contains(networkType)) { 1719 enforceConnectivityInternalPermission(); 1720 } 1721 boolean exempt; 1722 InetAddress addr; 1723 try { 1724 addr = InetAddress.getByAddress(hostAddress); 1725 } catch (UnknownHostException e) { 1726 if (DBG) log("requestRouteToHostAddress got " + e.toString()); 1727 return false; 1728 } 1729 // System apps may request routes bypassing the VPN to keep other networks working. 1730 if (Binder.getCallingUid() == Process.SYSTEM_UID) { 1731 exempt = true; 1732 } else { 1733 mAppOpsManager.checkPackage(Binder.getCallingUid(), packageName); 1734 try { 1735 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(packageName, 1736 0); 1737 exempt = (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 1738 } catch (NameNotFoundException e) { 1739 throw new IllegalArgumentException("Failed to find calling package details", e); 1740 } 1741 } 1742 1743 // Non-exempt routeToHost's can only be added if the host is not covered by the VPN. 1744 // This can be either because the VPN's routes do not cover the destination or a 1745 // system application added an exemption that covers this destination. 1746 if (!exempt && isAddressUnderVpn(addr)) { 1747 return false; 1748 } 1749 1750 if (!ConnectivityManager.isNetworkTypeValid(networkType)) { 1751 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType); 1752 return false; 1753 } 1754 1755 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 1756 if (nai == null) { 1757 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) { 1758 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType); 1759 } else { 1760 if (DBG) log("requestRouteToHostAddress on down network: " + networkType); 1761 } 1762 return false; 1763 } 1764 1765 DetailedState netState = nai.networkInfo.getDetailedState(); 1766 1767 if ((netState != DetailedState.CONNECTED && 1768 netState != DetailedState.CAPTIVE_PORTAL_CHECK)) { 1769 if (VDBG) { 1770 log("requestRouteToHostAddress on down network " 1771 + "(" + networkType + ") - dropped" 1772 + " netState=" + netState); 1773 } 1774 return false; 1775 } 1776 final int uid = Binder.getCallingUid(); 1777 final long token = Binder.clearCallingIdentity(); 1778 try { 1779 LinkProperties lp = nai.linkProperties; 1780 boolean ok = modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt, 1781 nai.network.netId, uid); 1782 if (DBG) log("requestRouteToHostAddress ok=" + ok); 1783 return ok; 1784 } finally { 1785 Binder.restoreCallingIdentity(token); 1786 } 1787 } 1788 1789 private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable, 1790 boolean exempt, int netId) { 1791 return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt, netId, false, UID_UNUSED); 1792 } 1793 1794 private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable, int netId) { 1795 return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT, netId, false, UID_UNUSED); 1796 } 1797 1798 private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd, 1799 boolean toDefaultTable, boolean exempt, int netId, int uid) { 1800 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr); 1801 if (bestRoute == null) { 1802 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName()); 1803 } else { 1804 String iface = bestRoute.getInterface(); 1805 if (bestRoute.getGateway().equals(addr)) { 1806 // if there is no better route, add the implied hostroute for our gateway 1807 bestRoute = RouteInfo.makeHostRoute(addr, iface); 1808 } else { 1809 // if we will connect to this through another route, add a direct route 1810 // to it's gateway 1811 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface); 1812 } 1813 } 1814 return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt, netId, true, uid); 1815 } 1816 1817 /* 1818 * TODO: Clean all this stuff up. Once we have UID-based routing, stuff will break due to 1819 * incorrect tracking of mAddedRoutes, so a cleanup becomes necessary and urgent. But at 1820 * the same time, there'll be no more need to track mAddedRoutes or mExemptAddresses, 1821 * or even have the concept of an exempt address, or do things like "selectBestRoute", or 1822 * determine "default" vs "secondary" table, etc., so the cleanup becomes possible. 1823 */ 1824 private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd, 1825 boolean toDefaultTable, boolean exempt, int netId, boolean legacy, int uid) { 1826 if ((lp == null) || (r == null)) { 1827 if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r); 1828 return false; 1829 } 1830 1831 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) { 1832 loge("Error modifying route - too much recursion"); 1833 return false; 1834 } 1835 1836 String ifaceName = r.getInterface(); 1837 if(ifaceName == null) { 1838 loge("Error modifying route - no interface name"); 1839 return false; 1840 } 1841 if (r.hasGateway()) { 1842 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway()); 1843 if (bestRoute != null) { 1844 if (bestRoute.getGateway().equals(r.getGateway())) { 1845 // if there is no better route, add the implied hostroute for our gateway 1846 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName); 1847 } else { 1848 // if we will connect to our gateway through another route, add a direct 1849 // route to it's gateway 1850 bestRoute = RouteInfo.makeHostRoute(r.getGateway(), 1851 bestRoute.getGateway(), 1852 ifaceName); 1853 } 1854 modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt, netId, 1855 legacy, uid); 1856 } 1857 } 1858 if (doAdd) { 1859 if (VDBG) log("Adding " + r + " for interface " + ifaceName); 1860 try { 1861 if (toDefaultTable) { 1862 synchronized (mRoutesLock) { 1863 // only track default table - only one apps can effect 1864 mAddedRoutes.add(r); 1865 if (legacy) { 1866 mNetd.addLegacyRouteForNetId(netId, r, uid); 1867 } else { 1868 mNetd.addRoute(netId, r); 1869 } 1870 if (exempt) { 1871 LinkAddress dest = r.getDestinationLinkAddress(); 1872 if (!mExemptAddresses.contains(dest)) { 1873 mNetd.setHostExemption(dest); 1874 mExemptAddresses.add(dest); 1875 } 1876 } 1877 } 1878 } else { 1879 if (legacy) { 1880 mNetd.addLegacyRouteForNetId(netId, r, uid); 1881 } else { 1882 mNetd.addRoute(netId, r); 1883 } 1884 } 1885 } catch (Exception e) { 1886 // never crash - catch them all 1887 if (DBG) loge("Exception trying to add a route: " + e); 1888 return false; 1889 } 1890 } else { 1891 // if we remove this one and there are no more like it, then refcount==0 and 1892 // we can remove it from the table 1893 if (toDefaultTable) { 1894 synchronized (mRoutesLock) { 1895 mAddedRoutes.remove(r); 1896 if (mAddedRoutes.contains(r) == false) { 1897 if (VDBG) log("Removing " + r + " for interface " + ifaceName); 1898 try { 1899 if (legacy) { 1900 mNetd.removeLegacyRouteForNetId(netId, r, uid); 1901 } else { 1902 mNetd.removeRoute(netId, r); 1903 } 1904 LinkAddress dest = r.getDestinationLinkAddress(); 1905 if (mExemptAddresses.contains(dest)) { 1906 mNetd.clearHostExemption(dest); 1907 mExemptAddresses.remove(dest); 1908 } 1909 } catch (Exception e) { 1910 // never crash - catch them all 1911 if (VDBG) loge("Exception trying to remove a route: " + e); 1912 return false; 1913 } 1914 } else { 1915 if (VDBG) log("not removing " + r + " as it's still in use"); 1916 } 1917 } 1918 } else { 1919 if (VDBG) log("Removing " + r + " for interface " + ifaceName); 1920 try { 1921 if (legacy) { 1922 mNetd.removeLegacyRouteForNetId(netId, r, uid); 1923 } else { 1924 mNetd.removeRoute(netId, r); 1925 } 1926 } catch (Exception e) { 1927 // never crash - catch them all 1928 if (VDBG) loge("Exception trying to remove a route: " + e); 1929 return false; 1930 } 1931 } 1932 } 1933 return true; 1934 } 1935 1936 public void setDataDependency(int networkType, boolean met) { 1937 enforceConnectivityInternalPermission(); 1938 1939 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET, 1940 (met ? ENABLED : DISABLED), networkType)); 1941 } 1942 1943 private void handleSetDependencyMet(int networkType, boolean met) { 1944 if (mNetTrackers[networkType] != null) { 1945 if (DBG) { 1946 log("handleSetDependencyMet(" + networkType + ", " + met + ")"); 1947 } 1948 mNetTrackers[networkType].setDependencyMet(met); 1949 } 1950 } 1951 1952 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() { 1953 @Override 1954 public void onUidRulesChanged(int uid, int uidRules) { 1955 // caller is NPMS, since we only register with them 1956 if (LOGD_RULES) { 1957 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")"); 1958 } 1959 1960 synchronized (mRulesLock) { 1961 // skip update when we've already applied rules 1962 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL); 1963 if (oldRules == uidRules) return; 1964 1965 mUidRules.put(uid, uidRules); 1966 } 1967 1968 // TODO: notify UID when it has requested targeted updates 1969 } 1970 1971 @Override 1972 public void onMeteredIfacesChanged(String[] meteredIfaces) { 1973 // caller is NPMS, since we only register with them 1974 if (LOGD_RULES) { 1975 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")"); 1976 } 1977 1978 synchronized (mRulesLock) { 1979 mMeteredIfaces.clear(); 1980 for (String iface : meteredIfaces) { 1981 mMeteredIfaces.add(iface); 1982 } 1983 } 1984 } 1985 1986 @Override 1987 public void onRestrictBackgroundChanged(boolean restrictBackground) { 1988 // caller is NPMS, since we only register with them 1989 if (LOGD_RULES) { 1990 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")"); 1991 } 1992 1993 // kick off connectivity change broadcast for active network, since 1994 // global background policy change is radical. 1995 final int networkType = mActiveDefaultNetwork; 1996 if (isNetworkTypeValid(networkType)) { 1997 final NetworkStateTracker tracker = mNetTrackers[networkType]; 1998 if (tracker != null) { 1999 final NetworkInfo info = tracker.getNetworkInfo(); 2000 if (info != null && info.isConnected()) { 2001 sendConnectedBroadcast(info); 2002 } 2003 } 2004 } 2005 } 2006 }; 2007 2008 @Override 2009 public void setPolicyDataEnable(int networkType, boolean enabled) { 2010 // only someone like NPMS should only be calling us 2011 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG); 2012 2013 mHandler.sendMessage(mHandler.obtainMessage( 2014 EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED))); 2015 } 2016 2017 private void handleSetPolicyDataEnable(int networkType, boolean enabled) { 2018 // TODO - handle this passing to factories 2019// if (isNetworkTypeValid(networkType)) { 2020// final NetworkStateTracker tracker = mNetTrackers[networkType]; 2021// if (tracker != null) { 2022// tracker.setPolicyDataEnable(enabled); 2023// } 2024// } 2025 } 2026 2027 private void enforceAccessPermission() { 2028 mContext.enforceCallingOrSelfPermission( 2029 android.Manifest.permission.ACCESS_NETWORK_STATE, 2030 "ConnectivityService"); 2031 } 2032 2033 private void enforceChangePermission() { 2034 mContext.enforceCallingOrSelfPermission( 2035 android.Manifest.permission.CHANGE_NETWORK_STATE, 2036 "ConnectivityService"); 2037 } 2038 2039 // TODO Make this a special check when it goes public 2040 private void enforceTetherChangePermission() { 2041 mContext.enforceCallingOrSelfPermission( 2042 android.Manifest.permission.CHANGE_NETWORK_STATE, 2043 "ConnectivityService"); 2044 } 2045 2046 private void enforceTetherAccessPermission() { 2047 mContext.enforceCallingOrSelfPermission( 2048 android.Manifest.permission.ACCESS_NETWORK_STATE, 2049 "ConnectivityService"); 2050 } 2051 2052 private void enforceConnectivityInternalPermission() { 2053 mContext.enforceCallingOrSelfPermission( 2054 android.Manifest.permission.CONNECTIVITY_INTERNAL, 2055 "ConnectivityService"); 2056 } 2057 2058 private void enforceMarkNetworkSocketPermission() { 2059 //Media server special case 2060 if (Binder.getCallingUid() == Process.MEDIA_UID) { 2061 return; 2062 } 2063 mContext.enforceCallingOrSelfPermission( 2064 android.Manifest.permission.MARK_NETWORK_SOCKET, 2065 "ConnectivityService"); 2066 } 2067 2068 /** 2069 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active 2070 * network, we ignore it. If it is for the active network, we send out a 2071 * broadcast. But first, we check whether it might be possible to connect 2072 * to a different network. 2073 * @param info the {@code NetworkInfo} for the network 2074 */ 2075 private void handleDisconnect(NetworkInfo info) { 2076 2077 int prevNetType = info.getType(); 2078 2079 mNetTrackers[prevNetType].setTeardownRequested(false); 2080 int thisNetId = mNetTrackers[prevNetType].getNetwork().netId; 2081 2082 // Remove idletimer previously setup in {@code handleConnect} 2083// Already in place in new function. This is dead code. 2084// if (mNetConfigs[prevNetType].isDefault()) { 2085// removeDataActivityTracking(prevNetType); 2086// } 2087 2088 /* 2089 * If the disconnected network is not the active one, then don't report 2090 * this as a loss of connectivity. What probably happened is that we're 2091 * getting the disconnect for a network that we explicitly disabled 2092 * in accordance with network preference policies. 2093 */ 2094 if (!mNetConfigs[prevNetType].isDefault()) { 2095 List<Integer> pids = mNetRequestersPids[prevNetType]; 2096 for (Integer pid : pids) { 2097 // will remove them because the net's no longer connected 2098 // need to do this now as only now do we know the pids and 2099 // can properly null things that are no longer referenced. 2100 reassessPidDns(pid.intValue(), false); 2101 } 2102 } 2103 2104 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 2105 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info)); 2106 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 2107 if (info.isFailover()) { 2108 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 2109 info.setFailover(false); 2110 } 2111 if (info.getReason() != null) { 2112 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 2113 } 2114 if (info.getExtraInfo() != null) { 2115 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, 2116 info.getExtraInfo()); 2117 } 2118 2119 if (mNetConfigs[prevNetType].isDefault()) { 2120 tryFailover(prevNetType); 2121 if (mActiveDefaultNetwork != -1) { 2122 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(); 2123 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo); 2124 } else { 2125 mDefaultInetConditionPublished = 0; // we're not connected anymore 2126 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 2127 } 2128 } 2129 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished); 2130 2131 // Reset interface if no other connections are using the same interface 2132 boolean doReset = true; 2133 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties(); 2134 if (linkProperties != null) { 2135 String oldIface = linkProperties.getInterfaceName(); 2136 if (TextUtils.isEmpty(oldIface) == false) { 2137 for (NetworkStateTracker networkStateTracker : mNetTrackers) { 2138 if (networkStateTracker == null) continue; 2139 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo(); 2140 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) { 2141 LinkProperties l = networkStateTracker.getLinkProperties(); 2142 if (l == null) continue; 2143 if (oldIface.equals(l.getInterfaceName())) { 2144 doReset = false; 2145 break; 2146 } 2147 } 2148 } 2149 } 2150 } 2151 2152 // do this before we broadcast the change 2153// Already done in new function. This is dead code. 2154// handleConnectivityChange(prevNetType, doReset); 2155 2156 final Intent immediateIntent = new Intent(intent); 2157 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE); 2158 sendStickyBroadcast(immediateIntent); 2159 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay()); 2160 /* 2161 * If the failover network is already connected, then immediately send 2162 * out a followup broadcast indicating successful failover 2163 */ 2164 if (mActiveDefaultNetwork != -1) { 2165 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(), 2166 getConnectivityChangeDelay()); 2167 } 2168 try { 2169// mNetd.removeNetwork(thisNetId); 2170 } catch (Exception e) { 2171 loge("Exception removing network: " + e); 2172 } finally { 2173 mNetTrackers[prevNetType].setNetId(INVALID_NET_ID); 2174 } 2175 } 2176 2177 private void tryFailover(int prevNetType) { 2178 /* 2179 * If this is a default network, check if other defaults are available. 2180 * Try to reconnect on all available and let them hash it out when 2181 * more than one connects. 2182 */ 2183 if (mNetConfigs[prevNetType].isDefault()) { 2184 if (mActiveDefaultNetwork == prevNetType) { 2185 if (DBG) { 2186 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType); 2187 } 2188 mActiveDefaultNetwork = -1; 2189 try { 2190 mNetd.clearDefaultNetId(); 2191 } catch (Exception e) { 2192 loge("Exception clearing default network :" + e); 2193 } 2194 } 2195 2196 // don't signal a reconnect for anything lower or equal priority than our 2197 // current connected default 2198 // TODO - don't filter by priority now - nice optimization but risky 2199// int currentPriority = -1; 2200// if (mActiveDefaultNetwork != -1) { 2201// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority; 2202// } 2203 2204 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) { 2205 if (checkType == prevNetType) continue; 2206 if (mNetConfigs[checkType] == null) continue; 2207 if (!mNetConfigs[checkType].isDefault()) continue; 2208 if (mNetTrackers[checkType] == null) continue; 2209 2210// Enabling the isAvailable() optimization caused mobile to not get 2211// selected if it was in the middle of error handling. Specifically 2212// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL 2213// would not be available and we wouldn't get connected to anything. 2214// So removing the isAvailable() optimization below for now. TODO: This 2215// optimization should work and we need to investigate why it doesn't work. 2216// This could be related to how DEACTIVATE_DATA_CALL is reporting its 2217// complete before it is really complete. 2218 2219// if (!mNetTrackers[checkType].isAvailable()) continue; 2220 2221// if (currentPriority >= mNetConfigs[checkType].mPriority) continue; 2222 2223 NetworkStateTracker checkTracker = mNetTrackers[checkType]; 2224 NetworkInfo checkInfo = checkTracker.getNetworkInfo(); 2225 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) { 2226 checkInfo.setFailover(true); 2227 checkTracker.reconnect(); 2228 } 2229 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName()); 2230 } 2231 } 2232 } 2233 2234 public void sendConnectedBroadcast(NetworkInfo info) { 2235 enforceConnectivityInternalPermission(); 2236 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE); 2237 sendGeneralBroadcast(info, CONNECTIVITY_ACTION); 2238 } 2239 2240 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) { 2241 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE); 2242 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs); 2243 } 2244 2245 private void sendInetConditionBroadcast(NetworkInfo info) { 2246 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION); 2247 } 2248 2249 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) { 2250 if (mLockdownTracker != null) { 2251 info = mLockdownTracker.augmentNetworkInfo(info); 2252 } 2253 2254 Intent intent = new Intent(bcastType); 2255 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info)); 2256 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 2257 if (info.isFailover()) { 2258 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 2259 info.setFailover(false); 2260 } 2261 if (info.getReason() != null) { 2262 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 2263 } 2264 if (info.getExtraInfo() != null) { 2265 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, 2266 info.getExtraInfo()); 2267 } 2268 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished); 2269 return intent; 2270 } 2271 2272 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) { 2273 sendStickyBroadcast(makeGeneralIntent(info, bcastType)); 2274 } 2275 2276 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) { 2277 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs); 2278 } 2279 2280 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) { 2281 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE); 2282 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType); 2283 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active); 2284 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos); 2285 final long ident = Binder.clearCallingIdentity(); 2286 try { 2287 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL, 2288 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null); 2289 } finally { 2290 Binder.restoreCallingIdentity(ident); 2291 } 2292 } 2293 2294 private void sendStickyBroadcast(Intent intent) { 2295 synchronized(this) { 2296 if (!mSystemReady) { 2297 mInitialBroadcast = new Intent(intent); 2298 } 2299 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 2300 if (VDBG) { 2301 log("sendStickyBroadcast: action=" + intent.getAction()); 2302 } 2303 2304 final long ident = Binder.clearCallingIdentity(); 2305 try { 2306 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 2307 } finally { 2308 Binder.restoreCallingIdentity(ident); 2309 } 2310 } 2311 } 2312 2313 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) { 2314 if (delayMs <= 0) { 2315 sendStickyBroadcast(intent); 2316 } else { 2317 if (VDBG) { 2318 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action=" 2319 + intent.getAction()); 2320 } 2321 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2322 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs); 2323 } 2324 } 2325 2326 void systemReady() { 2327 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this); 2328 loadGlobalProxy(); 2329 2330 synchronized(this) { 2331 mSystemReady = true; 2332 if (mInitialBroadcast != null) { 2333 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL); 2334 mInitialBroadcast = null; 2335 } 2336 } 2337 // load the global proxy at startup 2338 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY)); 2339 2340 // Try bringing up tracker, but if KeyStore isn't ready yet, wait 2341 // for user to unlock device. 2342 if (!updateLockdownVpn()) { 2343 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT); 2344 mContext.registerReceiver(mUserPresentReceiver, filter); 2345 } 2346 } 2347 2348 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() { 2349 @Override 2350 public void onReceive(Context context, Intent intent) { 2351 // Try creating lockdown tracker, since user present usually means 2352 // unlocked keystore. 2353 if (updateLockdownVpn()) { 2354 mContext.unregisterReceiver(this); 2355 } 2356 } 2357 }; 2358 2359 private boolean isNewNetTypePreferredOverCurrentNetType(int type) { 2360 if (((type != mNetworkPreference) 2361 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority)) 2362 || (mNetworkPreference == mActiveDefaultNetwork)) { 2363 return false; 2364 } 2365 return true; 2366 } 2367 2368 private void handleConnect(NetworkInfo info) { 2369 final int newNetType = info.getType(); 2370 2371 // snapshot isFailover, because sendConnectedBroadcast() resets it 2372 boolean isFailover = info.isFailover(); 2373 final NetworkStateTracker thisNet = mNetTrackers[newNetType]; 2374 final String thisIface = thisNet.getLinkProperties().getInterfaceName(); 2375 2376 if (VDBG) { 2377 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface 2378 + " isFailover" + isFailover); 2379 } 2380 2381 // if this is a default net and other default is running 2382 // kill the one not preferred 2383 if (mNetConfigs[newNetType].isDefault()) { 2384 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) { 2385 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) { 2386 String teardownPolicy = SystemProperties.get("net.teardownPolicy"); 2387 if (TextUtils.equals(teardownPolicy, "keep") == false) { 2388 // tear down the other 2389 NetworkStateTracker otherNet = 2390 mNetTrackers[mActiveDefaultNetwork]; 2391 if (DBG) { 2392 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() + 2393 " teardown"); 2394 } 2395 if (!teardown(otherNet)) { 2396 loge("Network declined teardown request"); 2397 teardown(thisNet); 2398 return; 2399 } 2400 } else { 2401 //TODO - remove 2402 loge("network teardown skipped due to net.teardownPolicy setting"); 2403 } 2404 } else { 2405 // don't accept this one 2406 if (VDBG) { 2407 log("Not broadcasting CONNECT_ACTION " + 2408 "to torn down network " + info.getTypeName()); 2409 } 2410 teardown(thisNet); 2411 return; 2412 } 2413 } 2414 int thisNetId = nextNetId(); 2415 thisNet.setNetId(thisNetId); 2416 try { 2417// mNetd.createNetwork(thisNetId, thisIface); 2418 } catch (Exception e) { 2419 loge("Exception creating network :" + e); 2420 teardown(thisNet); 2421 return; 2422 } 2423// Already in place in new function. This is dead code. 2424// setupDataActivityTracking(newNetType); 2425 synchronized (ConnectivityService.this) { 2426 // have a new default network, release the transition wakelock in a second 2427 // if it's held. The second pause is to allow apps to reconnect over the 2428 // new network 2429 if (mNetTransitionWakeLock.isHeld()) { 2430 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2431 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 2432 mNetTransitionWakeLockSerialNumber, 0), 2433 1000); 2434 } 2435 } 2436 mActiveDefaultNetwork = newNetType; 2437 try { 2438 mNetd.setDefaultNetId(thisNetId); 2439 } catch (Exception e) { 2440 loge("Exception setting default network :" + e); 2441 } 2442 // this will cause us to come up initially as unconnected and switching 2443 // to connected after our normal pause unless somebody reports us as reall 2444 // disconnected 2445 mDefaultInetConditionPublished = 0; 2446 mDefaultConnectionSequence++; 2447 mInetConditionChangeInFlight = false; 2448 // Don't do this - if we never sign in stay, grey 2449 //reportNetworkCondition(mActiveDefaultNetwork, 100); 2450 updateNetworkSettings(thisNet); 2451 } else { 2452 int thisNetId = nextNetId(); 2453 thisNet.setNetId(thisNetId); 2454 try { 2455// mNetd.createNetwork(thisNetId, thisIface); 2456 } catch (Exception e) { 2457 loge("Exception creating network :" + e); 2458 teardown(thisNet); 2459 return; 2460 } 2461 } 2462 thisNet.setTeardownRequested(false); 2463// Already in place in new function. This is dead code. 2464// updateMtuSizeSettings(thisNet); 2465// handleConnectivityChange(newNetType, false); 2466 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay()); 2467 2468 // notify battery stats service about this network 2469 if (thisIface != null) { 2470 try { 2471 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType); 2472 } catch (RemoteException e) { 2473 // ignored; service lives in system_server 2474 } 2475 } 2476 } 2477 2478 /** @hide */ 2479 @Override 2480 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) { 2481 enforceConnectivityInternalPermission(); 2482 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal); 2483// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal); 2484 } 2485 2486 /** 2487 * Setup data activity tracking for the given network. 2488 * 2489 * Every {@code setupDataActivityTracking} should be paired with a 2490 * {@link #removeDataActivityTracking} for cleanup. 2491 */ 2492 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) { 2493 final String iface = networkAgent.linkProperties.getInterfaceName(); 2494 2495 final int timeout; 2496 int type = ConnectivityManager.TYPE_NONE; 2497 2498 if (networkAgent.networkCapabilities.hasTransport( 2499 NetworkCapabilities.TRANSPORT_CELLULAR)) { 2500 timeout = Settings.Global.getInt(mContext.getContentResolver(), 2501 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE, 2502 5); 2503 type = ConnectivityManager.TYPE_MOBILE; 2504 } else if (networkAgent.networkCapabilities.hasTransport( 2505 NetworkCapabilities.TRANSPORT_WIFI)) { 2506 timeout = Settings.Global.getInt(mContext.getContentResolver(), 2507 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI, 2508 0); 2509 type = ConnectivityManager.TYPE_WIFI; 2510 } else { 2511 // do not track any other networks 2512 timeout = 0; 2513 } 2514 2515 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) { 2516 try { 2517 mNetd.addIdleTimer(iface, timeout, type); 2518 } catch (Exception e) { 2519 // You shall not crash! 2520 loge("Exception in setupDataActivityTracking " + e); 2521 } 2522 } 2523 } 2524 2525 /** 2526 * Remove data activity tracking when network disconnects. 2527 */ 2528 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) { 2529 final String iface = networkAgent.linkProperties.getInterfaceName(); 2530 final NetworkCapabilities caps = networkAgent.networkCapabilities; 2531 2532 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || 2533 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) { 2534 try { 2535 // the call fails silently if no idletimer setup for this interface 2536 mNetd.removeIdleTimer(iface); 2537 } catch (Exception e) { 2538 loge("Exception in removeDataActivityTracking " + e); 2539 } 2540 } 2541 } 2542 2543 /** 2544 * After a change in the connectivity state of a network. We're mainly 2545 * concerned with making sure that the list of DNS servers is set up 2546 * according to which networks are connected, and ensuring that the 2547 * right routing table entries exist. 2548 * 2549 * TODO - delete when we're sure all this functionallity is captured. 2550 */ 2551 private void handleConnectivityChange(int netType, LinkProperties curLp, boolean doReset) { 2552 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0; 2553 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType); 2554 if (VDBG) { 2555 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset 2556 + " resetMask=" + resetMask); 2557 } 2558 2559 /* 2560 * If a non-default network is enabled, add the host routes that 2561 * will allow it's DNS servers to be accessed. 2562 */ 2563 handleDnsConfigurationChange(netType); 2564 2565 LinkProperties newLp = null; 2566 2567 if (mNetTrackers[netType].getNetworkInfo().isConnected()) { 2568 newLp = mNetTrackers[netType].getLinkProperties(); 2569 if (VDBG) { 2570 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" + 2571 " doReset=" + doReset + " resetMask=" + resetMask + 2572 "\n curLp=" + curLp + 2573 "\n newLp=" + newLp); 2574 } 2575 2576 if (curLp != null) { 2577 if (curLp.isIdenticalInterfaceName(newLp)) { 2578 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp); 2579 if ((car.removed.size() != 0) || (car.added.size() != 0)) { 2580 for (LinkAddress linkAddr : car.removed) { 2581 if (linkAddr.getAddress() instanceof Inet4Address) { 2582 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES; 2583 } 2584 if (linkAddr.getAddress() instanceof Inet6Address) { 2585 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES; 2586 } 2587 } 2588 if (DBG) { 2589 log("handleConnectivityChange: addresses changed" + 2590 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask + 2591 "\n car=" + car); 2592 } 2593 } else { 2594 if (VDBG) { 2595 log("handleConnectivityChange: addresses are the same reset per" + 2596 " doReset linkProperty[" + netType + "]:" + 2597 " resetMask=" + resetMask); 2598 } 2599 } 2600 } else { 2601 resetMask = NetworkUtils.RESET_ALL_ADDRESSES; 2602 if (DBG) { 2603 log("handleConnectivityChange: interface not not equivalent reset both" + 2604 " linkProperty[" + netType + "]:" + 2605 " resetMask=" + resetMask); 2606 } 2607 } 2608 } 2609 if (mNetConfigs[netType].isDefault()) { 2610 handleApplyDefaultProxy(newLp.getHttpProxy()); 2611 } 2612 } else { 2613 if (VDBG) { 2614 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" + 2615 " doReset=" + doReset + " resetMask=" + resetMask + 2616 "\n curLp=" + curLp + 2617 "\n newLp= null"); 2618 } 2619 } 2620 mCurrentLinkProperties[netType] = newLp; 2621 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt, 2622 mNetTrackers[netType].getNetwork().netId); 2623 2624 if (resetMask != 0 || resetDns) { 2625 if (VDBG) log("handleConnectivityChange: resetting"); 2626 if (curLp != null) { 2627 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp); 2628 for (String iface : curLp.getAllInterfaceNames()) { 2629 if (TextUtils.isEmpty(iface) == false) { 2630 if (resetMask != 0) { 2631 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")"); 2632 NetworkUtils.resetConnections(iface, resetMask); 2633 2634 // Tell VPN the interface is down. It is a temporary 2635 // but effective fix to make VPN aware of the change. 2636 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) { 2637 synchronized(mVpns) { 2638 for (int i = 0; i < mVpns.size(); i++) { 2639 mVpns.valueAt(i).interfaceStatusChanged(iface, false); 2640 } 2641 } 2642 } 2643 } 2644 } else { 2645 loge("Can't reset connection for type "+netType); 2646 } 2647 } 2648 if (resetDns) { 2649 flushVmDnsCache(); 2650 if (VDBG) log("resetting DNS cache for type " + netType); 2651 try { 2652 mNetd.flushNetworkDnsCache(mNetTrackers[netType].getNetwork().netId); 2653 } catch (Exception e) { 2654 // never crash - catch them all 2655 if (DBG) loge("Exception resetting dns cache: " + e); 2656 } 2657 } 2658 } 2659 } 2660 2661 // TODO: Temporary notifying upstread change to Tethering. 2662 // @see bug/4455071 2663 /** Notify TetheringService if interface name has been changed. */ 2664 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(), 2665 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) { 2666 if (isTetheringSupported()) { 2667 mTethering.handleTetherIfaceChange(); 2668 } 2669 } 2670 } 2671 2672 /** 2673 * Add and remove routes using the old properties (null if not previously connected), 2674 * new properties (null if becoming disconnected). May even be double null, which 2675 * is a noop. 2676 * Uses isLinkDefault to determine if default routes should be set or conversely if 2677 * host routes should be set to the dns servers 2678 * returns a boolean indicating the routes changed 2679 */ 2680 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp, 2681 boolean isLinkDefault, boolean exempt, int netId) { 2682 Collection<RouteInfo> routesToAdd = null; 2683 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>(); 2684 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 2685 if (curLp != null) { 2686 // check for the delta between the current set and the new 2687 routeDiff = curLp.compareAllRoutes(newLp); 2688 dnsDiff = curLp.compareDnses(newLp); 2689 } else if (newLp != null) { 2690 routeDiff.added = newLp.getAllRoutes(); 2691 dnsDiff.added = newLp.getDnsServers(); 2692 } 2693 2694 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0); 2695 2696 for (RouteInfo r : routeDiff.removed) { 2697 if (isLinkDefault || ! r.isDefaultRoute()) { 2698 if (VDBG) log("updateRoutes: default remove route r=" + r); 2699 removeRoute(curLp, r, TO_DEFAULT_TABLE, netId); 2700 } 2701 if (isLinkDefault == false) { 2702 // remove from a secondary route table 2703 removeRoute(curLp, r, TO_SECONDARY_TABLE, netId); 2704 } 2705 } 2706 2707 for (RouteInfo r : routeDiff.added) { 2708 if (isLinkDefault || ! r.isDefaultRoute()) { 2709 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt, netId); 2710 } else { 2711 // add to a secondary route table 2712 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT, netId); 2713 2714 // many radios add a default route even when we don't want one. 2715 // remove the default route unless somebody else has asked for it 2716 String ifaceName = newLp.getInterfaceName(); 2717 synchronized (mRoutesLock) { 2718 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) { 2719 if (VDBG) log("Removing " + r + " for interface " + ifaceName); 2720 try { 2721 mNetd.removeRoute(netId, r); 2722 } catch (Exception e) { 2723 // never crash - catch them all 2724 if (DBG) loge("Exception trying to remove a route: " + e); 2725 } 2726 } 2727 } 2728 } 2729 } 2730 2731 return routesChanged; 2732 } 2733 2734 /** 2735 * Reads the network specific MTU size from reources. 2736 * and set it on it's iface. 2737 */ 2738 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) { 2739 final String iface = newLp.getInterfaceName(); 2740 final int mtu = newLp.getMtu(); 2741 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) { 2742 if (VDBG) log("identical MTU - not setting"); 2743 return; 2744 } 2745 2746 if (mtu < 68 || mtu > 10000) { 2747 loge("Unexpected mtu value: " + mtu + ", " + iface); 2748 return; 2749 } 2750 2751 try { 2752 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu); 2753 mNetd.setMtu(iface, mtu); 2754 } catch (Exception e) { 2755 Slog.e(TAG, "exception in setMtu()" + e); 2756 } 2757 } 2758 2759 /** 2760 * Reads the network specific TCP buffer sizes from SystemProperties 2761 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system 2762 * wide use 2763 */ 2764 private void updateNetworkSettings(NetworkStateTracker nt) { 2765 String key = nt.getTcpBufferSizesPropName(); 2766 String bufferSizes = key == null ? null : SystemProperties.get(key); 2767 2768 if (TextUtils.isEmpty(bufferSizes)) { 2769 if (VDBG) log(key + " not found in system properties. Using defaults"); 2770 2771 // Setting to default values so we won't be stuck to previous values 2772 key = "net.tcp.buffersize.default"; 2773 bufferSizes = SystemProperties.get(key); 2774 } 2775 2776 // Set values in kernel 2777 if (bufferSizes.length() != 0) { 2778 if (VDBG) { 2779 log("Setting TCP values: [" + bufferSizes 2780 + "] which comes from [" + key + "]"); 2781 } 2782 setBufferSize(bufferSizes); 2783 } 2784 2785 final String defaultRwndKey = "net.tcp.default_init_rwnd"; 2786 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0); 2787 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(), 2788 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue); 2789 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd"; 2790 if (rwndValue != 0) { 2791 SystemProperties.set(sysctlKey, rwndValue.toString()); 2792 } 2793 } 2794 2795 /** 2796 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max] 2797 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem 2798 * 2799 * @param bufferSizes in the format of "readMin, readInitial, readMax, 2800 * writeMin, writeInitial, writeMax" 2801 */ 2802 private void setBufferSize(String bufferSizes) { 2803 try { 2804 String[] values = bufferSizes.split(","); 2805 2806 if (values.length == 6) { 2807 final String prefix = "/sys/kernel/ipv4/tcp_"; 2808 FileUtils.stringToFile(prefix + "rmem_min", values[0]); 2809 FileUtils.stringToFile(prefix + "rmem_def", values[1]); 2810 FileUtils.stringToFile(prefix + "rmem_max", values[2]); 2811 FileUtils.stringToFile(prefix + "wmem_min", values[3]); 2812 FileUtils.stringToFile(prefix + "wmem_def", values[4]); 2813 FileUtils.stringToFile(prefix + "wmem_max", values[5]); 2814 } else { 2815 loge("Invalid buffersize string: " + bufferSizes); 2816 } 2817 } catch (IOException e) { 2818 loge("Can't set tcp buffer sizes:" + e); 2819 } 2820 } 2821 2822 /** 2823 * Adjust the per-process dns entries (net.dns<x>.<pid>) based 2824 * on the highest priority active net which this process requested. 2825 * If there aren't any, clear it out 2826 */ 2827 private void reassessPidDns(int pid, boolean doBump) 2828 { 2829 if (VDBG) log("reassessPidDns for pid " + pid); 2830 Integer myPid = new Integer(pid); 2831 for(int i : mPriorityList) { 2832 if (mNetConfigs[i].isDefault()) { 2833 continue; 2834 } 2835 NetworkStateTracker nt = mNetTrackers[i]; 2836 if (nt.getNetworkInfo().isConnected() && 2837 !nt.isTeardownRequested()) { 2838 LinkProperties p = nt.getLinkProperties(); 2839 if (p == null) continue; 2840 if (mNetRequestersPids[i].contains(myPid)) { 2841 try { 2842 // TODO: Reimplement this via local variable in bionic. 2843 // mNetd.setDnsNetworkForPid(nt.getNetwork().netId, pid); 2844 } catch (Exception e) { 2845 Slog.e(TAG, "exception reasseses pid dns: " + e); 2846 } 2847 return; 2848 } 2849 } 2850 } 2851 // nothing found - delete 2852 try { 2853 // TODO: Reimplement this via local variable in bionic. 2854 // mNetd.clearDnsNetworkForPid(pid); 2855 } catch (Exception e) { 2856 Slog.e(TAG, "exception clear interface from pid: " + e); 2857 } 2858 } 2859 2860 private void flushVmDnsCache() { 2861 /* 2862 * Tell the VMs to toss their DNS caches 2863 */ 2864 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE); 2865 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 2866 /* 2867 * Connectivity events can happen before boot has completed ... 2868 */ 2869 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 2870 final long ident = Binder.clearCallingIdentity(); 2871 try { 2872 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 2873 } finally { 2874 Binder.restoreCallingIdentity(ident); 2875 } 2876 } 2877 2878 // Caller must grab mDnsLock. 2879 private void updateDnsLocked(String network, int netId, 2880 Collection<InetAddress> dnses, String domains) { 2881 int last = 0; 2882 if (dnses.size() == 0 && mDefaultDns != null) { 2883 dnses = new ArrayList(); 2884 dnses.add(mDefaultDns); 2885 if (DBG) { 2886 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress()); 2887 } 2888 } 2889 2890 try { 2891 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), domains); 2892 2893 for (InetAddress dns : dnses) { 2894 ++last; 2895 String key = "net.dns" + last; 2896 String value = dns.getHostAddress(); 2897 SystemProperties.set(key, value); 2898 } 2899 for (int i = last + 1; i <= mNumDnsEntries; ++i) { 2900 String key = "net.dns" + i; 2901 SystemProperties.set(key, ""); 2902 } 2903 mNumDnsEntries = last; 2904 } catch (Exception e) { 2905 loge("exception setting default dns interface: " + e); 2906 } 2907 } 2908 2909 private void handleDnsConfigurationChange(int netType) { 2910 // add default net's dns entries 2911 NetworkStateTracker nt = mNetTrackers[netType]; 2912 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) { 2913 LinkProperties p = nt.getLinkProperties(); 2914 if (p == null) return; 2915 Collection<InetAddress> dnses = p.getDnsServers(); 2916 int netId = nt.getNetwork().netId; 2917 if (mNetConfigs[netType].isDefault()) { 2918 String network = nt.getNetworkInfo().getTypeName(); 2919 synchronized (mDnsLock) { 2920 updateDnsLocked(network, netId, dnses, p.getDomains()); 2921 } 2922 } else { 2923 try { 2924 mNetd.setDnsServersForNetwork(netId, 2925 NetworkUtils.makeStrings(dnses), p.getDomains()); 2926 } catch (Exception e) { 2927 if (DBG) loge("exception setting dns servers: " + e); 2928 } 2929 // set per-pid dns for attached secondary nets 2930 List<Integer> pids = mNetRequestersPids[netType]; 2931 for (Integer pid : pids) { 2932 try { 2933 // TODO: Reimplement this via local variable in bionic. 2934 // mNetd.setDnsNetworkForPid(netId, pid); 2935 } catch (Exception e) { 2936 Slog.e(TAG, "exception setting interface for pid: " + e); 2937 } 2938 } 2939 } 2940 flushVmDnsCache(); 2941 } 2942 } 2943 2944 @Override 2945 public int getRestoreDefaultNetworkDelay(int networkType) { 2946 String restoreDefaultNetworkDelayStr = SystemProperties.get( 2947 NETWORK_RESTORE_DELAY_PROP_NAME); 2948 if(restoreDefaultNetworkDelayStr != null && 2949 restoreDefaultNetworkDelayStr.length() != 0) { 2950 try { 2951 return Integer.valueOf(restoreDefaultNetworkDelayStr); 2952 } catch (NumberFormatException e) { 2953 } 2954 } 2955 // if the system property isn't set, use the value for the apn type 2956 int ret = RESTORE_DEFAULT_NETWORK_DELAY; 2957 2958 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) && 2959 (mNetConfigs[networkType] != null)) { 2960 ret = mNetConfigs[networkType].restoreTime; 2961 } 2962 return ret; 2963 } 2964 2965 @Override 2966 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) { 2967 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); 2968 if (mContext.checkCallingOrSelfPermission( 2969 android.Manifest.permission.DUMP) 2970 != PackageManager.PERMISSION_GRANTED) { 2971 pw.println("Permission Denial: can't dump ConnectivityService " + 2972 "from from pid=" + Binder.getCallingPid() + ", uid=" + 2973 Binder.getCallingUid()); 2974 return; 2975 } 2976 2977 pw.println("NetworkFactories for:"); 2978 pw.increaseIndent(); 2979 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 2980 pw.println(nfi.name); 2981 } 2982 pw.decreaseIndent(); 2983 pw.println(); 2984 2985 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId); 2986 pw.print("Active default network: "); 2987 if (defaultNai == null) { 2988 pw.println("none"); 2989 } else { 2990 pw.println(defaultNai.network.netId); 2991 } 2992 pw.println(); 2993 2994 pw.println("Current Networks:"); 2995 pw.increaseIndent(); 2996 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2997 pw.println(nai.toString()); 2998 pw.increaseIndent(); 2999 pw.println("Requests:"); 3000 pw.increaseIndent(); 3001 for (int i = 0; i < nai.networkRequests.size(); i++) { 3002 pw.println(nai.networkRequests.valueAt(i).toString()); 3003 } 3004 pw.decreaseIndent(); 3005 pw.println("Lingered:"); 3006 pw.increaseIndent(); 3007 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString()); 3008 pw.decreaseIndent(); 3009 pw.decreaseIndent(); 3010 } 3011 pw.decreaseIndent(); 3012 pw.println(); 3013 3014 pw.println("Network Requests:"); 3015 pw.increaseIndent(); 3016 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 3017 pw.println(nri.toString()); 3018 } 3019 pw.println(); 3020 pw.decreaseIndent(); 3021 3022 synchronized (this) { 3023 pw.println("NetworkTranstionWakeLock is currently " + 3024 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held."); 3025 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy); 3026 } 3027 pw.println(); 3028 3029 mTethering.dump(fd, pw, args); 3030 3031 if (mInetLog != null) { 3032 pw.println(); 3033 pw.println("Inet condition reports:"); 3034 pw.increaseIndent(); 3035 for(int i = 0; i < mInetLog.size(); i++) { 3036 pw.println(mInetLog.get(i)); 3037 } 3038 pw.decreaseIndent(); 3039 } 3040 } 3041 3042 // must be stateless - things change under us. 3043 private class NetworkStateTrackerHandler extends Handler { 3044 public NetworkStateTrackerHandler(Looper looper) { 3045 super(looper); 3046 } 3047 3048 @Override 3049 public void handleMessage(Message msg) { 3050 NetworkInfo info; 3051 switch (msg.what) { 3052 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: { 3053 handleAsyncChannelHalfConnect(msg); 3054 break; 3055 } 3056 case AsyncChannel.CMD_CHANNEL_DISCONNECT: { 3057 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3058 if (nai != null) nai.asyncChannel.disconnect(); 3059 break; 3060 } 3061 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: { 3062 handleAsyncChannelDisconnected(msg); 3063 break; 3064 } 3065 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: { 3066 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3067 if (nai == null) { 3068 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent"); 3069 } else { 3070 updateCapabilities(nai, (NetworkCapabilities)msg.obj); 3071 } 3072 break; 3073 } 3074 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: { 3075 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3076 if (nai == null) { 3077 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED"); 3078 } else { 3079 if (VDBG) log("Update of Linkproperties for " + nai.name()); 3080 LinkProperties oldLp = nai.linkProperties; 3081 nai.linkProperties = (LinkProperties)msg.obj; 3082 updateLinkProperties(nai, oldLp); 3083 } 3084 break; 3085 } 3086 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: { 3087 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3088 if (nai == null) { 3089 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent"); 3090 break; 3091 } 3092 info = (NetworkInfo) msg.obj; 3093 updateNetworkInfo(nai, info); 3094 break; 3095 } 3096 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: { 3097 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3098 if (nai == null) { 3099 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent"); 3100 break; 3101 } 3102 Integer score = (Integer) msg.obj; 3103 if (score != null) updateNetworkScore(nai, score.intValue()); 3104 break; 3105 } 3106 case NetworkMonitor.EVENT_NETWORK_VALIDATED: { 3107 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj; 3108 handleConnectionValidated(nai); 3109 break; 3110 } 3111 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: { 3112 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj; 3113 handleLingerComplete(nai); 3114 break; 3115 } 3116 case NetworkStateTracker.EVENT_STATE_CHANGED: { 3117 info = (NetworkInfo) msg.obj; 3118 NetworkInfo.State state = info.getState(); 3119 3120 if (VDBG || (state == NetworkInfo.State.CONNECTED) || 3121 (state == NetworkInfo.State.DISCONNECTED) || 3122 (state == NetworkInfo.State.SUSPENDED)) { 3123 log("ConnectivityChange for " + 3124 info.getTypeName() + ": " + 3125 state + "/" + info.getDetailedState()); 3126 } 3127 3128 // Since mobile has the notion of a network/apn that can be used for 3129 // provisioning we need to check every time we're connected as 3130 // CaptiveProtalTracker won't detected it because DCT doesn't report it 3131 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its 3132 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which 3133 // is received by MDST and sent here as EVENT_STATE_CHANGED. 3134 if (ConnectivityManager.isNetworkTypeMobile(info.getType()) 3135 && (0 != Settings.Global.getInt(mContext.getContentResolver(), 3136 Settings.Global.DEVICE_PROVISIONED, 0)) 3137 && (((state == NetworkInfo.State.CONNECTED) 3138 && (info.getType() == ConnectivityManager.TYPE_MOBILE)) 3139 || info.isConnectedToProvisioningNetwork())) { 3140 log("ConnectivityChange checkMobileProvisioning for" 3141 + " TYPE_MOBILE or ProvisioningNetwork"); 3142 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS); 3143 } 3144 3145 EventLogTags.writeConnectivityStateChanged( 3146 info.getType(), info.getSubtype(), info.getDetailedState().ordinal()); 3147 3148 if (info.isConnectedToProvisioningNetwork()) { 3149 /** 3150 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING 3151 * for now its an in between network, its a network that 3152 * is actually a default network but we don't want it to be 3153 * announced as such to keep background applications from 3154 * trying to use it. It turns out that some still try so we 3155 * take the additional step of clearing any default routes 3156 * to the link that may have incorrectly setup by the lower 3157 * levels. 3158 */ 3159 LinkProperties lp = getLinkPropertiesForTypeInternal(info.getType()); 3160 if (DBG) { 3161 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp); 3162 } 3163 3164 // Clear any default routes setup by the radio so 3165 // any activity by applications trying to use this 3166 // connection will fail until the provisioning network 3167 // is enabled. 3168 for (RouteInfo r : lp.getRoutes()) { 3169 removeRoute(lp, r, TO_DEFAULT_TABLE, 3170 mNetTrackers[info.getType()].getNetwork().netId); 3171 } 3172 } else if (state == NetworkInfo.State.DISCONNECTED) { 3173 } else if (state == NetworkInfo.State.SUSPENDED) { 3174 } else if (state == NetworkInfo.State.CONNECTED) { 3175 // handleConnect(info); 3176 } 3177 if (mLockdownTracker != null) { 3178 mLockdownTracker.onNetworkInfoChanged(info); 3179 } 3180 break; 3181 } 3182 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: { 3183 info = (NetworkInfo) msg.obj; 3184 // TODO: Temporary allowing network configuration 3185 // change not resetting sockets. 3186 // @see bug/4455071 3187 handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()], 3188 false); 3189 break; 3190 } 3191 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: { 3192 info = (NetworkInfo) msg.obj; 3193 int type = info.getType(); 3194 if (mNetConfigs[type].isDefault()) updateNetworkSettings(mNetTrackers[type]); 3195 break; 3196 } 3197 } 3198 } 3199 } 3200 3201 private void handleAsyncChannelHalfConnect(Message msg) { 3202 AsyncChannel ac = (AsyncChannel) msg.obj; 3203 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) { 3204 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 3205 if (VDBG) log("NetworkFactory connected"); 3206 // A network factory has connected. Send it all current NetworkRequests. 3207 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 3208 if (nri.isRequest == false) continue; 3209 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId); 3210 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, 3211 (nai != null ? nai.currentScore : 0), 0, nri.request); 3212 } 3213 } else { 3214 loge("Error connecting NetworkFactory"); 3215 mNetworkFactoryInfos.remove(msg.obj); 3216 } 3217 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) { 3218 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 3219 if (VDBG) log("NetworkAgent connected"); 3220 // A network agent has requested a connection. Establish the connection. 3221 mNetworkAgentInfos.get(msg.replyTo).asyncChannel. 3222 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION); 3223 } else { 3224 loge("Error connecting NetworkAgent"); 3225 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo); 3226 if (nai != null) { 3227 mNetworkForNetId.remove(nai.network.netId); 3228 mLegacyTypeTracker.remove(nai); 3229 } 3230 } 3231 } 3232 } 3233 private void handleAsyncChannelDisconnected(Message msg) { 3234 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3235 if (nai != null) { 3236 if (DBG) { 3237 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size()); 3238 } 3239 // A network agent has disconnected. 3240 // Tell netd to clean up the configuration for this network 3241 // (routing rules, DNS, etc). 3242 try { 3243 mNetd.removeNetwork(nai.network.netId); 3244 } catch (Exception e) { 3245 loge("Exception removing network: " + e); 3246 } 3247 // TODO - if we move the logic to the network agent (have them disconnect 3248 // because they lost all their requests or because their score isn't good) 3249 // then they would disconnect organically, report their new state and then 3250 // disconnect the channel. 3251 if (nai.networkInfo.isConnected()) { 3252 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, 3253 null, null); 3254 } 3255 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST); 3256 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED); 3257 mNetworkAgentInfos.remove(msg.replyTo); 3258 updateClat(null, nai.linkProperties, nai); 3259 mLegacyTypeTracker.remove(nai); 3260 mNetworkForNetId.remove(nai.network.netId); 3261 // Since we've lost the network, go through all the requests that 3262 // it was satisfying and see if any other factory can satisfy them. 3263 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>(); 3264 for (int i = 0; i < nai.networkRequests.size(); i++) { 3265 NetworkRequest request = nai.networkRequests.valueAt(i); 3266 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId); 3267 if (VDBG) { 3268 log(" checking request " + request + ", currentNetwork = " + 3269 (currentNetwork != null ? currentNetwork.name() : "null")); 3270 } 3271 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) { 3272 mNetworkForRequestId.remove(request.requestId); 3273 sendUpdatedScoreToFactories(request, 0); 3274 NetworkAgentInfo alternative = null; 3275 for (Map.Entry entry : mNetworkAgentInfos.entrySet()) { 3276 NetworkAgentInfo existing = (NetworkAgentInfo)entry.getValue(); 3277 if (existing.networkInfo.isConnected() && 3278 request.networkCapabilities.satisfiedByNetworkCapabilities( 3279 existing.networkCapabilities) && 3280 (alternative == null || 3281 alternative.currentScore < existing.currentScore)) { 3282 alternative = existing; 3283 } 3284 } 3285 if (alternative != null && !toActivate.contains(alternative)) { 3286 toActivate.add(alternative); 3287 } 3288 } 3289 } 3290 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 3291 removeDataActivityTracking(nai); 3292 mActiveDefaultNetwork = ConnectivityManager.TYPE_NONE; 3293 } 3294 for (NetworkAgentInfo networkToActivate : toActivate) { 3295 networkToActivate.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 3296 } 3297 } 3298 } 3299 3300 private void handleRegisterNetworkRequest(Message msg) { 3301 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj); 3302 final NetworkCapabilities newCap = nri.request.networkCapabilities; 3303 int score = 0; 3304 3305 // Check for the best currently alive network that satisfies this request 3306 NetworkAgentInfo bestNetwork = null; 3307 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) { 3308 if (VDBG) log("handleRegisterNetworkRequest checking " + network.name()); 3309 if (newCap.satisfiedByNetworkCapabilities(network.networkCapabilities)) { 3310 if (VDBG) log("apparently satisfied. currentScore=" + network.currentScore); 3311 if ((bestNetwork == null) || bestNetwork.currentScore < network.currentScore) { 3312 bestNetwork = network; 3313 } 3314 } 3315 } 3316 if (bestNetwork != null) { 3317 if (VDBG) log("using " + bestNetwork.name()); 3318 bestNetwork.addRequest(nri.request); 3319 mNetworkForRequestId.put(nri.request.requestId, bestNetwork); 3320 int legacyType = nri.request.legacyType; 3321 if (legacyType != TYPE_NONE) { 3322 mLegacyTypeTracker.add(legacyType, bestNetwork); 3323 } 3324 notifyNetworkCallback(bestNetwork, nri); 3325 score = bestNetwork.currentScore; 3326 } 3327 mNetworkRequests.put(nri.request, nri); 3328 if (msg.what == EVENT_REGISTER_NETWORK_REQUEST) { 3329 if (DBG) log("sending new NetworkRequest to factories"); 3330 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 3331 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 3332 0, nri.request); 3333 } 3334 } 3335 } 3336 3337 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) { 3338 NetworkRequestInfo nri = mNetworkRequests.get(request); 3339 if (nri != null) { 3340 if (nri.mUid != callingUid) { 3341 if (DBG) log("Attempt to release unowned NetworkRequest " + request); 3342 return; 3343 } 3344 if (DBG) log("releasing NetworkRequest " + request); 3345 mNetworkRequests.remove(request); 3346 // tell the network currently servicing this that it's no longer interested 3347 NetworkAgentInfo affectedNetwork = mNetworkForRequestId.get(nri.request.requestId); 3348 if (affectedNetwork != null) { 3349 mNetworkForRequestId.remove(nri.request.requestId); 3350 affectedNetwork.networkRequests.remove(nri.request.requestId); 3351 if (VDBG) { 3352 log(" Removing from current network " + affectedNetwork.name() + ", leaving " + 3353 affectedNetwork.networkRequests.size() + " requests."); 3354 } 3355 } 3356 3357 if (nri.isRequest) { 3358 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 3359 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST, 3360 nri.request); 3361 } 3362 3363 if (affectedNetwork != null) { 3364 // check if this network still has live requests - otherwise, tear down 3365 // TODO - probably push this to the NF/NA 3366 boolean keep = false; 3367 for (int i = 0; i < affectedNetwork.networkRequests.size(); i++) { 3368 NetworkRequest r = affectedNetwork.networkRequests.valueAt(i); 3369 if (mNetworkRequests.get(r).isRequest) { 3370 keep = true; 3371 break; 3372 } 3373 } 3374 if (keep == false) { 3375 if (DBG) log("no live requests for " + affectedNetwork.name() + 3376 "; disconnecting"); 3377 affectedNetwork.asyncChannel.disconnect(); 3378 } 3379 } 3380 } 3381 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED); 3382 } 3383 } 3384 3385 private class InternalHandler extends Handler { 3386 public InternalHandler(Looper looper) { 3387 super(looper); 3388 } 3389 3390 @Override 3391 public void handleMessage(Message msg) { 3392 NetworkInfo info; 3393 switch (msg.what) { 3394 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: { 3395 String causedBy = null; 3396 synchronized (ConnectivityService.this) { 3397 if (msg.arg1 == mNetTransitionWakeLockSerialNumber && 3398 mNetTransitionWakeLock.isHeld()) { 3399 mNetTransitionWakeLock.release(); 3400 causedBy = mNetTransitionWakeLockCausedBy; 3401 } 3402 } 3403 if (causedBy != null) { 3404 log("NetTransition Wakelock for " + causedBy + " released by timeout"); 3405 } 3406 break; 3407 } 3408 case EVENT_RESTORE_DEFAULT_NETWORK: { 3409 FeatureUser u = (FeatureUser)msg.obj; 3410 u.expire(); 3411 break; 3412 } 3413 case EVENT_INET_CONDITION_CHANGE: { 3414 int netType = msg.arg1; 3415 int condition = msg.arg2; 3416 handleInetConditionChange(netType, condition); 3417 break; 3418 } 3419 case EVENT_INET_CONDITION_HOLD_END: { 3420 int netType = msg.arg1; 3421 int sequence = msg.arg2; 3422 handleInetConditionHoldEnd(netType, sequence); 3423 break; 3424 } 3425 case EVENT_APPLY_GLOBAL_HTTP_PROXY: { 3426 handleDeprecatedGlobalHttpProxy(); 3427 break; 3428 } 3429 case EVENT_SET_DEPENDENCY_MET: { 3430 boolean met = (msg.arg1 == ENABLED); 3431 handleSetDependencyMet(msg.arg2, met); 3432 break; 3433 } 3434 case EVENT_SEND_STICKY_BROADCAST_INTENT: { 3435 Intent intent = (Intent)msg.obj; 3436 sendStickyBroadcast(intent); 3437 break; 3438 } 3439 case EVENT_SET_POLICY_DATA_ENABLE: { 3440 final int networkType = msg.arg1; 3441 final boolean enabled = msg.arg2 == ENABLED; 3442 handleSetPolicyDataEnable(networkType, enabled); 3443 break; 3444 } 3445 case EVENT_VPN_STATE_CHANGED: { 3446 if (mLockdownTracker != null) { 3447 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj); 3448 } 3449 break; 3450 } 3451 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: { 3452 int tag = mEnableFailFastMobileDataTag.get(); 3453 if (msg.arg1 == tag) { 3454 MobileDataStateTracker mobileDst = 3455 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 3456 if (mobileDst != null) { 3457 mobileDst.setEnableFailFastMobileData(msg.arg2); 3458 } 3459 } else { 3460 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1 3461 + " != tag:" + tag); 3462 } 3463 break; 3464 } 3465 case EVENT_SAMPLE_INTERVAL_ELAPSED: { 3466 handleNetworkSamplingTimeout(); 3467 break; 3468 } 3469 case EVENT_PROXY_HAS_CHANGED: { 3470 handleApplyDefaultProxy((ProxyInfo)msg.obj); 3471 break; 3472 } 3473 case EVENT_REGISTER_NETWORK_FACTORY: { 3474 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj); 3475 break; 3476 } 3477 case EVENT_UNREGISTER_NETWORK_FACTORY: { 3478 handleUnregisterNetworkFactory((Messenger)msg.obj); 3479 break; 3480 } 3481 case EVENT_REGISTER_NETWORK_AGENT: { 3482 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj); 3483 break; 3484 } 3485 case EVENT_REGISTER_NETWORK_REQUEST: 3486 case EVENT_REGISTER_NETWORK_LISTENER: { 3487 handleRegisterNetworkRequest(msg); 3488 break; 3489 } 3490 case EVENT_RELEASE_NETWORK_REQUEST: { 3491 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1); 3492 break; 3493 } 3494 } 3495 } 3496 } 3497 3498 // javadoc from interface 3499 public int tether(String iface) { 3500 enforceTetherChangePermission(); 3501 3502 if (isTetheringSupported()) { 3503 return mTethering.tether(iface); 3504 } else { 3505 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3506 } 3507 } 3508 3509 // javadoc from interface 3510 public int untether(String iface) { 3511 enforceTetherChangePermission(); 3512 3513 if (isTetheringSupported()) { 3514 return mTethering.untether(iface); 3515 } else { 3516 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3517 } 3518 } 3519 3520 // javadoc from interface 3521 public int getLastTetherError(String iface) { 3522 enforceTetherAccessPermission(); 3523 3524 if (isTetheringSupported()) { 3525 return mTethering.getLastTetherError(iface); 3526 } else { 3527 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3528 } 3529 } 3530 3531 // TODO - proper iface API for selection by property, inspection, etc 3532 public String[] getTetherableUsbRegexs() { 3533 enforceTetherAccessPermission(); 3534 if (isTetheringSupported()) { 3535 return mTethering.getTetherableUsbRegexs(); 3536 } else { 3537 return new String[0]; 3538 } 3539 } 3540 3541 public String[] getTetherableWifiRegexs() { 3542 enforceTetherAccessPermission(); 3543 if (isTetheringSupported()) { 3544 return mTethering.getTetherableWifiRegexs(); 3545 } else { 3546 return new String[0]; 3547 } 3548 } 3549 3550 public String[] getTetherableBluetoothRegexs() { 3551 enforceTetherAccessPermission(); 3552 if (isTetheringSupported()) { 3553 return mTethering.getTetherableBluetoothRegexs(); 3554 } else { 3555 return new String[0]; 3556 } 3557 } 3558 3559 public int setUsbTethering(boolean enable) { 3560 enforceTetherChangePermission(); 3561 if (isTetheringSupported()) { 3562 return mTethering.setUsbTethering(enable); 3563 } else { 3564 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3565 } 3566 } 3567 3568 // TODO - move iface listing, queries, etc to new module 3569 // javadoc from interface 3570 public String[] getTetherableIfaces() { 3571 enforceTetherAccessPermission(); 3572 return mTethering.getTetherableIfaces(); 3573 } 3574 3575 public String[] getTetheredIfaces() { 3576 enforceTetherAccessPermission(); 3577 return mTethering.getTetheredIfaces(); 3578 } 3579 3580 public String[] getTetheringErroredIfaces() { 3581 enforceTetherAccessPermission(); 3582 return mTethering.getErroredIfaces(); 3583 } 3584 3585 // if ro.tether.denied = true we default to no tethering 3586 // gservices could set the secure setting to 1 though to enable it on a build where it 3587 // had previously been turned off. 3588 public boolean isTetheringSupported() { 3589 enforceTetherAccessPermission(); 3590 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 3591 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(), 3592 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0); 3593 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 || 3594 mTethering.getTetherableWifiRegexs().length != 0 || 3595 mTethering.getTetherableBluetoothRegexs().length != 0) && 3596 mTethering.getUpstreamIfaceTypes().length != 0); 3597 } 3598 3599 // An API NetworkStateTrackers can call when they lose their network. 3600 // This will automatically be cleared after X seconds or a network becomes CONNECTED, 3601 // whichever happens first. The timer is started by the first caller and not 3602 // restarted by subsequent callers. 3603 public void requestNetworkTransitionWakelock(String forWhom) { 3604 enforceConnectivityInternalPermission(); 3605 synchronized (this) { 3606 if (mNetTransitionWakeLock.isHeld()) return; 3607 mNetTransitionWakeLockSerialNumber++; 3608 mNetTransitionWakeLock.acquire(); 3609 mNetTransitionWakeLockCausedBy = forWhom; 3610 } 3611 mHandler.sendMessageDelayed(mHandler.obtainMessage( 3612 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 3613 mNetTransitionWakeLockSerialNumber, 0), 3614 mNetTransitionWakeLockTimeout); 3615 return; 3616 } 3617 3618 // 100 percent is full good, 0 is full bad. 3619 public void reportInetCondition(int networkType, int percentage) { 3620 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")"); 3621 mContext.enforceCallingOrSelfPermission( 3622 android.Manifest.permission.STATUS_BAR, 3623 "ConnectivityService"); 3624 3625 if (DBG) { 3626 int pid = getCallingPid(); 3627 int uid = getCallingUid(); 3628 String s = pid + "(" + uid + ") reports inet is " + 3629 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " + 3630 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime(); 3631 mInetLog.add(s); 3632 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) { 3633 mInetLog.remove(0); 3634 } 3635 } 3636 mHandler.sendMessage(mHandler.obtainMessage( 3637 EVENT_INET_CONDITION_CHANGE, networkType, percentage)); 3638 } 3639 3640 public void reportBadNetwork(Network network) { 3641 //TODO 3642 } 3643 3644 private void handleInetConditionChange(int netType, int condition) { 3645 if (mActiveDefaultNetwork == -1) { 3646 if (DBG) log("handleInetConditionChange: no active default network - ignore"); 3647 return; 3648 } 3649 if (mActiveDefaultNetwork != netType) { 3650 if (DBG) log("handleInetConditionChange: net=" + netType + 3651 " != default=" + mActiveDefaultNetwork + " - ignore"); 3652 return; 3653 } 3654 if (VDBG) { 3655 log("handleInetConditionChange: net=" + 3656 netType + ", condition=" + condition + 3657 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork); 3658 } 3659 mDefaultInetCondition = condition; 3660 int delay; 3661 if (mInetConditionChangeInFlight == false) { 3662 if (VDBG) log("handleInetConditionChange: starting a change hold"); 3663 // setup a new hold to debounce this 3664 if (mDefaultInetCondition > 50) { 3665 delay = Settings.Global.getInt(mContext.getContentResolver(), 3666 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500); 3667 } else { 3668 delay = Settings.Global.getInt(mContext.getContentResolver(), 3669 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000); 3670 } 3671 mInetConditionChangeInFlight = true; 3672 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END, 3673 mActiveDefaultNetwork, mDefaultConnectionSequence), delay); 3674 } else { 3675 // we've set the new condition, when this hold ends that will get picked up 3676 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt"); 3677 } 3678 } 3679 3680 private void handleInetConditionHoldEnd(int netType, int sequence) { 3681 if (DBG) { 3682 log("handleInetConditionHoldEnd: net=" + netType + 3683 ", condition=" + mDefaultInetCondition + 3684 ", published condition=" + mDefaultInetConditionPublished); 3685 } 3686 mInetConditionChangeInFlight = false; 3687 3688 if (mActiveDefaultNetwork == -1) { 3689 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring"); 3690 return; 3691 } 3692 if (mDefaultConnectionSequence != sequence) { 3693 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring"); 3694 return; 3695 } 3696 // TODO: Figure out why this optimization sometimes causes a 3697 // change in mDefaultInetCondition to be missed and the 3698 // UI to not be updated. 3699 //if (mDefaultInetConditionPublished == mDefaultInetCondition) { 3700 // if (DBG) log("no change in condition - aborting"); 3701 // return; 3702 //} 3703 NetworkInfo networkInfo = getNetworkInfoForType(mActiveDefaultNetwork); 3704 if (networkInfo.isConnected() == false) { 3705 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring"); 3706 return; 3707 } 3708 mDefaultInetConditionPublished = mDefaultInetCondition; 3709 sendInetConditionBroadcast(networkInfo); 3710 return; 3711 } 3712 3713 public ProxyInfo getProxy() { 3714 // this information is already available as a world read/writable jvm property 3715 // so this API change wouldn't have a benifit. It also breaks the passing 3716 // of proxy info to all the JVMs. 3717 // enforceAccessPermission(); 3718 synchronized (mProxyLock) { 3719 ProxyInfo ret = mGlobalProxy; 3720 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy; 3721 return ret; 3722 } 3723 } 3724 3725 public void setGlobalProxy(ProxyInfo proxyProperties) { 3726 enforceConnectivityInternalPermission(); 3727 3728 synchronized (mProxyLock) { 3729 if (proxyProperties == mGlobalProxy) return; 3730 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return; 3731 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return; 3732 3733 String host = ""; 3734 int port = 0; 3735 String exclList = ""; 3736 String pacFileUrl = ""; 3737 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) || 3738 (proxyProperties.getPacFileUrl() != null))) { 3739 if (!proxyProperties.isValid()) { 3740 if (DBG) 3741 log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3742 return; 3743 } 3744 mGlobalProxy = new ProxyInfo(proxyProperties); 3745 host = mGlobalProxy.getHost(); 3746 port = mGlobalProxy.getPort(); 3747 exclList = mGlobalProxy.getExclusionListAsString(); 3748 if (proxyProperties.getPacFileUrl() != null) { 3749 pacFileUrl = proxyProperties.getPacFileUrl().toString(); 3750 } 3751 } else { 3752 mGlobalProxy = null; 3753 } 3754 ContentResolver res = mContext.getContentResolver(); 3755 final long token = Binder.clearCallingIdentity(); 3756 try { 3757 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host); 3758 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port); 3759 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 3760 exclList); 3761 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl); 3762 } finally { 3763 Binder.restoreCallingIdentity(token); 3764 } 3765 } 3766 3767 if (mGlobalProxy == null) { 3768 proxyProperties = mDefaultProxy; 3769 } 3770 sendProxyBroadcast(proxyProperties); 3771 } 3772 3773 private void loadGlobalProxy() { 3774 ContentResolver res = mContext.getContentResolver(); 3775 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST); 3776 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0); 3777 String exclList = Settings.Global.getString(res, 3778 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST); 3779 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC); 3780 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) { 3781 ProxyInfo proxyProperties; 3782 if (!TextUtils.isEmpty(pacFileUrl)) { 3783 proxyProperties = new ProxyInfo(pacFileUrl); 3784 } else { 3785 proxyProperties = new ProxyInfo(host, port, exclList); 3786 } 3787 if (!proxyProperties.isValid()) { 3788 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3789 return; 3790 } 3791 3792 synchronized (mProxyLock) { 3793 mGlobalProxy = proxyProperties; 3794 } 3795 } 3796 } 3797 3798 public ProxyInfo getGlobalProxy() { 3799 // this information is already available as a world read/writable jvm property 3800 // so this API change wouldn't have a benifit. It also breaks the passing 3801 // of proxy info to all the JVMs. 3802 // enforceAccessPermission(); 3803 synchronized (mProxyLock) { 3804 return mGlobalProxy; 3805 } 3806 } 3807 3808 private void handleApplyDefaultProxy(ProxyInfo proxy) { 3809 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 3810 && (proxy.getPacFileUrl() == null)) { 3811 proxy = null; 3812 } 3813 synchronized (mProxyLock) { 3814 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return; 3815 if (mDefaultProxy == proxy) return; // catches repeated nulls 3816 if (proxy != null && !proxy.isValid()) { 3817 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString()); 3818 return; 3819 } 3820 3821 // This call could be coming from the PacManager, containing the port of the local 3822 // proxy. If this new proxy matches the global proxy then copy this proxy to the 3823 // global (to get the correct local port), and send a broadcast. 3824 // TODO: Switch PacManager to have its own message to send back rather than 3825 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy. 3826 if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null) 3827 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) { 3828 mGlobalProxy = proxy; 3829 sendProxyBroadcast(mGlobalProxy); 3830 return; 3831 } 3832 mDefaultProxy = proxy; 3833 3834 if (mGlobalProxy != null) return; 3835 if (!mDefaultProxyDisabled) { 3836 sendProxyBroadcast(proxy); 3837 } 3838 } 3839 } 3840 3841 private void handleDeprecatedGlobalHttpProxy() { 3842 String proxy = Settings.Global.getString(mContext.getContentResolver(), 3843 Settings.Global.HTTP_PROXY); 3844 if (!TextUtils.isEmpty(proxy)) { 3845 String data[] = proxy.split(":"); 3846 if (data.length == 0) { 3847 return; 3848 } 3849 3850 String proxyHost = data[0]; 3851 int proxyPort = 8080; 3852 if (data.length > 1) { 3853 try { 3854 proxyPort = Integer.parseInt(data[1]); 3855 } catch (NumberFormatException e) { 3856 return; 3857 } 3858 } 3859 ProxyInfo p = new ProxyInfo(data[0], proxyPort, ""); 3860 setGlobalProxy(p); 3861 } 3862 } 3863 3864 private void sendProxyBroadcast(ProxyInfo proxy) { 3865 if (proxy == null) proxy = new ProxyInfo("", 0, ""); 3866 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return; 3867 if (DBG) log("sending Proxy Broadcast for " + proxy); 3868 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); 3869 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 3870 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3871 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy); 3872 final long ident = Binder.clearCallingIdentity(); 3873 try { 3874 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 3875 } finally { 3876 Binder.restoreCallingIdentity(ident); 3877 } 3878 } 3879 3880 private static class SettingsObserver extends ContentObserver { 3881 private int mWhat; 3882 private Handler mHandler; 3883 SettingsObserver(Handler handler, int what) { 3884 super(handler); 3885 mHandler = handler; 3886 mWhat = what; 3887 } 3888 3889 void observe(Context context) { 3890 ContentResolver resolver = context.getContentResolver(); 3891 resolver.registerContentObserver(Settings.Global.getUriFor( 3892 Settings.Global.HTTP_PROXY), false, this); 3893 } 3894 3895 @Override 3896 public void onChange(boolean selfChange) { 3897 mHandler.obtainMessage(mWhat).sendToTarget(); 3898 } 3899 } 3900 3901 private static void log(String s) { 3902 Slog.d(TAG, s); 3903 } 3904 3905 private static void loge(String s) { 3906 Slog.e(TAG, s); 3907 } 3908 3909 int convertFeatureToNetworkType(int networkType, String feature) { 3910 int usedNetworkType = networkType; 3911 3912 if(networkType == ConnectivityManager.TYPE_MOBILE) { 3913 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) { 3914 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS; 3915 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) { 3916 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL; 3917 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) || 3918 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) { 3919 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN; 3920 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) { 3921 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI; 3922 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) { 3923 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA; 3924 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) { 3925 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS; 3926 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) { 3927 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS; 3928 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_EMERGENCY)) { 3929 usedNetworkType = ConnectivityManager.TYPE_MOBILE_EMERGENCY; 3930 } else { 3931 Slog.e(TAG, "Can't match any mobile netTracker!"); 3932 } 3933 } else if (networkType == ConnectivityManager.TYPE_WIFI) { 3934 if (TextUtils.equals(feature, "p2p")) { 3935 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P; 3936 } else { 3937 Slog.e(TAG, "Can't match any wifi netTracker!"); 3938 } 3939 } else { 3940 Slog.e(TAG, "Unexpected network type"); 3941 } 3942 return usedNetworkType; 3943 } 3944 3945 private static <T> T checkNotNull(T value, String message) { 3946 if (value == null) { 3947 throw new NullPointerException(message); 3948 } 3949 return value; 3950 } 3951 3952 /** 3953 * Protect a socket from VPN routing rules. This method is used by 3954 * VpnBuilder and not available in ConnectivityManager. Permissions 3955 * are checked in Vpn class. 3956 * @hide 3957 */ 3958 @Override 3959 public boolean protectVpn(ParcelFileDescriptor socket) { 3960 throwIfLockdownEnabled(); 3961 try { 3962 int type = mActiveDefaultNetwork; 3963 int user = UserHandle.getUserId(Binder.getCallingUid()); 3964 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) { 3965 synchronized(mVpns) { 3966 mVpns.get(user).protect(socket); 3967 } 3968 return true; 3969 } 3970 } catch (Exception e) { 3971 // ignore 3972 } finally { 3973 try { 3974 socket.close(); 3975 } catch (Exception e) { 3976 // ignore 3977 } 3978 } 3979 return false; 3980 } 3981 3982 /** 3983 * Prepare for a VPN application. This method is used by VpnDialogs 3984 * and not available in ConnectivityManager. Permissions are checked 3985 * in Vpn class. 3986 * @hide 3987 */ 3988 @Override 3989 public boolean prepareVpn(String oldPackage, String newPackage) { 3990 throwIfLockdownEnabled(); 3991 int user = UserHandle.getUserId(Binder.getCallingUid()); 3992 synchronized(mVpns) { 3993 return mVpns.get(user).prepare(oldPackage, newPackage); 3994 } 3995 } 3996 3997 @Override 3998 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) { 3999 enforceMarkNetworkSocketPermission(); 4000 final long token = Binder.clearCallingIdentity(); 4001 try { 4002 int mark = mNetd.getMarkForUid(uid); 4003 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues 4004 if (mark == -1) { 4005 mark = 0; 4006 } 4007 NetworkUtils.markSocket(socket.getFd(), mark); 4008 } catch (RemoteException e) { 4009 } finally { 4010 Binder.restoreCallingIdentity(token); 4011 } 4012 } 4013 4014 /** 4015 * Configure a TUN interface and return its file descriptor. Parameters 4016 * are encoded and opaque to this class. This method is used by VpnBuilder 4017 * and not available in ConnectivityManager. Permissions are checked in 4018 * Vpn class. 4019 * @hide 4020 */ 4021 @Override 4022 public ParcelFileDescriptor establishVpn(VpnConfig config) { 4023 throwIfLockdownEnabled(); 4024 int user = UserHandle.getUserId(Binder.getCallingUid()); 4025 synchronized(mVpns) { 4026 return mVpns.get(user).establish(config); 4027 } 4028 } 4029 4030 /** 4031 * Start legacy VPN, controlling native daemons as needed. Creates a 4032 * secondary thread to perform connection work, returning quickly. 4033 */ 4034 @Override 4035 public void startLegacyVpn(VpnProfile profile) { 4036 throwIfLockdownEnabled(); 4037 final LinkProperties egress = getActiveLinkProperties(); 4038 if (egress == null) { 4039 throw new IllegalStateException("Missing active network connection"); 4040 } 4041 int user = UserHandle.getUserId(Binder.getCallingUid()); 4042 synchronized(mVpns) { 4043 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress); 4044 } 4045 } 4046 4047 /** 4048 * Return the information of the ongoing legacy VPN. This method is used 4049 * by VpnSettings and not available in ConnectivityManager. Permissions 4050 * are checked in Vpn class. 4051 * @hide 4052 */ 4053 @Override 4054 public LegacyVpnInfo getLegacyVpnInfo() { 4055 throwIfLockdownEnabled(); 4056 int user = UserHandle.getUserId(Binder.getCallingUid()); 4057 synchronized(mVpns) { 4058 return mVpns.get(user).getLegacyVpnInfo(); 4059 } 4060 } 4061 4062 /** 4063 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and 4064 * not available in ConnectivityManager. 4065 * Permissions are checked in Vpn class. 4066 * @hide 4067 */ 4068 @Override 4069 public VpnConfig getVpnConfig() { 4070 int user = UserHandle.getUserId(Binder.getCallingUid()); 4071 synchronized(mVpns) { 4072 return mVpns.get(user).getVpnConfig(); 4073 } 4074 } 4075 4076 /** 4077 * Callback for VPN subsystem. Currently VPN is not adapted to the service 4078 * through NetworkStateTracker since it works differently. For example, it 4079 * needs to override DNS servers but never takes the default routes. It 4080 * relies on another data network, and it could keep existing connections 4081 * alive after reconnecting, switching between networks, or even resuming 4082 * from deep sleep. Calls from applications should be done synchronously 4083 * to avoid race conditions. As these are all hidden APIs, refactoring can 4084 * be done whenever a better abstraction is developed. 4085 */ 4086 public class VpnCallback { 4087 private VpnCallback() { 4088 } 4089 4090 public void onStateChanged(NetworkInfo info) { 4091 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget(); 4092 } 4093 4094 public void override(String iface, List<String> dnsServers, List<String> searchDomains) { 4095 if (dnsServers == null) { 4096 restore(); 4097 return; 4098 } 4099 4100 // Convert DNS servers into addresses. 4101 List<InetAddress> addresses = new ArrayList<InetAddress>(); 4102 for (String address : dnsServers) { 4103 // Double check the addresses and remove invalid ones. 4104 try { 4105 addresses.add(InetAddress.parseNumericAddress(address)); 4106 } catch (Exception e) { 4107 // ignore 4108 } 4109 } 4110 if (addresses.isEmpty()) { 4111 restore(); 4112 return; 4113 } 4114 4115 // Concatenate search domains into a string. 4116 StringBuilder buffer = new StringBuilder(); 4117 if (searchDomains != null) { 4118 for (String domain : searchDomains) { 4119 buffer.append(domain).append(' '); 4120 } 4121 } 4122 String domains = buffer.toString().trim(); 4123 4124 // Apply DNS changes. 4125 synchronized (mDnsLock) { 4126 // TODO: Re-enable this when the netId of the VPN is known. 4127 // updateDnsLocked("VPN", netId, addresses, domains); 4128 } 4129 4130 // Temporarily disable the default proxy (not global). 4131 synchronized (mProxyLock) { 4132 mDefaultProxyDisabled = true; 4133 if (mGlobalProxy == null && mDefaultProxy != null) { 4134 sendProxyBroadcast(null); 4135 } 4136 } 4137 4138 // TODO: support proxy per network. 4139 } 4140 4141 public void restore() { 4142 synchronized (mProxyLock) { 4143 mDefaultProxyDisabled = false; 4144 if (mGlobalProxy == null && mDefaultProxy != null) { 4145 sendProxyBroadcast(mDefaultProxy); 4146 } 4147 } 4148 } 4149 4150 public void protect(ParcelFileDescriptor socket) { 4151 try { 4152 final int mark = mNetd.getMarkForProtect(); 4153 NetworkUtils.markSocket(socket.getFd(), mark); 4154 } catch (RemoteException e) { 4155 } 4156 } 4157 4158 public void setRoutes(String interfaze, List<RouteInfo> routes) { 4159 for (RouteInfo route : routes) { 4160 try { 4161 mNetd.setMarkedForwardingRoute(interfaze, route); 4162 } catch (RemoteException e) { 4163 } 4164 } 4165 } 4166 4167 public void setMarkedForwarding(String interfaze) { 4168 try { 4169 mNetd.setMarkedForwarding(interfaze); 4170 } catch (RemoteException e) { 4171 } 4172 } 4173 4174 public void clearMarkedForwarding(String interfaze) { 4175 try { 4176 mNetd.clearMarkedForwarding(interfaze); 4177 } catch (RemoteException e) { 4178 } 4179 } 4180 4181 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) { 4182 int uidStart = uid * UserHandle.PER_USER_RANGE; 4183 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1; 4184 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns); 4185 } 4186 4187 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) { 4188 int uidStart = uid * UserHandle.PER_USER_RANGE; 4189 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1; 4190 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns); 4191 } 4192 4193 public void addUidForwarding(String interfaze, int uidStart, int uidEnd, 4194 boolean forwardDns) { 4195 // TODO: Re-enable this when the netId of the VPN is known. 4196 // try { 4197 // mNetd.setUidRangeRoute(netId, uidStart, uidEnd, forwardDns); 4198 // } catch (RemoteException e) { 4199 // } 4200 4201 } 4202 4203 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd, 4204 boolean forwardDns) { 4205 // TODO: Re-enable this when the netId of the VPN is known. 4206 // try { 4207 // mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd); 4208 // } catch (RemoteException e) { 4209 // } 4210 4211 } 4212 } 4213 4214 @Override 4215 public boolean updateLockdownVpn() { 4216 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 4217 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM"); 4218 return false; 4219 } 4220 4221 // Tear down existing lockdown if profile was removed 4222 mLockdownEnabled = LockdownVpnTracker.isEnabled(); 4223 if (mLockdownEnabled) { 4224 if (!mKeyStore.isUnlocked()) { 4225 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker"); 4226 return false; 4227 } 4228 4229 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN)); 4230 final VpnProfile profile = VpnProfile.decode( 4231 profileName, mKeyStore.get(Credentials.VPN + profileName)); 4232 int user = UserHandle.getUserId(Binder.getCallingUid()); 4233 synchronized(mVpns) { 4234 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user), 4235 profile)); 4236 } 4237 } else { 4238 setLockdownTracker(null); 4239 } 4240 4241 return true; 4242 } 4243 4244 /** 4245 * Internally set new {@link LockdownVpnTracker}, shutting down any existing 4246 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown. 4247 */ 4248 private void setLockdownTracker(LockdownVpnTracker tracker) { 4249 // Shutdown any existing tracker 4250 final LockdownVpnTracker existing = mLockdownTracker; 4251 mLockdownTracker = null; 4252 if (existing != null) { 4253 existing.shutdown(); 4254 } 4255 4256 try { 4257 if (tracker != null) { 4258 mNetd.setFirewallEnabled(true); 4259 mNetd.setFirewallInterfaceRule("lo", true); 4260 mLockdownTracker = tracker; 4261 mLockdownTracker.init(); 4262 } else { 4263 mNetd.setFirewallEnabled(false); 4264 } 4265 } catch (RemoteException e) { 4266 // ignored; NMS lives inside system_server 4267 } 4268 } 4269 4270 private void throwIfLockdownEnabled() { 4271 if (mLockdownEnabled) { 4272 throw new IllegalStateException("Unavailable in lockdown mode"); 4273 } 4274 } 4275 4276 public void supplyMessenger(int networkType, Messenger messenger) { 4277 enforceConnectivityInternalPermission(); 4278 4279 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) { 4280 mNetTrackers[networkType].supplyMessenger(messenger); 4281 } 4282 } 4283 4284 public int findConnectionTypeForIface(String iface) { 4285 enforceConnectivityInternalPermission(); 4286 4287 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE; 4288 for (NetworkStateTracker tracker : mNetTrackers) { 4289 if (tracker != null) { 4290 LinkProperties lp = tracker.getLinkProperties(); 4291 if (lp != null && iface.equals(lp.getInterfaceName())) { 4292 return tracker.getNetworkInfo().getType(); 4293 } 4294 } 4295 } 4296 return ConnectivityManager.TYPE_NONE; 4297 } 4298 4299 /** 4300 * Have mobile data fail fast if enabled. 4301 * 4302 * @param enabled DctConstants.ENABLED/DISABLED 4303 */ 4304 private void setEnableFailFastMobileData(int enabled) { 4305 int tag; 4306 4307 if (enabled == DctConstants.ENABLED) { 4308 tag = mEnableFailFastMobileDataTag.incrementAndGet(); 4309 } else { 4310 tag = mEnableFailFastMobileDataTag.get(); 4311 } 4312 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag, 4313 enabled)); 4314 } 4315 4316 private boolean isMobileDataStateTrackerReady() { 4317 MobileDataStateTracker mdst = 4318 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4319 return (mdst != null) && (mdst.isReady()); 4320 } 4321 4322 /** 4323 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE) 4324 */ 4325 4326 /** 4327 * No connection was possible to the network. 4328 * This is NOT a warm sim. 4329 */ 4330 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0; 4331 4332 /** 4333 * A connection was made to the internet, all is well. 4334 * This is NOT a warm sim. 4335 */ 4336 private static final int CMP_RESULT_CODE_CONNECTABLE = 1; 4337 4338 /** 4339 * A connection was made but no dns server was available to resolve a name to address. 4340 * This is NOT a warm sim since provisioning network is supported. 4341 */ 4342 private static final int CMP_RESULT_CODE_NO_DNS = 2; 4343 4344 /** 4345 * A connection was made but could not open a TCP connection. 4346 * This is NOT a warm sim since provisioning network is supported. 4347 */ 4348 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3; 4349 4350 /** 4351 * A connection was made but there was a redirection, we appear to be in walled garden. 4352 * This is an indication of a warm sim on a mobile network such as T-Mobile. 4353 */ 4354 private static final int CMP_RESULT_CODE_REDIRECTED = 4; 4355 4356 /** 4357 * The mobile network is a provisioning network. 4358 * This is an indication of a warm sim on a mobile network such as AT&T. 4359 */ 4360 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5; 4361 4362 /** 4363 * The mobile network is provisioning 4364 */ 4365 private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6; 4366 4367 private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false); 4368 private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false); 4369 4370 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false); 4371 4372 @Override 4373 public int checkMobileProvisioning(int suggestedTimeOutMs) { 4374 int timeOutMs = -1; 4375 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs); 4376 enforceConnectivityInternalPermission(); 4377 4378 final long token = Binder.clearCallingIdentity(); 4379 try { 4380 timeOutMs = suggestedTimeOutMs; 4381 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) { 4382 timeOutMs = CheckMp.MAX_TIMEOUT_MS; 4383 } 4384 4385 // Check that mobile networks are supported 4386 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE) 4387 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) { 4388 if (DBG) log("checkMobileProvisioning: X no mobile network"); 4389 return timeOutMs; 4390 } 4391 4392 // If we're already checking don't do it again 4393 // TODO: Add a queue of results... 4394 if (mIsCheckingMobileProvisioning.getAndSet(true)) { 4395 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment"); 4396 return timeOutMs; 4397 } 4398 4399 // Start off with mobile notification off 4400 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null); 4401 4402 CheckMp checkMp = new CheckMp(mContext, this); 4403 CheckMp.CallBack cb = new CheckMp.CallBack() { 4404 @Override 4405 void onComplete(Integer result) { 4406 if (DBG) log("CheckMp.onComplete: result=" + result); 4407 NetworkInfo ni = 4408 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo(); 4409 switch(result) { 4410 case CMP_RESULT_CODE_CONNECTABLE: 4411 case CMP_RESULT_CODE_NO_CONNECTION: 4412 case CMP_RESULT_CODE_NO_DNS: 4413 case CMP_RESULT_CODE_NO_TCP_CONNECTION: { 4414 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection"); 4415 break; 4416 } 4417 case CMP_RESULT_CODE_REDIRECTED: { 4418 if (DBG) log("CheckMp.onComplete: warm sim"); 4419 String url = getMobileProvisioningUrl(); 4420 if (TextUtils.isEmpty(url)) { 4421 url = getMobileRedirectedProvisioningUrl(); 4422 } 4423 if (TextUtils.isEmpty(url) == false) { 4424 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url); 4425 setProvNotificationVisible(true, 4426 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(), 4427 url); 4428 } else { 4429 if (DBG) log("CheckMp.onComplete: warm (redirected), no url"); 4430 } 4431 break; 4432 } 4433 case CMP_RESULT_CODE_PROVISIONING_NETWORK: { 4434 String url = getMobileProvisioningUrl(); 4435 if (TextUtils.isEmpty(url) == false) { 4436 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url); 4437 setProvNotificationVisible(true, 4438 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(), 4439 url); 4440 // Mark that we've got a provisioning network and 4441 // Disable Mobile Data until user actually starts provisioning. 4442 mIsProvisioningNetwork.set(true); 4443 MobileDataStateTracker mdst = (MobileDataStateTracker) 4444 mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4445 4446 // Disable radio until user starts provisioning 4447 mdst.setRadio(false); 4448 } else { 4449 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url"); 4450 } 4451 break; 4452 } 4453 case CMP_RESULT_CODE_IS_PROVISIONING: { 4454 // FIXME: Need to know when provisioning is done. Probably we can 4455 // check the completion status if successful we're done if we 4456 // "timedout" or still connected to provisioning APN turn off data? 4457 if (DBG) log("CheckMp.onComplete: provisioning started"); 4458 mIsStartingProvisioning.set(false); 4459 break; 4460 } 4461 default: { 4462 loge("CheckMp.onComplete: ignore unexpected result=" + result); 4463 break; 4464 } 4465 } 4466 mIsCheckingMobileProvisioning.set(false); 4467 } 4468 }; 4469 CheckMp.Params params = 4470 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb); 4471 if (DBG) log("checkMobileProvisioning: params=" + params); 4472 // TODO: Reenable when calls to the now defunct 4473 // MobileDataStateTracker.isProvisioningNetwork() are removed. 4474 // This code should be moved to the Telephony code. 4475 // checkMp.execute(params); 4476 } finally { 4477 Binder.restoreCallingIdentity(token); 4478 if (DBG) log("checkMobileProvisioning: X"); 4479 } 4480 return timeOutMs; 4481 } 4482 4483 static class CheckMp extends 4484 AsyncTask<CheckMp.Params, Void, Integer> { 4485 private static final String CHECKMP_TAG = "CheckMp"; 4486 4487 // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures 4488 private static boolean mTestingFailures; 4489 4490 // Choosing 4 loops as half of them will use HTTPS and the other half HTTP 4491 private static final int MAX_LOOPS = 4; 4492 4493 // Number of milli-seconds to complete all of the retires 4494 public static final int MAX_TIMEOUT_MS = 60000; 4495 4496 // The socket should retry only 5 seconds, the default is longer 4497 private static final int SOCKET_TIMEOUT_MS = 5000; 4498 4499 // Sleep time for network errors 4500 private static final int NET_ERROR_SLEEP_SEC = 3; 4501 4502 // Sleep time for network route establishment 4503 private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3; 4504 4505 // Short sleep time for polling :( 4506 private static final int POLLING_SLEEP_SEC = 1; 4507 4508 private Context mContext; 4509 private ConnectivityService mCs; 4510 private TelephonyManager mTm; 4511 private Params mParams; 4512 4513 /** 4514 * Parameters for AsyncTask.execute 4515 */ 4516 static class Params { 4517 private String mUrl; 4518 private long mTimeOutMs; 4519 private CallBack mCb; 4520 4521 Params(String url, long timeOutMs, CallBack cb) { 4522 mUrl = url; 4523 mTimeOutMs = timeOutMs; 4524 mCb = cb; 4525 } 4526 4527 @Override 4528 public String toString() { 4529 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}"; 4530 } 4531 } 4532 4533 // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be 4534 // issued by name or ip address, for Google its by name so when we construct 4535 // this HostnameVerifier we'll pass the original Uri and use it to verify 4536 // the host. If the host name in the original uril fails we'll test the 4537 // hostname parameter just incase things change. 4538 static class CheckMpHostnameVerifier implements HostnameVerifier { 4539 Uri mOrgUri; 4540 4541 CheckMpHostnameVerifier(Uri orgUri) { 4542 mOrgUri = orgUri; 4543 } 4544 4545 @Override 4546 public boolean verify(String hostname, SSLSession session) { 4547 HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); 4548 String orgUriHost = mOrgUri.getHost(); 4549 boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session); 4550 if (DBG) { 4551 log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname 4552 + " orgUriHost=" + orgUriHost); 4553 } 4554 return retVal; 4555 } 4556 } 4557 4558 /** 4559 * The call back object passed in Params. onComplete will be called 4560 * on the main thread. 4561 */ 4562 abstract static class CallBack { 4563 // Called on the main thread. 4564 abstract void onComplete(Integer result); 4565 } 4566 4567 public CheckMp(Context context, ConnectivityService cs) { 4568 if (Build.IS_DEBUGGABLE) { 4569 mTestingFailures = 4570 SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1; 4571 } else { 4572 mTestingFailures = false; 4573 } 4574 4575 mContext = context; 4576 mCs = cs; 4577 4578 // Setup access to TelephonyService we'll be using. 4579 mTm = (TelephonyManager) mContext.getSystemService( 4580 Context.TELEPHONY_SERVICE); 4581 } 4582 4583 /** 4584 * Get the default url to use for the test. 4585 */ 4586 public String getDefaultUrl() { 4587 // See http://go/clientsdns for usage approval 4588 String server = Settings.Global.getString(mContext.getContentResolver(), 4589 Settings.Global.CAPTIVE_PORTAL_SERVER); 4590 if (server == null) { 4591 server = "clients3.google.com"; 4592 } 4593 return "http://" + server + "/generate_204"; 4594 } 4595 4596 /** 4597 * Detect if its possible to connect to the http url. DNS based detection techniques 4598 * do not work at all hotspots. The best way to check is to perform a request to 4599 * a known address that fetches the data we expect. 4600 */ 4601 private synchronized Integer isMobileOk(Params params) { 4602 Integer result = CMP_RESULT_CODE_NO_CONNECTION; 4603 Uri orgUri = Uri.parse(params.mUrl); 4604 Random rand = new Random(); 4605 mParams = params; 4606 4607 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) { 4608 result = CMP_RESULT_CODE_NO_CONNECTION; 4609 log("isMobileOk: X not mobile capable result=" + result); 4610 return result; 4611 } 4612 4613 if (mCs.mIsStartingProvisioning.get()) { 4614 result = CMP_RESULT_CODE_IS_PROVISIONING; 4615 log("isMobileOk: X is provisioning result=" + result); 4616 return result; 4617 } 4618 4619 // See if we've already determined we've got a provisioning connection, 4620 // if so we don't need to do anything active. 4621 MobileDataStateTracker mdstDefault = (MobileDataStateTracker) 4622 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4623 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork(); 4624 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning); 4625 4626 MobileDataStateTracker mdstHipri = (MobileDataStateTracker) 4627 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4628 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork(); 4629 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning); 4630 4631 if (isDefaultProvisioning || isHipriProvisioning) { 4632 result = CMP_RESULT_CODE_PROVISIONING_NETWORK; 4633 log("isMobileOk: X default || hipri is provisioning result=" + result); 4634 return result; 4635 } 4636 4637 try { 4638 // Continue trying to connect until time has run out 4639 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs; 4640 4641 if (!mCs.isMobileDataStateTrackerReady()) { 4642 // Wait for MobileDataStateTracker to be ready. 4643 if (DBG) log("isMobileOk: mdst is not ready"); 4644 while(SystemClock.elapsedRealtime() < endTime) { 4645 if (mCs.isMobileDataStateTrackerReady()) { 4646 // Enable fail fast as we'll do retries here and use a 4647 // hipri connection so the default connection stays active. 4648 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data"); 4649 mCs.setEnableFailFastMobileData(DctConstants.ENABLED); 4650 break; 4651 } 4652 sleep(POLLING_SLEEP_SEC); 4653 } 4654 } 4655 4656 log("isMobileOk: start hipri url=" + params.mUrl); 4657 4658 // First wait until we can start using hipri 4659 Binder binder = new Binder(); 4660 while(SystemClock.elapsedRealtime() < endTime) { 4661 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, 4662 Phone.FEATURE_ENABLE_HIPRI, binder); 4663 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE) 4664 || (ret == PhoneConstants.APN_REQUEST_STARTED)) { 4665 log("isMobileOk: hipri started"); 4666 break; 4667 } 4668 if (VDBG) log("isMobileOk: hipri not started yet"); 4669 result = CMP_RESULT_CODE_NO_CONNECTION; 4670 sleep(POLLING_SLEEP_SEC); 4671 } 4672 4673 // Continue trying to connect until time has run out 4674 while(SystemClock.elapsedRealtime() < endTime) { 4675 try { 4676 // Wait for hipri to connect. 4677 // TODO: Don't poll and handle situation where hipri fails 4678 // because default is retrying. See b/9569540 4679 NetworkInfo.State state = mCs 4680 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); 4681 if (state != NetworkInfo.State.CONNECTED) { 4682 if (true/*VDBG*/) { 4683 log("isMobileOk: not connected ni=" + 4684 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI)); 4685 } 4686 sleep(POLLING_SLEEP_SEC); 4687 result = CMP_RESULT_CODE_NO_CONNECTION; 4688 continue; 4689 } 4690 4691 // Hipri has started check if this is a provisioning url 4692 MobileDataStateTracker mdst = (MobileDataStateTracker) 4693 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4694 if (mdst.isProvisioningNetwork()) { 4695 result = CMP_RESULT_CODE_PROVISIONING_NETWORK; 4696 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result); 4697 return result; 4698 } else { 4699 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue"); 4700 } 4701 4702 // Get of the addresses associated with the url host. We need to use the 4703 // address otherwise HttpURLConnection object will use the name to get 4704 // the addresses and will try every address but that will bypass the 4705 // route to host we setup and the connection could succeed as the default 4706 // interface might be connected to the internet via wifi or other interface. 4707 InetAddress[] addresses; 4708 try { 4709 addresses = InetAddress.getAllByName(orgUri.getHost()); 4710 } catch (UnknownHostException e) { 4711 result = CMP_RESULT_CODE_NO_DNS; 4712 log("isMobileOk: X UnknownHostException result=" + result); 4713 return result; 4714 } 4715 log("isMobileOk: addresses=" + inetAddressesToString(addresses)); 4716 4717 // Get the type of addresses supported by this link 4718 LinkProperties lp = mCs.getLinkPropertiesForTypeInternal( 4719 ConnectivityManager.TYPE_MOBILE_HIPRI); 4720 boolean linkHasIpv4 = lp.hasIPv4Address(); 4721 boolean linkHasIpv6 = lp.hasGlobalIPv6Address(); 4722 log("isMobileOk: linkHasIpv4=" + linkHasIpv4 4723 + " linkHasIpv6=" + linkHasIpv6); 4724 4725 final ArrayList<InetAddress> validAddresses = 4726 new ArrayList<InetAddress>(addresses.length); 4727 4728 for (InetAddress addr : addresses) { 4729 if (((addr instanceof Inet4Address) && linkHasIpv4) || 4730 ((addr instanceof Inet6Address) && linkHasIpv6)) { 4731 validAddresses.add(addr); 4732 } 4733 } 4734 4735 if (validAddresses.size() == 0) { 4736 return CMP_RESULT_CODE_NO_CONNECTION; 4737 } 4738 4739 int addrTried = 0; 4740 while (true) { 4741 // Loop through at most MAX_LOOPS valid addresses or until 4742 // we run out of time 4743 if (addrTried++ >= MAX_LOOPS) { 4744 log("isMobileOk: too many loops tried - giving up"); 4745 break; 4746 } 4747 if (SystemClock.elapsedRealtime() >= endTime) { 4748 log("isMobileOk: spend too much time - giving up"); 4749 break; 4750 } 4751 4752 InetAddress hostAddr = validAddresses.get(rand.nextInt( 4753 validAddresses.size())); 4754 4755 // Make a route to host so we check the specific interface. 4756 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI, 4757 hostAddr.getAddress(), null)) { 4758 // Wait a short time to be sure the route is established ?? 4759 log("isMobileOk:" 4760 + " wait to establish route to hostAddr=" + hostAddr); 4761 sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC); 4762 } else { 4763 log("isMobileOk:" 4764 + " could not establish route to hostAddr=" + hostAddr); 4765 // Wait a short time before the next attempt 4766 sleep(NET_ERROR_SLEEP_SEC); 4767 continue; 4768 } 4769 4770 // Rewrite the url to have numeric address to use the specific route 4771 // using http for half the attempts and https for the other half. 4772 // Doing https first and http second as on a redirected walled garden 4773 // such as t-mobile uses we get a SocketTimeoutException: "SSL 4774 // handshake timed out" which we declare as 4775 // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by 4776 // having http second we will be using logic used for some time. 4777 URL newUrl; 4778 String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http"; 4779 newUrl = new URL(scheme, hostAddr.getHostAddress(), 4780 orgUri.getPath()); 4781 log("isMobileOk: newUrl=" + newUrl); 4782 4783 HttpURLConnection urlConn = null; 4784 try { 4785 // Open the connection set the request headers and get the response 4786 urlConn = (HttpURLConnection)newUrl.openConnection( 4787 java.net.Proxy.NO_PROXY); 4788 if (scheme.equals("https")) { 4789 ((HttpsURLConnection)urlConn).setHostnameVerifier( 4790 new CheckMpHostnameVerifier(orgUri)); 4791 } 4792 urlConn.setInstanceFollowRedirects(false); 4793 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS); 4794 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS); 4795 urlConn.setUseCaches(false); 4796 urlConn.setAllowUserInteraction(false); 4797 // Set the "Connection" to "Close" as by default "Keep-Alive" 4798 // is used which is useless in this case. 4799 urlConn.setRequestProperty("Connection", "close"); 4800 int responseCode = urlConn.getResponseCode(); 4801 4802 // For debug display the headers 4803 Map<String, List<String>> headers = urlConn.getHeaderFields(); 4804 log("isMobileOk: headers=" + headers); 4805 4806 // Close the connection 4807 urlConn.disconnect(); 4808 urlConn = null; 4809 4810 if (mTestingFailures) { 4811 // Pretend no connection, this tests using http and https 4812 result = CMP_RESULT_CODE_NO_CONNECTION; 4813 log("isMobileOk: TESTING_FAILURES, pretend no connction"); 4814 continue; 4815 } 4816 4817 if (responseCode == 204) { 4818 // Return 4819 result = CMP_RESULT_CODE_CONNECTABLE; 4820 log("isMobileOk: X got expected responseCode=" + responseCode 4821 + " result=" + result); 4822 return result; 4823 } else { 4824 // Retry to be sure this was redirected, we've gotten 4825 // occasions where a server returned 200 even though 4826 // the device didn't have a "warm" sim. 4827 log("isMobileOk: not expected responseCode=" + responseCode); 4828 // TODO - it would be nice in the single-address case to do 4829 // another DNS resolve here, but flushing the cache is a bit 4830 // heavy-handed. 4831 result = CMP_RESULT_CODE_REDIRECTED; 4832 } 4833 } catch (Exception e) { 4834 log("isMobileOk: HttpURLConnection Exception" + e); 4835 result = CMP_RESULT_CODE_NO_TCP_CONNECTION; 4836 if (urlConn != null) { 4837 urlConn.disconnect(); 4838 urlConn = null; 4839 } 4840 sleep(NET_ERROR_SLEEP_SEC); 4841 continue; 4842 } 4843 } 4844 log("isMobileOk: X loops|timed out result=" + result); 4845 return result; 4846 } catch (Exception e) { 4847 log("isMobileOk: Exception e=" + e); 4848 continue; 4849 } 4850 } 4851 log("isMobileOk: timed out"); 4852 } finally { 4853 log("isMobileOk: F stop hipri"); 4854 mCs.setEnableFailFastMobileData(DctConstants.DISABLED); 4855 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, 4856 Phone.FEATURE_ENABLE_HIPRI); 4857 4858 // Wait for hipri to disconnect. 4859 long endTime = SystemClock.elapsedRealtime() + 5000; 4860 4861 while(SystemClock.elapsedRealtime() < endTime) { 4862 NetworkInfo.State state = mCs 4863 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); 4864 if (state != NetworkInfo.State.DISCONNECTED) { 4865 if (VDBG) { 4866 log("isMobileOk: connected ni=" + 4867 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI)); 4868 } 4869 sleep(POLLING_SLEEP_SEC); 4870 continue; 4871 } 4872 } 4873 4874 log("isMobileOk: X result=" + result); 4875 } 4876 return result; 4877 } 4878 4879 @Override 4880 protected Integer doInBackground(Params... params) { 4881 return isMobileOk(params[0]); 4882 } 4883 4884 @Override 4885 protected void onPostExecute(Integer result) { 4886 log("onPostExecute: result=" + result); 4887 if ((mParams != null) && (mParams.mCb != null)) { 4888 mParams.mCb.onComplete(result); 4889 } 4890 } 4891 4892 private String inetAddressesToString(InetAddress[] addresses) { 4893 StringBuffer sb = new StringBuffer(); 4894 boolean firstTime = true; 4895 for(InetAddress addr : addresses) { 4896 if (firstTime) { 4897 firstTime = false; 4898 } else { 4899 sb.append(","); 4900 } 4901 sb.append(addr); 4902 } 4903 return sb.toString(); 4904 } 4905 4906 private void printNetworkInfo() { 4907 boolean hasIccCard = mTm.hasIccCard(); 4908 int simState = mTm.getSimState(); 4909 log("hasIccCard=" + hasIccCard 4910 + " simState=" + simState); 4911 NetworkInfo[] ni = mCs.getAllNetworkInfo(); 4912 if (ni != null) { 4913 log("ni.length=" + ni.length); 4914 for (NetworkInfo netInfo: ni) { 4915 log("netInfo=" + netInfo.toString()); 4916 } 4917 } else { 4918 log("no network info ni=null"); 4919 } 4920 } 4921 4922 /** 4923 * Sleep for a few seconds then return. 4924 * @param seconds 4925 */ 4926 private static void sleep(int seconds) { 4927 long stopTime = System.nanoTime() + (seconds * 1000000000); 4928 long sleepTime; 4929 while ((sleepTime = stopTime - System.nanoTime()) > 0) { 4930 try { 4931 Thread.sleep(sleepTime / 1000000); 4932 } catch (InterruptedException ignored) { 4933 } 4934 } 4935 } 4936 4937 private static void log(String s) { 4938 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s); 4939 } 4940 } 4941 4942 // TODO: Move to ConnectivityManager and make public? 4943 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION = 4944 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION"; 4945 4946 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() { 4947 @Override 4948 public void onReceive(Context context, Intent intent) { 4949 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) { 4950 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL")); 4951 } 4952 } 4953 }; 4954 4955 private void handleMobileProvisioningAction(String url) { 4956 // Mark notification as not visible 4957 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null); 4958 4959 // Check airplane mode 4960 boolean isAirplaneModeOn = Settings.System.getInt(mContext.getContentResolver(), 4961 Settings.Global.AIRPLANE_MODE_ON, 0) == 1; 4962 // If provisioning network and not in airplane mode handle as a special case, 4963 // otherwise launch browser with the intent directly. 4964 if (mIsProvisioningNetwork.get() && !isAirplaneModeOn) { 4965 if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch"); 4966 mIsProvisioningNetwork.set(false); 4967// mIsStartingProvisioning.set(true); 4968// MobileDataStateTracker mdst = (MobileDataStateTracker) 4969// mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4970 // Radio was disabled on CMP_RESULT_CODE_PROVISIONING_NETWORK, enable it here 4971// mdst.setRadio(true); 4972// mdst.setEnableFailFastMobileData(DctConstants.ENABLED); 4973// mdst.enableMobileProvisioning(url); 4974 } else { 4975 if (DBG) log("handleMobileProvisioningAction: not prov network"); 4976 mIsProvisioningNetwork.set(false); 4977 // Check for apps that can handle provisioning first 4978 Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP); 4979 provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX 4980 + mTelephonyManager.getSimOperator()); 4981 if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */) 4982 != null) { 4983 provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 4984 Intent.FLAG_ACTIVITY_NEW_TASK); 4985 mContext.startActivity(provisioningIntent); 4986 } else { 4987 // If no apps exist, use standard URL ACTION_VIEW method 4988 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, 4989 Intent.CATEGORY_APP_BROWSER); 4990 newIntent.setData(Uri.parse(url)); 4991 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 4992 Intent.FLAG_ACTIVITY_NEW_TASK); 4993 try { 4994 mContext.startActivity(newIntent); 4995 } catch (ActivityNotFoundException e) { 4996 loge("handleMobileProvisioningAction: startActivity failed" + e); 4997 } 4998 } 4999 } 5000 } 5001 5002 private static final String NOTIFICATION_ID = "CaptivePortal.Notification"; 5003 private volatile boolean mIsNotificationVisible = false; 5004 5005 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo, 5006 String url) { 5007 if (DBG) { 5008 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType 5009 + " extraInfo=" + extraInfo + " url=" + url); 5010 } 5011 5012 Resources r = Resources.getSystem(); 5013 NotificationManager notificationManager = (NotificationManager) mContext 5014 .getSystemService(Context.NOTIFICATION_SERVICE); 5015 5016 if (visible) { 5017 CharSequence title; 5018 CharSequence details; 5019 int icon; 5020 Intent intent; 5021 Notification notification = new Notification(); 5022 switch (networkType) { 5023 case ConnectivityManager.TYPE_WIFI: 5024 title = r.getString(R.string.wifi_available_sign_in, 0); 5025 details = r.getString(R.string.network_available_sign_in_detailed, 5026 extraInfo); 5027 icon = R.drawable.stat_notify_wifi_in_range; 5028 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 5029 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 5030 Intent.FLAG_ACTIVITY_NEW_TASK); 5031 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0); 5032 break; 5033 case ConnectivityManager.TYPE_MOBILE: 5034 case ConnectivityManager.TYPE_MOBILE_HIPRI: 5035 title = r.getString(R.string.network_available_sign_in, 0); 5036 // TODO: Change this to pull from NetworkInfo once a printable 5037 // name has been added to it 5038 details = mTelephonyManager.getNetworkOperatorName(); 5039 icon = R.drawable.stat_notify_rssi_in_range; 5040 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION); 5041 intent.putExtra("EXTRA_URL", url); 5042 intent.setFlags(0); 5043 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); 5044 break; 5045 default: 5046 title = r.getString(R.string.network_available_sign_in, 0); 5047 details = r.getString(R.string.network_available_sign_in_detailed, 5048 extraInfo); 5049 icon = R.drawable.stat_notify_rssi_in_range; 5050 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 5051 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 5052 Intent.FLAG_ACTIVITY_NEW_TASK); 5053 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0); 5054 break; 5055 } 5056 5057 notification.when = 0; 5058 notification.icon = icon; 5059 notification.flags = Notification.FLAG_AUTO_CANCEL; 5060 notification.tickerText = title; 5061 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent); 5062 5063 try { 5064 notificationManager.notify(NOTIFICATION_ID, networkType, notification); 5065 } catch (NullPointerException npe) { 5066 loge("setNotificaitionVisible: visible notificationManager npe=" + npe); 5067 npe.printStackTrace(); 5068 } 5069 } else { 5070 try { 5071 notificationManager.cancel(NOTIFICATION_ID, networkType); 5072 } catch (NullPointerException npe) { 5073 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe); 5074 npe.printStackTrace(); 5075 } 5076 } 5077 mIsNotificationVisible = visible; 5078 } 5079 5080 /** Location to an updatable file listing carrier provisioning urls. 5081 * An example: 5082 * 5083 * <?xml version="1.0" encoding="utf-8"?> 5084 * <provisioningUrls> 5085 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl> 5086 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl> 5087 * </provisioningUrls> 5088 */ 5089 private static final String PROVISIONING_URL_PATH = 5090 "/data/misc/radio/provisioning_urls.xml"; 5091 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH); 5092 5093 /** XML tag for root element. */ 5094 private static final String TAG_PROVISIONING_URLS = "provisioningUrls"; 5095 /** XML tag for individual url */ 5096 private static final String TAG_PROVISIONING_URL = "provisioningUrl"; 5097 /** XML tag for redirected url */ 5098 private static final String TAG_REDIRECTED_URL = "redirectedUrl"; 5099 /** XML attribute for mcc */ 5100 private static final String ATTR_MCC = "mcc"; 5101 /** XML attribute for mnc */ 5102 private static final String ATTR_MNC = "mnc"; 5103 5104 private static final int REDIRECTED_PROVISIONING = 1; 5105 private static final int PROVISIONING = 2; 5106 5107 private String getProvisioningUrlBaseFromFile(int type) { 5108 FileReader fileReader = null; 5109 XmlPullParser parser = null; 5110 Configuration config = mContext.getResources().getConfiguration(); 5111 String tagType; 5112 5113 switch (type) { 5114 case PROVISIONING: 5115 tagType = TAG_PROVISIONING_URL; 5116 break; 5117 case REDIRECTED_PROVISIONING: 5118 tagType = TAG_REDIRECTED_URL; 5119 break; 5120 default: 5121 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " + 5122 type); 5123 } 5124 5125 try { 5126 fileReader = new FileReader(mProvisioningUrlFile); 5127 parser = Xml.newPullParser(); 5128 parser.setInput(fileReader); 5129 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS); 5130 5131 while (true) { 5132 XmlUtils.nextElement(parser); 5133 5134 String element = parser.getName(); 5135 if (element == null) break; 5136 5137 if (element.equals(tagType)) { 5138 String mcc = parser.getAttributeValue(null, ATTR_MCC); 5139 try { 5140 if (mcc != null && Integer.parseInt(mcc) == config.mcc) { 5141 String mnc = parser.getAttributeValue(null, ATTR_MNC); 5142 if (mnc != null && Integer.parseInt(mnc) == config.mnc) { 5143 parser.next(); 5144 if (parser.getEventType() == XmlPullParser.TEXT) { 5145 return parser.getText(); 5146 } 5147 } 5148 } 5149 } catch (NumberFormatException e) { 5150 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e); 5151 } 5152 } 5153 } 5154 return null; 5155 } catch (FileNotFoundException e) { 5156 loge("Carrier Provisioning Urls file not found"); 5157 } catch (XmlPullParserException e) { 5158 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e); 5159 } catch (IOException e) { 5160 loge("I/O exception reading Carrier Provisioning Urls file: " + e); 5161 } finally { 5162 if (fileReader != null) { 5163 try { 5164 fileReader.close(); 5165 } catch (IOException e) {} 5166 } 5167 } 5168 return null; 5169 } 5170 5171 @Override 5172 public String getMobileRedirectedProvisioningUrl() { 5173 enforceConnectivityInternalPermission(); 5174 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING); 5175 if (TextUtils.isEmpty(url)) { 5176 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url); 5177 } 5178 return url; 5179 } 5180 5181 @Override 5182 public String getMobileProvisioningUrl() { 5183 enforceConnectivityInternalPermission(); 5184 String url = getProvisioningUrlBaseFromFile(PROVISIONING); 5185 if (TextUtils.isEmpty(url)) { 5186 url = mContext.getResources().getString(R.string.mobile_provisioning_url); 5187 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url); 5188 } else { 5189 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url); 5190 } 5191 // populate the iccid, imei and phone number in the provisioning url. 5192 if (!TextUtils.isEmpty(url)) { 5193 String phoneNumber = mTelephonyManager.getLine1Number(); 5194 if (TextUtils.isEmpty(phoneNumber)) { 5195 phoneNumber = "0000000000"; 5196 } 5197 url = String.format(url, 5198 mTelephonyManager.getSimSerialNumber() /* ICCID */, 5199 mTelephonyManager.getDeviceId() /* IMEI */, 5200 phoneNumber /* Phone numer */); 5201 } 5202 5203 return url; 5204 } 5205 5206 @Override 5207 public void setProvisioningNotificationVisible(boolean visible, int networkType, 5208 String extraInfo, String url) { 5209 enforceConnectivityInternalPermission(); 5210 setProvNotificationVisible(visible, networkType, extraInfo, url); 5211 } 5212 5213 @Override 5214 public void setAirplaneMode(boolean enable) { 5215 enforceConnectivityInternalPermission(); 5216 final long ident = Binder.clearCallingIdentity(); 5217 try { 5218 final ContentResolver cr = mContext.getContentResolver(); 5219 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 5220 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 5221 intent.putExtra("state", enable); 5222 mContext.sendBroadcast(intent); 5223 } finally { 5224 Binder.restoreCallingIdentity(ident); 5225 } 5226 } 5227 5228 private void onUserStart(int userId) { 5229 synchronized(mVpns) { 5230 Vpn userVpn = mVpns.get(userId); 5231 if (userVpn != null) { 5232 loge("Starting user already has a VPN"); 5233 return; 5234 } 5235 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId); 5236 mVpns.put(userId, userVpn); 5237 userVpn.startMonitoring(mContext, mTrackerHandler); 5238 } 5239 } 5240 5241 private void onUserStop(int userId) { 5242 synchronized(mVpns) { 5243 Vpn userVpn = mVpns.get(userId); 5244 if (userVpn == null) { 5245 loge("Stopping user has no VPN"); 5246 return; 5247 } 5248 mVpns.delete(userId); 5249 } 5250 } 5251 5252 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() { 5253 @Override 5254 public void onReceive(Context context, Intent intent) { 5255 final String action = intent.getAction(); 5256 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 5257 if (userId == UserHandle.USER_NULL) return; 5258 5259 if (Intent.ACTION_USER_STARTING.equals(action)) { 5260 onUserStart(userId); 5261 } else if (Intent.ACTION_USER_STOPPING.equals(action)) { 5262 onUserStop(userId); 5263 } 5264 } 5265 }; 5266 5267 @Override 5268 public LinkQualityInfo getLinkQualityInfo(int networkType) { 5269 enforceAccessPermission(); 5270 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) { 5271 return mNetTrackers[networkType].getLinkQualityInfo(); 5272 } else { 5273 return null; 5274 } 5275 } 5276 5277 @Override 5278 public LinkQualityInfo getActiveLinkQualityInfo() { 5279 enforceAccessPermission(); 5280 if (isNetworkTypeValid(mActiveDefaultNetwork) && 5281 mNetTrackers[mActiveDefaultNetwork] != null) { 5282 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo(); 5283 } else { 5284 return null; 5285 } 5286 } 5287 5288 @Override 5289 public LinkQualityInfo[] getAllLinkQualityInfo() { 5290 enforceAccessPermission(); 5291 final ArrayList<LinkQualityInfo> result = Lists.newArrayList(); 5292 for (NetworkStateTracker tracker : mNetTrackers) { 5293 if (tracker != null) { 5294 LinkQualityInfo li = tracker.getLinkQualityInfo(); 5295 if (li != null) { 5296 result.add(li); 5297 } 5298 } 5299 } 5300 5301 return result.toArray(new LinkQualityInfo[result.size()]); 5302 } 5303 5304 /* Infrastructure for network sampling */ 5305 5306 private void handleNetworkSamplingTimeout() { 5307 5308 log("Sampling interval elapsed, updating statistics .."); 5309 5310 // initialize list of interfaces .. 5311 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample = 5312 new HashMap<String, SamplingDataTracker.SamplingSnapshot>(); 5313 for (NetworkStateTracker tracker : mNetTrackers) { 5314 if (tracker != null) { 5315 String ifaceName = tracker.getNetworkInterfaceName(); 5316 if (ifaceName != null) { 5317 mapIfaceToSample.put(ifaceName, null); 5318 } 5319 } 5320 } 5321 5322 // Read samples for all interfaces 5323 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample); 5324 5325 // process samples for all networks 5326 for (NetworkStateTracker tracker : mNetTrackers) { 5327 if (tracker != null) { 5328 String ifaceName = tracker.getNetworkInterfaceName(); 5329 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName); 5330 if (ss != null) { 5331 // end the previous sampling cycle 5332 tracker.stopSampling(ss); 5333 // start a new sampling cycle .. 5334 tracker.startSampling(ss); 5335 } 5336 } 5337 } 5338 5339 log("Done."); 5340 5341 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(), 5342 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS, 5343 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS); 5344 5345 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds"); 5346 5347 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent); 5348 } 5349 5350 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) { 5351 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds; 5352 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent); 5353 } 5354 5355 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = 5356 new HashMap<Messenger, NetworkFactoryInfo>(); 5357 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = 5358 new HashMap<NetworkRequest, NetworkRequestInfo>(); 5359 5360 private static class NetworkFactoryInfo { 5361 public final String name; 5362 public final Messenger messenger; 5363 public final AsyncChannel asyncChannel; 5364 5365 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) { 5366 this.name = name; 5367 this.messenger = messenger; 5368 this.asyncChannel = asyncChannel; 5369 } 5370 } 5371 5372 private class NetworkRequestInfo implements IBinder.DeathRecipient { 5373 static final boolean REQUEST = true; 5374 static final boolean LISTEN = false; 5375 5376 final NetworkRequest request; 5377 IBinder mBinder; 5378 final int mPid; 5379 final int mUid; 5380 final Messenger messenger; 5381 final boolean isRequest; 5382 5383 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) { 5384 super(); 5385 messenger = m; 5386 request = r; 5387 mBinder = binder; 5388 mPid = getCallingPid(); 5389 mUid = getCallingUid(); 5390 this.isRequest = isRequest; 5391 5392 try { 5393 mBinder.linkToDeath(this, 0); 5394 } catch (RemoteException e) { 5395 binderDied(); 5396 } 5397 } 5398 5399 void unlinkDeathRecipient() { 5400 mBinder.unlinkToDeath(this, 0); 5401 } 5402 5403 public void binderDied() { 5404 log("ConnectivityService NetworkRequestInfo binderDied(" + 5405 request + ", " + mBinder + ")"); 5406 releaseNetworkRequest(request); 5407 } 5408 5409 public String toString() { 5410 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" + 5411 mPid + " for " + request; 5412 } 5413 } 5414 5415 @Override 5416 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities, 5417 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) { 5418 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED) 5419 == false) { 5420 enforceConnectivityInternalPermission(); 5421 } else { 5422 enforceChangePermission(); 5423 } 5424 5425 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) { 5426 throw new IllegalArgumentException("Bad timeout specified"); 5427 } 5428 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities( 5429 networkCapabilities), legacyType, nextNetworkRequestId()); 5430 if (DBG) log("requestNetwork for " + networkRequest); 5431 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, 5432 NetworkRequestInfo.REQUEST); 5433 5434 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri)); 5435 if (timeoutMs > 0) { 5436 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST, 5437 nri), timeoutMs); 5438 } 5439 return networkRequest; 5440 } 5441 5442 @Override 5443 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities, 5444 PendingIntent operation) { 5445 // TODO 5446 return null; 5447 } 5448 5449 @Override 5450 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities, 5451 Messenger messenger, IBinder binder) { 5452 enforceAccessPermission(); 5453 5454 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities( 5455 networkCapabilities), TYPE_NONE, nextNetworkRequestId()); 5456 if (DBG) log("listenForNetwork for " + networkRequest); 5457 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, 5458 NetworkRequestInfo.LISTEN); 5459 5460 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 5461 return networkRequest; 5462 } 5463 5464 @Override 5465 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities, 5466 PendingIntent operation) { 5467 } 5468 5469 @Override 5470 public void releaseNetworkRequest(NetworkRequest networkRequest) { 5471 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 5472 0, networkRequest)); 5473 } 5474 5475 @Override 5476 public void registerNetworkFactory(Messenger messenger, String name) { 5477 enforceConnectivityInternalPermission(); 5478 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel()); 5479 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi)); 5480 } 5481 5482 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) { 5483 if (VDBG) log("Got NetworkFactory Messenger for " + nfi.name); 5484 mNetworkFactoryInfos.put(nfi.messenger, nfi); 5485 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger); 5486 } 5487 5488 @Override 5489 public void unregisterNetworkFactory(Messenger messenger) { 5490 enforceConnectivityInternalPermission(); 5491 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger)); 5492 } 5493 5494 private void handleUnregisterNetworkFactory(Messenger messenger) { 5495 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger); 5496 if (nfi == null) { 5497 if (VDBG) log("Failed to find Messenger in unregisterNetworkFactory"); 5498 return; 5499 } 5500 if (VDBG) log("unregisterNetworkFactory for " + nfi.name); 5501 } 5502 5503 /** 5504 * NetworkAgentInfo supporting a request by requestId. 5505 * These have already been vetted (their Capabilities satisfy the request) 5506 * and the are the highest scored network available. 5507 * the are keyed off the Requests requestId. 5508 */ 5509 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = 5510 new SparseArray<NetworkAgentInfo>(); 5511 5512 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = 5513 new SparseArray<NetworkAgentInfo>(); 5514 5515 // NetworkAgentInfo keyed off its connecting messenger 5516 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays 5517 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = 5518 new HashMap<Messenger, NetworkAgentInfo>(); 5519 5520 private final NetworkRequest mDefaultRequest; 5521 5522 public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo, 5523 LinkProperties linkProperties, NetworkCapabilities networkCapabilities, 5524 int currentScore) { 5525 enforceConnectivityInternalPermission(); 5526 5527 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), nextNetId(), 5528 new NetworkInfo(networkInfo), new LinkProperties(linkProperties), 5529 new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler); 5530 if (VDBG) log("registerNetworkAgent " + nai); 5531 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai)); 5532 } 5533 5534 private void handleRegisterNetworkAgent(NetworkAgentInfo na) { 5535 if (VDBG) log("Got NetworkAgent Messenger"); 5536 mNetworkAgentInfos.put(na.messenger, na); 5537 mNetworkForNetId.put(na.network.netId, na); 5538 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger); 5539 NetworkInfo networkInfo = na.networkInfo; 5540 na.networkInfo = null; 5541 updateNetworkInfo(na, networkInfo); 5542 } 5543 5544 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) { 5545 LinkProperties newLp = networkAgent.linkProperties; 5546 int netId = networkAgent.network.netId; 5547 5548 updateInterfaces(newLp, oldLp, netId); 5549 updateMtu(newLp, oldLp); 5550 // TODO - figure out what to do for clat 5551// for (LinkProperties lp : newLp.getStackedLinks()) { 5552// updateMtu(lp, null); 5553// } 5554 updateRoutes(newLp, oldLp, netId); 5555 updateDnses(newLp, oldLp, netId); 5556 updateClat(newLp, oldLp, networkAgent); 5557 } 5558 5559 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) { 5560 // Update 464xlat state. 5561 if (mClat.requiresClat(na)) { 5562 5563 // If the connection was previously using clat, but is not using it now, stop the clat 5564 // daemon. Normally, this happens automatically when the connection disconnects, but if 5565 // the disconnect is not reported, or if the connection's LinkProperties changed for 5566 // some other reason (e.g., handoff changes the IP addresses on the link), it would 5567 // still be running. If it's not running, then stopping it is a no-op. 5568 if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) { 5569 mClat.stopClat(); 5570 } 5571 // If the link requires clat to be running, then start the daemon now. 5572 if (na.networkInfo.isConnected()) { 5573 mClat.startClat(na); 5574 } else { 5575 mClat.stopClat(); 5576 } 5577 } 5578 } 5579 5580 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) { 5581 CompareResult<String> interfaceDiff = new CompareResult<String>(); 5582 if (oldLp != null) { 5583 interfaceDiff = oldLp.compareAllInterfaceNames(newLp); 5584 } else if (newLp != null) { 5585 interfaceDiff.added = newLp.getAllInterfaceNames(); 5586 } 5587 for (String iface : interfaceDiff.added) { 5588 try { 5589 mNetd.addInterfaceToNetwork(iface, netId); 5590 } catch (Exception e) { 5591 loge("Exception adding interface: " + e); 5592 } 5593 } 5594 for (String iface : interfaceDiff.removed) { 5595 try { 5596 mNetd.removeInterfaceFromNetwork(iface, netId); 5597 } catch (Exception e) { 5598 loge("Exception removing interface: " + e); 5599 } 5600 } 5601 } 5602 5603 private void updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) { 5604 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 5605 if (oldLp != null) { 5606 routeDiff = oldLp.compareAllRoutes(newLp); 5607 } else if (newLp != null) { 5608 routeDiff.added = newLp.getAllRoutes(); 5609 } 5610 5611 // add routes before removing old in case it helps with continuous connectivity 5612 5613 // do this twice, adding non-nexthop routes first, then routes they are dependent on 5614 for (RouteInfo route : routeDiff.added) { 5615 if (route.hasGateway()) continue; 5616 try { 5617 mNetd.addRoute(netId, route); 5618 } catch (Exception e) { 5619 loge("Exception in addRoute for non-gateway: " + e); 5620 } 5621 } 5622 for (RouteInfo route : routeDiff.added) { 5623 if (route.hasGateway() == false) continue; 5624 try { 5625 mNetd.addRoute(netId, route); 5626 } catch (Exception e) { 5627 loge("Exception in addRoute for gateway: " + e); 5628 } 5629 } 5630 5631 for (RouteInfo route : routeDiff.removed) { 5632 try { 5633 mNetd.removeRoute(netId, route); 5634 } catch (Exception e) { 5635 loge("Exception in removeRoute: " + e); 5636 } 5637 } 5638 } 5639 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) { 5640 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) { 5641 Collection<InetAddress> dnses = newLp.getDnsServers(); 5642 if (dnses.size() == 0 && mDefaultDns != null) { 5643 dnses = new ArrayList(); 5644 dnses.add(mDefaultDns); 5645 if (DBG) { 5646 loge("no dns provided for netId " + netId + ", so using defaults"); 5647 } 5648 } 5649 try { 5650 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), 5651 newLp.getDomains()); 5652 } catch (Exception e) { 5653 loge("Exception in setDnsServersForNetwork: " + e); 5654 } 5655 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId); 5656 if (defaultNai != null && defaultNai.network.netId == netId) { 5657 setDefaultDnsSystemProperties(dnses); 5658 } 5659 } 5660 } 5661 5662 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) { 5663 int last = 0; 5664 for (InetAddress dns : dnses) { 5665 ++last; 5666 String key = "net.dns" + last; 5667 String value = dns.getHostAddress(); 5668 SystemProperties.set(key, value); 5669 } 5670 for (int i = last + 1; i <= mNumDnsEntries; ++i) { 5671 String key = "net.dns" + i; 5672 SystemProperties.set(key, ""); 5673 } 5674 mNumDnsEntries = last; 5675 } 5676 5677 5678 private void updateCapabilities(NetworkAgentInfo networkAgent, 5679 NetworkCapabilities networkCapabilities) { 5680 // TODO - what else here? Verify still satisfies everybody? 5681 // Check if satisfies somebody new? call callbacks? 5682 networkAgent.networkCapabilities = networkCapabilities; 5683 } 5684 5685 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) { 5686 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString()); 5687 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 5688 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0, 5689 networkRequest); 5690 } 5691 } 5692 5693 private void callCallbackForRequest(NetworkRequestInfo nri, 5694 NetworkAgentInfo networkAgent, int notificationType) { 5695 if (nri.messenger == null) return; // Default request has no msgr 5696 Object o; 5697 int a1 = 0; 5698 int a2 = 0; 5699 switch (notificationType) { 5700 case ConnectivityManager.CALLBACK_LOSING: 5701 a1 = 30 * 1000; // TODO - read this from NetworkMonitor 5702 // fall through 5703 case ConnectivityManager.CALLBACK_PRECHECK: 5704 case ConnectivityManager.CALLBACK_AVAILABLE: 5705 case ConnectivityManager.CALLBACK_LOST: 5706 case ConnectivityManager.CALLBACK_CAP_CHANGED: 5707 case ConnectivityManager.CALLBACK_IP_CHANGED: { 5708 o = new NetworkRequest(nri.request); 5709 a2 = networkAgent.network.netId; 5710 break; 5711 } 5712 case ConnectivityManager.CALLBACK_UNAVAIL: 5713 case ConnectivityManager.CALLBACK_RELEASED: { 5714 o = new NetworkRequest(nri.request); 5715 break; 5716 } 5717 default: { 5718 loge("Unknown notificationType " + notificationType); 5719 return; 5720 } 5721 } 5722 Message msg = Message.obtain(); 5723 msg.arg1 = a1; 5724 msg.arg2 = a2; 5725 msg.obj = o; 5726 msg.what = notificationType; 5727 try { 5728 if (VDBG) log("sending notification " + notificationType + " for " + nri.request); 5729 nri.messenger.send(msg); 5730 } catch (RemoteException e) { 5731 // may occur naturally in the race of binder death. 5732 loge("RemoteException caught trying to send a callback msg for " + nri.request); 5733 } 5734 } 5735 5736 private void handleLingerComplete(NetworkAgentInfo oldNetwork) { 5737 if (oldNetwork == null) { 5738 loge("Unknown NetworkAgentInfo in handleLingerComplete"); 5739 return; 5740 } 5741 if (DBG) log("handleLingerComplete for " + oldNetwork.name()); 5742 if (DBG) { 5743 if (oldNetwork.networkRequests.size() != 0) { 5744 loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests"); 5745 } 5746 } 5747 oldNetwork.asyncChannel.disconnect(); 5748 } 5749 5750 private void handleConnectionValidated(NetworkAgentInfo newNetwork) { 5751 if (newNetwork == null) { 5752 loge("Unknown NetworkAgentInfo in handleConnectionValidated"); 5753 return; 5754 } 5755 boolean keep = false; 5756 boolean isNewDefault = false; 5757 if (DBG) log("handleConnectionValidated for "+newNetwork.name()); 5758 // check if any NetworkRequest wants this NetworkAgent 5759 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>(); 5760 if (VDBG) log(" new Network has: " + newNetwork.networkCapabilities); 5761 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 5762 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId); 5763 if (newNetwork == currentNetwork) { 5764 if (VDBG) log("Network " + newNetwork.name() + " was already satisfying" + 5765 " request " + nri.request.requestId + ". No change."); 5766 keep = true; 5767 continue; 5768 } 5769 5770 // check if it satisfies the NetworkCapabilities 5771 if (VDBG) log(" checking if request is satisfied: " + nri.request); 5772 if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities( 5773 newNetwork.networkCapabilities)) { 5774 // next check if it's better than any current network we're using for 5775 // this request 5776 if (VDBG) { 5777 log("currentScore = " + 5778 (currentNetwork != null ? currentNetwork.currentScore : 0) + 5779 ", newScore = " + newNetwork.currentScore); 5780 } 5781 if (currentNetwork == null || 5782 currentNetwork.currentScore < newNetwork.currentScore) { 5783 if (currentNetwork != null) { 5784 if (VDBG) log(" accepting network in place of " + currentNetwork.name()); 5785 currentNetwork.networkRequests.remove(nri.request.requestId); 5786 currentNetwork.networkLingered.add(nri.request); 5787 affectedNetworks.add(currentNetwork); 5788 } else { 5789 if (VDBG) log(" accepting network in place of null"); 5790 } 5791 mNetworkForRequestId.put(nri.request.requestId, newNetwork); 5792 newNetwork.addRequest(nri.request); 5793 int legacyType = nri.request.legacyType; 5794 if (legacyType != TYPE_NONE) { 5795 mLegacyTypeTracker.add(legacyType, newNetwork); 5796 } 5797 keep = true; 5798 // TODO - this could get expensive if we have alot of requests for this 5799 // network. Think about if there is a way to reduce this. Push 5800 // netid->request mapping to each factory? 5801 sendUpdatedScoreToFactories(nri.request, newNetwork.currentScore); 5802 if (mDefaultRequest.requestId == nri.request.requestId) { 5803 isNewDefault = true; 5804 updateActiveDefaultNetwork(newNetwork); 5805 if (newNetwork.linkProperties != null) { 5806 setDefaultDnsSystemProperties( 5807 newNetwork.linkProperties.getDnsServers()); 5808 } else { 5809 setDefaultDnsSystemProperties(new ArrayList<InetAddress>()); 5810 } 5811 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork); 5812 } 5813 } 5814 } 5815 } 5816 for (NetworkAgentInfo nai : affectedNetworks) { 5817 boolean teardown = true; 5818 for (int i = 0; i < nai.networkRequests.size(); i++) { 5819 NetworkRequest nr = nai.networkRequests.valueAt(i); 5820 try { 5821 if (mNetworkRequests.get(nr).isRequest) { 5822 teardown = false; 5823 } 5824 } catch (Exception e) { 5825 loge("Request " + nr + " not found in mNetworkRequests."); 5826 loge(" it came from request list of " + nai.name()); 5827 } 5828 } 5829 if (teardown) { 5830 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER); 5831 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING); 5832 } else { 5833 // not going to linger, so kill the list of linger networks.. only 5834 // notify them of linger if it happens as the result of gaining another, 5835 // but if they transition and old network stays up, don't tell them of linger 5836 // or very delayed loss 5837 nai.networkLingered.clear(); 5838 if (VDBG) log("Lingered for " + nai.name() + " cleared"); 5839 } 5840 } 5841 if (keep) { 5842 if (isNewDefault) { 5843 if (VDBG) log("Switching to new default network: " + newNetwork); 5844 setupDataActivityTracking(newNetwork); 5845 try { 5846 mNetd.setDefaultNetId(newNetwork.network.netId); 5847 } catch (Exception e) { 5848 loge("Exception setting default network :" + e); 5849 } 5850 if (newNetwork.equals(mNetworkForRequestId.get(mDefaultRequest.requestId))) { 5851 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy()); 5852 } 5853 synchronized (ConnectivityService.this) { 5854 // have a new default network, release the transition wakelock in 5855 // a second if it's held. The second pause is to allow apps 5856 // to reconnect over the new network 5857 if (mNetTransitionWakeLock.isHeld()) { 5858 mHandler.sendMessageDelayed(mHandler.obtainMessage( 5859 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 5860 mNetTransitionWakeLockSerialNumber, 0), 5861 1000); 5862 } 5863 } 5864 5865 // this will cause us to come up initially as unconnected and switching 5866 // to connected after our normal pause unless somebody reports us as 5867 // really disconnected 5868 mDefaultInetConditionPublished = 0; 5869 mDefaultConnectionSequence++; 5870 mInetConditionChangeInFlight = false; 5871 // TODO - read the tcp buffer size config string from somewhere 5872 // updateNetworkSettings(); 5873 } 5874 // notify battery stats service about this network 5875 try { 5876 BatteryStatsService.getService().noteNetworkInterfaceType( 5877 newNetwork.linkProperties.getInterfaceName(), 5878 newNetwork.networkInfo.getType()); 5879 } catch (RemoteException e) { } 5880 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE); 5881 } else { 5882 if (DBG && newNetwork.networkRequests.size() != 0) { 5883 loge("tearing down network with live requests:"); 5884 for (int i=0; i < newNetwork.networkRequests.size(); i++) { 5885 loge(" " + newNetwork.networkRequests.valueAt(i)); 5886 } 5887 } 5888 if (VDBG) log("Validated network turns out to be unwanted. Tear it down."); 5889 newNetwork.asyncChannel.disconnect(); 5890 } 5891 } 5892 5893 5894 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) { 5895 NetworkInfo.State state = newInfo.getState(); 5896 NetworkInfo oldInfo = networkAgent.networkInfo; 5897 networkAgent.networkInfo = newInfo; 5898 5899 if (oldInfo != null && oldInfo.getState() == state) { 5900 if (VDBG) log("ignoring duplicate network state non-change"); 5901 return; 5902 } 5903 if (DBG) { 5904 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " + 5905 (oldInfo == null ? "null" : oldInfo.getState()) + 5906 " to " + state); 5907 } 5908 5909 if (state == NetworkInfo.State.CONNECTED) { 5910 try { 5911 // This is likely caused by the fact that this network already 5912 // exists. An example is when a network goes from CONNECTED to 5913 // CONNECTING and back (like wifi on DHCP renew). 5914 // TODO: keep track of which networks we've created, or ask netd 5915 // to tell us whether we've already created this network or not. 5916 mNetd.createNetwork(networkAgent.network.netId); 5917 } catch (Exception e) { 5918 loge("Error creating network " + networkAgent.network.netId + ": " 5919 + e.getMessage()); 5920 return; 5921 } 5922 5923 updateLinkProperties(networkAgent, null); 5924 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK); 5925 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 5926 } else if (state == NetworkInfo.State.DISCONNECTED || 5927 state == NetworkInfo.State.SUSPENDED) { 5928 networkAgent.asyncChannel.disconnect(); 5929 } 5930 } 5931 5932 private void updateNetworkScore(NetworkAgentInfo nai, int score) { 5933 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score); 5934 5935 nai.currentScore = score; 5936 5937 // TODO - This will not do the right thing if this network is lowering 5938 // its score and has requests that can be served by other 5939 // currently-active networks, or if the network is increasing its 5940 // score and other networks have requests that can be better served 5941 // by this network. 5942 // 5943 // Really we want to see if any of our requests migrate to other 5944 // active/lingered networks and if any other requests migrate to us (depending 5945 // on increasing/decreasing currentScore. That's a bit of work and probably our 5946 // score checking/network allocation code needs to be modularized so we can understand 5947 // (see handleConnectionValided for an example). 5948 // 5949 // As a first order approx, lets just advertise the new score to factories. If 5950 // somebody can beat it they will nominate a network and our normal net replacement 5951 // code will fire. 5952 for (int i = 0; i < nai.networkRequests.size(); i++) { 5953 NetworkRequest nr = nai.networkRequests.valueAt(i); 5954 sendUpdatedScoreToFactories(nr, score); 5955 } 5956 } 5957 5958 // notify only this one new request of the current state 5959 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) { 5960 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE; 5961 // TODO - read state from monitor to decide what to send. 5962// if (nai.networkMonitor.isLingering()) { 5963// notifyType = NetworkCallbacks.LOSING; 5964// } else if (nai.networkMonitor.isEvaluating()) { 5965// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType); 5966// } 5967 callCallbackForRequest(nri, nai, notifyType); 5968 } 5969 5970 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) { 5971 if (connected) { 5972 NetworkInfo info = new NetworkInfo(nai.networkInfo); 5973 info.setType(type); 5974 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay()); 5975 } else { 5976 NetworkInfo info = new NetworkInfo(nai.networkInfo); 5977 info.setType(type); 5978 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 5979 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 5980 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 5981 if (info.isFailover()) { 5982 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 5983 nai.networkInfo.setFailover(false); 5984 } 5985 if (info.getReason() != null) { 5986 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 5987 } 5988 if (info.getExtraInfo() != null) { 5989 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo()); 5990 } 5991 NetworkAgentInfo newDefaultAgent = null; 5992 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 5993 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId); 5994 if (newDefaultAgent != null) { 5995 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, 5996 newDefaultAgent.networkInfo); 5997 } else { 5998 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 5999 } 6000 } 6001 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, 6002 mDefaultInetConditionPublished); 6003 final Intent immediateIntent = new Intent(intent); 6004 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE); 6005 sendStickyBroadcast(immediateIntent); 6006 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay()); 6007 if (newDefaultAgent != null) { 6008 sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo, 6009 getConnectivityChangeDelay()); 6010 } 6011 } 6012 } 6013 6014 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) { 6015 if (VDBG) log("notifyType " + notifyType + " for " + networkAgent.name()); 6016 for (int i = 0; i < networkAgent.networkRequests.size(); i++) { 6017 NetworkRequest nr = networkAgent.networkRequests.valueAt(i); 6018 NetworkRequestInfo nri = mNetworkRequests.get(nr); 6019 if (VDBG) log(" sending notification for " + nr); 6020 callCallbackForRequest(nri, networkAgent, notifyType); 6021 } 6022 } 6023 6024 private LinkProperties getLinkPropertiesForTypeInternal(int networkType) { 6025 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 6026 return (nai != null) ? 6027 new LinkProperties(nai.linkProperties) : 6028 new LinkProperties(); 6029 } 6030 6031 private NetworkInfo getNetworkInfoForType(int networkType) { 6032 if (!mLegacyTypeTracker.isTypeSupported(networkType)) 6033 return null; 6034 6035 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 6036 if (nai != null) { 6037 NetworkInfo result = new NetworkInfo(nai.networkInfo); 6038 result.setType(networkType); 6039 return result; 6040 } else { 6041 return new NetworkInfo(networkType, 0, "Unknown", ""); 6042 } 6043 } 6044 6045 private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) { 6046 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 6047 return (nai != null) ? 6048 new NetworkCapabilities(nai.networkCapabilities) : 6049 new NetworkCapabilities(); 6050 } 6051} 6052