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