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