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