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