ConnectivityService.java revision 3b75982e39ed9370153ae7f238f1d6041b9506ed
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.NetworkPolicyManager.RULE_ALLOW_ALL; 35import static android.net.NetworkPolicyManager.RULE_REJECT_METERED; 36 37import android.app.AlarmManager; 38import android.app.AppOpsManager; 39import android.app.Notification; 40import android.app.NotificationManager; 41import android.app.PendingIntent; 42import android.bluetooth.BluetoothTetheringDataTracker; 43import android.content.ActivityNotFoundException; 44import android.content.BroadcastReceiver; 45import android.content.ContentResolver; 46import android.content.Context; 47import android.content.ContextWrapper; 48import android.content.Intent; 49import android.content.IntentFilter; 50import android.content.pm.ApplicationInfo; 51import android.content.pm.PackageManager; 52import android.content.pm.PackageManager.NameNotFoundException; 53import android.content.res.Configuration; 54import android.content.res.Resources; 55import android.database.ContentObserver; 56import android.net.CaptivePortalTracker; 57import android.net.ConnectivityManager; 58import android.net.DummyDataStateTracker; 59import android.net.EthernetDataTracker; 60import android.net.IConnectivityManager; 61import android.net.INetworkManagementEventObserver; 62import android.net.INetworkPolicyListener; 63import android.net.INetworkPolicyManager; 64import android.net.INetworkStatsService; 65import android.net.LinkAddress; 66import android.net.LinkProperties; 67import android.net.LinkProperties.CompareResult; 68import android.net.LinkQualityInfo; 69import android.net.MobileDataStateTracker; 70import android.net.Network; 71import android.net.NetworkAgent; 72import android.net.NetworkCapabilities; 73import android.net.NetworkConfig; 74import android.net.NetworkInfo; 75import android.net.NetworkInfo.DetailedState; 76import android.net.NetworkQuotaInfo; 77import android.net.NetworkRequest; 78import android.net.NetworkState; 79import android.net.NetworkStateTracker; 80import android.net.NetworkUtils; 81import android.net.Proxy; 82import android.net.ProxyDataTracker; 83import android.net.ProxyInfo; 84import android.net.RouteInfo; 85import android.net.SamplingDataTracker; 86import android.net.Uri; 87import android.net.wimax.WimaxManagerConstants; 88import android.os.AsyncTask; 89import android.os.Binder; 90import android.os.Build; 91import android.os.FileUtils; 92import android.os.Handler; 93import android.os.HandlerThread; 94import android.os.IBinder; 95import android.os.INetworkManagementService; 96import android.os.Looper; 97import android.os.Message; 98import android.os.Messenger; 99import android.os.ParcelFileDescriptor; 100import android.os.PowerManager; 101import android.os.Process; 102import android.os.RemoteException; 103import android.os.ServiceManager; 104import android.os.SystemClock; 105import android.os.SystemProperties; 106import android.os.UserHandle; 107import android.provider.Settings; 108import android.security.Credentials; 109import android.security.KeyStore; 110import android.telephony.TelephonyManager; 111import android.text.TextUtils; 112import android.util.Slog; 113import android.util.SparseArray; 114import android.util.SparseIntArray; 115import android.util.Xml; 116 117import com.android.internal.R; 118import com.android.internal.annotations.GuardedBy; 119import com.android.internal.net.LegacyVpnInfo; 120import com.android.internal.net.VpnConfig; 121import com.android.internal.net.VpnProfile; 122import com.android.internal.telephony.DctConstants; 123import com.android.internal.telephony.Phone; 124import com.android.internal.telephony.PhoneConstants; 125import com.android.internal.telephony.TelephonyIntents; 126import com.android.internal.util.AsyncChannel; 127import com.android.internal.util.IndentingPrintWriter; 128import com.android.internal.util.XmlUtils; 129import com.android.server.am.BatteryStatsService; 130import com.android.server.connectivity.DataConnectionStats; 131import com.android.server.connectivity.Nat464Xlat; 132import com.android.server.connectivity.NetworkAgentInfo; 133import com.android.server.connectivity.NetworkMonitor; 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// Already in place in new function. This is dead code. 1912// if (mNetConfigs[prevNetType].isDefault()) { 1913// removeDataActivityTracking(prevNetType); 1914// } 1915 1916 /* 1917 * If the disconnected network is not the active one, then don't report 1918 * this as a loss of connectivity. What probably happened is that we're 1919 * getting the disconnect for a network that we explicitly disabled 1920 * in accordance with network preference policies. 1921 */ 1922 if (!mNetConfigs[prevNetType].isDefault()) { 1923 List<Integer> pids = mNetRequestersPids[prevNetType]; 1924 for (Integer pid : pids) { 1925 // will remove them because the net's no longer connected 1926 // need to do this now as only now do we know the pids and 1927 // can properly null things that are no longer referenced. 1928 reassessPidDns(pid.intValue(), false); 1929 } 1930 } 1931 1932 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 1933 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info)); 1934 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 1935 if (info.isFailover()) { 1936 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 1937 info.setFailover(false); 1938 } 1939 if (info.getReason() != null) { 1940 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 1941 } 1942 if (info.getExtraInfo() != null) { 1943 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, 1944 info.getExtraInfo()); 1945 } 1946 1947 if (mNetConfigs[prevNetType].isDefault()) { 1948 tryFailover(prevNetType); 1949 if (mActiveDefaultNetwork != -1) { 1950 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(); 1951 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo); 1952 } else { 1953 mDefaultInetConditionPublished = 0; // we're not connected anymore 1954 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 1955 } 1956 } 1957 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished); 1958 1959 // Reset interface if no other connections are using the same interface 1960 boolean doReset = true; 1961 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties(); 1962 if (linkProperties != null) { 1963 String oldIface = linkProperties.getInterfaceName(); 1964 if (TextUtils.isEmpty(oldIface) == false) { 1965 for (NetworkStateTracker networkStateTracker : mNetTrackers) { 1966 if (networkStateTracker == null) continue; 1967 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo(); 1968 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) { 1969 LinkProperties l = networkStateTracker.getLinkProperties(); 1970 if (l == null) continue; 1971 if (oldIface.equals(l.getInterfaceName())) { 1972 doReset = false; 1973 break; 1974 } 1975 } 1976 } 1977 } 1978 } 1979 1980 // do this before we broadcast the change 1981// Already done in new function. This is dead code. 1982// handleConnectivityChange(prevNetType, doReset); 1983 1984 final Intent immediateIntent = new Intent(intent); 1985 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE); 1986 sendStickyBroadcast(immediateIntent); 1987 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay()); 1988 /* 1989 * If the failover network is already connected, then immediately send 1990 * out a followup broadcast indicating successful failover 1991 */ 1992 if (mActiveDefaultNetwork != -1) { 1993 sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(), 1994 getConnectivityChangeDelay()); 1995 } 1996 try { 1997// mNetd.removeNetwork(thisNetId); 1998 } catch (Exception e) { 1999 loge("Exception removing network: " + e); 2000 } finally { 2001 mNetTrackers[prevNetType].setNetId(INVALID_NET_ID); 2002 } 2003 } 2004 2005 private void tryFailover(int prevNetType) { 2006 /* 2007 * If this is a default network, check if other defaults are available. 2008 * Try to reconnect on all available and let them hash it out when 2009 * more than one connects. 2010 */ 2011 if (mNetConfigs[prevNetType].isDefault()) { 2012 if (mActiveDefaultNetwork == prevNetType) { 2013 if (DBG) { 2014 log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType); 2015 } 2016 mActiveDefaultNetwork = -1; 2017 try { 2018 mNetd.clearDefaultNetId(); 2019 } catch (Exception e) { 2020 loge("Exception clearing default network :" + e); 2021 } 2022 } 2023 2024 // don't signal a reconnect for anything lower or equal priority than our 2025 // current connected default 2026 // TODO - don't filter by priority now - nice optimization but risky 2027// int currentPriority = -1; 2028// if (mActiveDefaultNetwork != -1) { 2029// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority; 2030// } 2031 2032 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) { 2033 if (checkType == prevNetType) continue; 2034 if (mNetConfigs[checkType] == null) continue; 2035 if (!mNetConfigs[checkType].isDefault()) continue; 2036 if (mNetTrackers[checkType] == null) continue; 2037 2038// Enabling the isAvailable() optimization caused mobile to not get 2039// selected if it was in the middle of error handling. Specifically 2040// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL 2041// would not be available and we wouldn't get connected to anything. 2042// So removing the isAvailable() optimization below for now. TODO: This 2043// optimization should work and we need to investigate why it doesn't work. 2044// This could be related to how DEACTIVATE_DATA_CALL is reporting its 2045// complete before it is really complete. 2046 2047// if (!mNetTrackers[checkType].isAvailable()) continue; 2048 2049// if (currentPriority >= mNetConfigs[checkType].mPriority) continue; 2050 2051 NetworkStateTracker checkTracker = mNetTrackers[checkType]; 2052 NetworkInfo checkInfo = checkTracker.getNetworkInfo(); 2053 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) { 2054 checkInfo.setFailover(true); 2055 checkTracker.reconnect(); 2056 } 2057 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName()); 2058 } 2059 } 2060 } 2061 2062 public void sendConnectedBroadcast(NetworkInfo info) { 2063 enforceConnectivityInternalPermission(); 2064 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE); 2065 sendGeneralBroadcast(info, CONNECTIVITY_ACTION); 2066 } 2067 2068 private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) { 2069 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE); 2070 sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs); 2071 } 2072 2073 private void sendInetConditionBroadcast(NetworkInfo info) { 2074 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION); 2075 } 2076 2077 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) { 2078 if (mLockdownTracker != null) { 2079 info = mLockdownTracker.augmentNetworkInfo(info); 2080 } 2081 2082 Intent intent = new Intent(bcastType); 2083 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info)); 2084 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 2085 if (info.isFailover()) { 2086 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 2087 info.setFailover(false); 2088 } 2089 if (info.getReason() != null) { 2090 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 2091 } 2092 if (info.getExtraInfo() != null) { 2093 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, 2094 info.getExtraInfo()); 2095 } 2096 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished); 2097 return intent; 2098 } 2099 2100 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) { 2101 sendStickyBroadcast(makeGeneralIntent(info, bcastType)); 2102 } 2103 2104 private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) { 2105 sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs); 2106 } 2107 2108 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) { 2109 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE); 2110 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType); 2111 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active); 2112 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos); 2113 final long ident = Binder.clearCallingIdentity(); 2114 try { 2115 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL, 2116 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null); 2117 } finally { 2118 Binder.restoreCallingIdentity(ident); 2119 } 2120 } 2121 2122 private void sendStickyBroadcast(Intent intent) { 2123 synchronized(this) { 2124 if (!mSystemReady) { 2125 mInitialBroadcast = new Intent(intent); 2126 } 2127 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 2128 if (VDBG) { 2129 log("sendStickyBroadcast: action=" + intent.getAction()); 2130 } 2131 2132 final long ident = Binder.clearCallingIdentity(); 2133 try { 2134 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 2135 } finally { 2136 Binder.restoreCallingIdentity(ident); 2137 } 2138 } 2139 } 2140 2141 private void sendStickyBroadcastDelayed(Intent intent, int delayMs) { 2142 if (delayMs <= 0) { 2143 sendStickyBroadcast(intent); 2144 } else { 2145 if (VDBG) { 2146 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action=" 2147 + intent.getAction()); 2148 } 2149 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2150 EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs); 2151 } 2152 } 2153 2154 void systemReady() { 2155 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this); 2156 loadGlobalProxy(); 2157 2158 synchronized(this) { 2159 mSystemReady = true; 2160 if (mInitialBroadcast != null) { 2161 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL); 2162 mInitialBroadcast = null; 2163 } 2164 } 2165 // load the global proxy at startup 2166 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY)); 2167 2168 // Try bringing up tracker, but if KeyStore isn't ready yet, wait 2169 // for user to unlock device. 2170 if (!updateLockdownVpn()) { 2171 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT); 2172 mContext.registerReceiver(mUserPresentReceiver, filter); 2173 } 2174 } 2175 2176 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() { 2177 @Override 2178 public void onReceive(Context context, Intent intent) { 2179 // Try creating lockdown tracker, since user present usually means 2180 // unlocked keystore. 2181 if (updateLockdownVpn()) { 2182 mContext.unregisterReceiver(this); 2183 } 2184 } 2185 }; 2186 2187 private boolean isNewNetTypePreferredOverCurrentNetType(int type) { 2188 if (((type != mNetworkPreference) 2189 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority)) 2190 || (mNetworkPreference == mActiveDefaultNetwork)) { 2191 return false; 2192 } 2193 return true; 2194 } 2195 2196 private void handleConnect(NetworkInfo info) { 2197 final int newNetType = info.getType(); 2198 2199 // snapshot isFailover, because sendConnectedBroadcast() resets it 2200 boolean isFailover = info.isFailover(); 2201 final NetworkStateTracker thisNet = mNetTrackers[newNetType]; 2202 final String thisIface = thisNet.getLinkProperties().getInterfaceName(); 2203 2204 if (VDBG) { 2205 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface 2206 + " isFailover" + isFailover); 2207 } 2208 2209 // if this is a default net and other default is running 2210 // kill the one not preferred 2211 if (mNetConfigs[newNetType].isDefault()) { 2212 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) { 2213 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) { 2214 String teardownPolicy = SystemProperties.get("net.teardownPolicy"); 2215 if (TextUtils.equals(teardownPolicy, "keep") == false) { 2216 // tear down the other 2217 NetworkStateTracker otherNet = 2218 mNetTrackers[mActiveDefaultNetwork]; 2219 if (DBG) { 2220 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() + 2221 " teardown"); 2222 } 2223 if (!teardown(otherNet)) { 2224 loge("Network declined teardown request"); 2225 teardown(thisNet); 2226 return; 2227 } 2228 } else { 2229 //TODO - remove 2230 loge("network teardown skipped due to net.teardownPolicy setting"); 2231 } 2232 } else { 2233 // don't accept this one 2234 if (VDBG) { 2235 log("Not broadcasting CONNECT_ACTION " + 2236 "to torn down network " + info.getTypeName()); 2237 } 2238 teardown(thisNet); 2239 return; 2240 } 2241 } 2242 int thisNetId = nextNetId(); 2243 thisNet.setNetId(thisNetId); 2244 try { 2245// mNetd.createNetwork(thisNetId, thisIface); 2246 } catch (Exception e) { 2247 loge("Exception creating network :" + e); 2248 teardown(thisNet); 2249 return; 2250 } 2251// Already in place in new function. This is dead code. 2252// setupDataActivityTracking(newNetType); 2253 synchronized (ConnectivityService.this) { 2254 // have a new default network, release the transition wakelock in a second 2255 // if it's held. The second pause is to allow apps to reconnect over the 2256 // new network 2257 if (mNetTransitionWakeLock.isHeld()) { 2258 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2259 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 2260 mNetTransitionWakeLockSerialNumber, 0), 2261 1000); 2262 } 2263 } 2264 mActiveDefaultNetwork = newNetType; 2265 try { 2266 mNetd.setDefaultNetId(thisNetId); 2267 } catch (Exception e) { 2268 loge("Exception setting default network :" + e); 2269 } 2270 // this will cause us to come up initially as unconnected and switching 2271 // to connected after our normal pause unless somebody reports us as reall 2272 // disconnected 2273 mDefaultInetConditionPublished = 0; 2274 mDefaultConnectionSequence++; 2275 mInetConditionChangeInFlight = false; 2276 // Don't do this - if we never sign in stay, grey 2277 //reportNetworkCondition(mActiveDefaultNetwork, 100); 2278 updateNetworkSettings(thisNet); 2279 } else { 2280 int thisNetId = nextNetId(); 2281 thisNet.setNetId(thisNetId); 2282 try { 2283// mNetd.createNetwork(thisNetId, thisIface); 2284 } catch (Exception e) { 2285 loge("Exception creating network :" + e); 2286 teardown(thisNet); 2287 return; 2288 } 2289 } 2290 thisNet.setTeardownRequested(false); 2291// Already in place in new function. This is dead code. 2292// updateMtuSizeSettings(thisNet); 2293// handleConnectivityChange(newNetType, false); 2294 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay()); 2295 2296 // notify battery stats service about this network 2297 if (thisIface != null) { 2298 try { 2299 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType); 2300 } catch (RemoteException e) { 2301 // ignored; service lives in system_server 2302 } 2303 } 2304 } 2305 2306 /** @hide */ 2307 @Override 2308 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) { 2309 enforceConnectivityInternalPermission(); 2310 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal); 2311 mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal); 2312 } 2313 2314 /** 2315 * Setup data activity tracking for the given network. 2316 * 2317 * Every {@code setupDataActivityTracking} should be paired with a 2318 * {@link #removeDataActivityTracking} for cleanup. 2319 */ 2320 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) { 2321 final String iface = networkAgent.linkProperties.getInterfaceName(); 2322 2323 final int timeout; 2324 int type = ConnectivityManager.TYPE_NONE; 2325 2326 if (networkAgent.networkCapabilities.hasTransport( 2327 NetworkCapabilities.TRANSPORT_CELLULAR)) { 2328 timeout = Settings.Global.getInt(mContext.getContentResolver(), 2329 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE, 2330 5); 2331 type = ConnectivityManager.TYPE_MOBILE; 2332 } else if (networkAgent.networkCapabilities.hasTransport( 2333 NetworkCapabilities.TRANSPORT_WIFI)) { 2334 timeout = Settings.Global.getInt(mContext.getContentResolver(), 2335 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI, 2336 0); 2337 type = ConnectivityManager.TYPE_WIFI; 2338 } else { 2339 // do not track any other networks 2340 timeout = 0; 2341 } 2342 2343 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) { 2344 try { 2345 mNetd.addIdleTimer(iface, timeout, type); 2346 } catch (Exception e) { 2347 // You shall not crash! 2348 loge("Exception in setupDataActivityTracking " + e); 2349 } 2350 } 2351 } 2352 2353 /** 2354 * Remove data activity tracking when network disconnects. 2355 */ 2356 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) { 2357 final String iface = networkAgent.linkProperties.getInterfaceName(); 2358 final NetworkCapabilities caps = networkAgent.networkCapabilities; 2359 2360 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || 2361 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) { 2362 try { 2363 // the call fails silently if no idletimer setup for this interface 2364 mNetd.removeIdleTimer(iface); 2365 } catch (Exception e) { 2366 loge("Exception in removeDataActivityTracking " + e); 2367 } 2368 } 2369 } 2370 2371 /** 2372 * After a change in the connectivity state of a network. We're mainly 2373 * concerned with making sure that the list of DNS servers is set up 2374 * according to which networks are connected, and ensuring that the 2375 * right routing table entries exist. 2376 * 2377 * TODO - delete when we're sure all this functionallity is captured. 2378 */ 2379 private void handleConnectivityChange(int netType, LinkProperties curLp, boolean doReset) { 2380 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0; 2381 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType); 2382 if (VDBG) { 2383 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset 2384 + " resetMask=" + resetMask); 2385 } 2386 2387 /* 2388 * If a non-default network is enabled, add the host routes that 2389 * will allow it's DNS servers to be accessed. 2390 */ 2391 handleDnsConfigurationChange(netType); 2392 2393 LinkProperties newLp = null; 2394 2395 if (mNetTrackers[netType].getNetworkInfo().isConnected()) { 2396 newLp = mNetTrackers[netType].getLinkProperties(); 2397 if (VDBG) { 2398 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" + 2399 " doReset=" + doReset + " resetMask=" + resetMask + 2400 "\n curLp=" + curLp + 2401 "\n newLp=" + newLp); 2402 } 2403 2404 if (curLp != null) { 2405 if (curLp.isIdenticalInterfaceName(newLp)) { 2406 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp); 2407 if ((car.removed.size() != 0) || (car.added.size() != 0)) { 2408 for (LinkAddress linkAddr : car.removed) { 2409 if (linkAddr.getAddress() instanceof Inet4Address) { 2410 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES; 2411 } 2412 if (linkAddr.getAddress() instanceof Inet6Address) { 2413 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES; 2414 } 2415 } 2416 if (DBG) { 2417 log("handleConnectivityChange: addresses changed" + 2418 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask + 2419 "\n car=" + car); 2420 } 2421 } else { 2422 if (VDBG) { 2423 log("handleConnectivityChange: addresses are the same reset per" + 2424 " doReset linkProperty[" + netType + "]:" + 2425 " resetMask=" + resetMask); 2426 } 2427 } 2428 } else { 2429 resetMask = NetworkUtils.RESET_ALL_ADDRESSES; 2430 if (DBG) { 2431 log("handleConnectivityChange: interface not not equivalent reset both" + 2432 " linkProperty[" + netType + "]:" + 2433 " resetMask=" + resetMask); 2434 } 2435 } 2436 } 2437 if (mNetConfigs[netType].isDefault()) { 2438 handleApplyDefaultProxy(newLp.getHttpProxy()); 2439 } 2440 } else { 2441 if (VDBG) { 2442 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" + 2443 " doReset=" + doReset + " resetMask=" + resetMask + 2444 "\n curLp=" + curLp + 2445 "\n newLp= null"); 2446 } 2447 } 2448 mCurrentLinkProperties[netType] = newLp; 2449 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt, 2450 mNetTrackers[netType].getNetwork().netId); 2451 2452 if (resetMask != 0 || resetDns) { 2453 if (VDBG) log("handleConnectivityChange: resetting"); 2454 if (curLp != null) { 2455 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp); 2456 for (String iface : curLp.getAllInterfaceNames()) { 2457 if (TextUtils.isEmpty(iface) == false) { 2458 if (resetMask != 0) { 2459 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")"); 2460 NetworkUtils.resetConnections(iface, resetMask); 2461 2462 // Tell VPN the interface is down. It is a temporary 2463 // but effective fix to make VPN aware of the change. 2464 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) { 2465 synchronized(mVpns) { 2466 for (int i = 0; i < mVpns.size(); i++) { 2467 mVpns.valueAt(i).interfaceStatusChanged(iface, false); 2468 } 2469 } 2470 } 2471 } 2472 } else { 2473 loge("Can't reset connection for type "+netType); 2474 } 2475 } 2476 if (resetDns) { 2477 flushVmDnsCache(); 2478 if (VDBG) log("resetting DNS cache for type " + netType); 2479 try { 2480 mNetd.flushNetworkDnsCache(mNetTrackers[netType].getNetwork().netId); 2481 } catch (Exception e) { 2482 // never crash - catch them all 2483 if (DBG) loge("Exception resetting dns cache: " + e); 2484 } 2485 } 2486 } 2487 } 2488 2489 // TODO: Temporary notifying upstread change to Tethering. 2490 // @see bug/4455071 2491 /** Notify TetheringService if interface name has been changed. */ 2492 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(), 2493 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) { 2494 if (isTetheringSupported()) { 2495 mTethering.handleTetherIfaceChange(); 2496 } 2497 } 2498 } 2499 2500 /** 2501 * Add and remove routes using the old properties (null if not previously connected), 2502 * new properties (null if becoming disconnected). May even be double null, which 2503 * is a noop. 2504 * Uses isLinkDefault to determine if default routes should be set or conversely if 2505 * host routes should be set to the dns servers 2506 * returns a boolean indicating the routes changed 2507 */ 2508 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp, 2509 boolean isLinkDefault, boolean exempt, int netId) { 2510 Collection<RouteInfo> routesToAdd = null; 2511 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>(); 2512 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 2513 if (curLp != null) { 2514 // check for the delta between the current set and the new 2515 routeDiff = curLp.compareAllRoutes(newLp); 2516 dnsDiff = curLp.compareDnses(newLp); 2517 } else if (newLp != null) { 2518 routeDiff.added = newLp.getAllRoutes(); 2519 dnsDiff.added = newLp.getDnses(); 2520 } 2521 2522 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0); 2523 2524 for (RouteInfo r : routeDiff.removed) { 2525 if (isLinkDefault || ! r.isDefaultRoute()) { 2526 if (VDBG) log("updateRoutes: default remove route r=" + r); 2527 removeRoute(curLp, r, TO_DEFAULT_TABLE, netId); 2528 } 2529 if (isLinkDefault == false) { 2530 // remove from a secondary route table 2531 removeRoute(curLp, r, TO_SECONDARY_TABLE, netId); 2532 } 2533 } 2534 2535 for (RouteInfo r : routeDiff.added) { 2536 if (isLinkDefault || ! r.isDefaultRoute()) { 2537 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt, netId); 2538 } else { 2539 // add to a secondary route table 2540 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT, netId); 2541 2542 // many radios add a default route even when we don't want one. 2543 // remove the default route unless somebody else has asked for it 2544 String ifaceName = newLp.getInterfaceName(); 2545 synchronized (mRoutesLock) { 2546 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) { 2547 if (VDBG) log("Removing " + r + " for interface " + ifaceName); 2548 try { 2549 mNetd.removeRoute(netId, r); 2550 } catch (Exception e) { 2551 // never crash - catch them all 2552 if (DBG) loge("Exception trying to remove a route: " + e); 2553 } 2554 } 2555 } 2556 } 2557 } 2558 2559 return routesChanged; 2560 } 2561 2562 /** 2563 * Reads the network specific MTU size from reources. 2564 * and set it on it's iface. 2565 */ 2566 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) { 2567 final String iface = newLp.getInterfaceName(); 2568 final int mtu = newLp.getMtu(); 2569 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) { 2570 if (VDBG) log("identical MTU - not setting"); 2571 return; 2572 } 2573 2574 if (mtu < 68 || mtu > 10000) { 2575 loge("Unexpected mtu value: " + mtu + ", " + iface); 2576 return; 2577 } 2578 2579 try { 2580 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu); 2581 mNetd.setMtu(iface, mtu); 2582 } catch (Exception e) { 2583 Slog.e(TAG, "exception in setMtu()" + e); 2584 } 2585 } 2586 2587 /** 2588 * Reads the network specific TCP buffer sizes from SystemProperties 2589 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system 2590 * wide use 2591 */ 2592 private void updateNetworkSettings(NetworkStateTracker nt) { 2593 String key = nt.getTcpBufferSizesPropName(); 2594 String bufferSizes = key == null ? null : SystemProperties.get(key); 2595 2596 if (TextUtils.isEmpty(bufferSizes)) { 2597 if (VDBG) log(key + " not found in system properties. Using defaults"); 2598 2599 // Setting to default values so we won't be stuck to previous values 2600 key = "net.tcp.buffersize.default"; 2601 bufferSizes = SystemProperties.get(key); 2602 } 2603 2604 // Set values in kernel 2605 if (bufferSizes.length() != 0) { 2606 if (VDBG) { 2607 log("Setting TCP values: [" + bufferSizes 2608 + "] which comes from [" + key + "]"); 2609 } 2610 setBufferSize(bufferSizes); 2611 } 2612 2613 final String defaultRwndKey = "net.tcp.default_init_rwnd"; 2614 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0); 2615 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(), 2616 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue); 2617 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd"; 2618 if (rwndValue != 0) { 2619 SystemProperties.set(sysctlKey, rwndValue.toString()); 2620 } 2621 } 2622 2623 /** 2624 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max] 2625 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem 2626 * 2627 * @param bufferSizes in the format of "readMin, readInitial, readMax, 2628 * writeMin, writeInitial, writeMax" 2629 */ 2630 private void setBufferSize(String bufferSizes) { 2631 try { 2632 String[] values = bufferSizes.split(","); 2633 2634 if (values.length == 6) { 2635 final String prefix = "/sys/kernel/ipv4/tcp_"; 2636 FileUtils.stringToFile(prefix + "rmem_min", values[0]); 2637 FileUtils.stringToFile(prefix + "rmem_def", values[1]); 2638 FileUtils.stringToFile(prefix + "rmem_max", values[2]); 2639 FileUtils.stringToFile(prefix + "wmem_min", values[3]); 2640 FileUtils.stringToFile(prefix + "wmem_def", values[4]); 2641 FileUtils.stringToFile(prefix + "wmem_max", values[5]); 2642 } else { 2643 loge("Invalid buffersize string: " + bufferSizes); 2644 } 2645 } catch (IOException e) { 2646 loge("Can't set tcp buffer sizes:" + e); 2647 } 2648 } 2649 2650 /** 2651 * Adjust the per-process dns entries (net.dns<x>.<pid>) based 2652 * on the highest priority active net which this process requested. 2653 * If there aren't any, clear it out 2654 */ 2655 private void reassessPidDns(int pid, boolean doBump) 2656 { 2657 if (VDBG) log("reassessPidDns for pid " + pid); 2658 Integer myPid = new Integer(pid); 2659 for(int i : mPriorityList) { 2660 if (mNetConfigs[i].isDefault()) { 2661 continue; 2662 } 2663 NetworkStateTracker nt = mNetTrackers[i]; 2664 if (nt.getNetworkInfo().isConnected() && 2665 !nt.isTeardownRequested()) { 2666 LinkProperties p = nt.getLinkProperties(); 2667 if (p == null) continue; 2668 if (mNetRequestersPids[i].contains(myPid)) { 2669 try { 2670 // TODO: Reimplement this via local variable in bionic. 2671 // mNetd.setDnsNetworkForPid(nt.getNetwork().netId, pid); 2672 } catch (Exception e) { 2673 Slog.e(TAG, "exception reasseses pid dns: " + e); 2674 } 2675 return; 2676 } 2677 } 2678 } 2679 // nothing found - delete 2680 try { 2681 // TODO: Reimplement this via local variable in bionic. 2682 // mNetd.clearDnsNetworkForPid(pid); 2683 } catch (Exception e) { 2684 Slog.e(TAG, "exception clear interface from pid: " + e); 2685 } 2686 } 2687 2688 private void flushVmDnsCache() { 2689 /* 2690 * Tell the VMs to toss their DNS caches 2691 */ 2692 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE); 2693 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 2694 /* 2695 * Connectivity events can happen before boot has completed ... 2696 */ 2697 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 2698 final long ident = Binder.clearCallingIdentity(); 2699 try { 2700 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 2701 } finally { 2702 Binder.restoreCallingIdentity(ident); 2703 } 2704 } 2705 2706 // Caller must grab mDnsLock. 2707 private void updateDnsLocked(String network, int netId, 2708 Collection<InetAddress> dnses, String domains) { 2709 int last = 0; 2710 if (dnses.size() == 0 && mDefaultDns != null) { 2711 dnses = new ArrayList(); 2712 dnses.add(mDefaultDns); 2713 if (DBG) { 2714 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress()); 2715 } 2716 } 2717 2718 try { 2719 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), domains); 2720 2721 for (InetAddress dns : dnses) { 2722 ++last; 2723 String key = "net.dns" + last; 2724 String value = dns.getHostAddress(); 2725 SystemProperties.set(key, value); 2726 } 2727 for (int i = last + 1; i <= mNumDnsEntries; ++i) { 2728 String key = "net.dns" + i; 2729 SystemProperties.set(key, ""); 2730 } 2731 mNumDnsEntries = last; 2732 } catch (Exception e) { 2733 loge("exception setting default dns interface: " + e); 2734 } 2735 } 2736 2737 private void handleDnsConfigurationChange(int netType) { 2738 // add default net's dns entries 2739 NetworkStateTracker nt = mNetTrackers[netType]; 2740 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) { 2741 LinkProperties p = nt.getLinkProperties(); 2742 if (p == null) return; 2743 Collection<InetAddress> dnses = p.getDnses(); 2744 int netId = nt.getNetwork().netId; 2745 if (mNetConfigs[netType].isDefault()) { 2746 String network = nt.getNetworkInfo().getTypeName(); 2747 synchronized (mDnsLock) { 2748 updateDnsLocked(network, netId, dnses, p.getDomains()); 2749 } 2750 } else { 2751 try { 2752 mNetd.setDnsServersForNetwork(netId, 2753 NetworkUtils.makeStrings(dnses), p.getDomains()); 2754 } catch (Exception e) { 2755 if (DBG) loge("exception setting dns servers: " + e); 2756 } 2757 // set per-pid dns for attached secondary nets 2758 List<Integer> pids = mNetRequestersPids[netType]; 2759 for (Integer pid : pids) { 2760 try { 2761 // TODO: Reimplement this via local variable in bionic. 2762 // mNetd.setDnsNetworkForPid(netId, pid); 2763 } catch (Exception e) { 2764 Slog.e(TAG, "exception setting interface for pid: " + e); 2765 } 2766 } 2767 } 2768 flushVmDnsCache(); 2769 } 2770 } 2771 2772 private int getRestoreDefaultNetworkDelay(int networkType) { 2773 String restoreDefaultNetworkDelayStr = SystemProperties.get( 2774 NETWORK_RESTORE_DELAY_PROP_NAME); 2775 if(restoreDefaultNetworkDelayStr != null && 2776 restoreDefaultNetworkDelayStr.length() != 0) { 2777 try { 2778 return Integer.valueOf(restoreDefaultNetworkDelayStr); 2779 } catch (NumberFormatException e) { 2780 } 2781 } 2782 // if the system property isn't set, use the value for the apn type 2783 int ret = RESTORE_DEFAULT_NETWORK_DELAY; 2784 2785 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) && 2786 (mNetConfigs[networkType] != null)) { 2787 ret = mNetConfigs[networkType].restoreTime; 2788 } 2789 return ret; 2790 } 2791 2792 @Override 2793 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) { 2794 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); 2795 if (mContext.checkCallingOrSelfPermission( 2796 android.Manifest.permission.DUMP) 2797 != PackageManager.PERMISSION_GRANTED) { 2798 pw.println("Permission Denial: can't dump ConnectivityService " + 2799 "from from pid=" + Binder.getCallingPid() + ", uid=" + 2800 Binder.getCallingUid()); 2801 return; 2802 } 2803 2804 // TODO: add locking to get atomic snapshot 2805 pw.println(); 2806 for (int i = 0; i < mNetTrackers.length; i++) { 2807 final NetworkStateTracker nst = mNetTrackers[i]; 2808 if (nst != null) { 2809 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":"); 2810 pw.increaseIndent(); 2811 if (nst.getNetworkInfo().isConnected()) { 2812 pw.println("Active network: " + nst.getNetworkInfo(). 2813 getTypeName()); 2814 } 2815 pw.println(nst.getNetworkInfo()); 2816 pw.println(nst.getLinkProperties()); 2817 pw.println(nst); 2818 pw.println(); 2819 pw.decreaseIndent(); 2820 } 2821 } 2822 2823 pw.print("Active default network: "); pw.println(getNetworkTypeName(mActiveDefaultNetwork)); 2824 pw.println(); 2825 2826 pw.println("Network Requester Pids:"); 2827 pw.increaseIndent(); 2828 for (int net : mPriorityList) { 2829 String pidString = net + ": "; 2830 for (Integer pid : mNetRequestersPids[net]) { 2831 pidString = pidString + pid.toString() + ", "; 2832 } 2833 pw.println(pidString); 2834 } 2835 pw.println(); 2836 pw.decreaseIndent(); 2837 2838 pw.println("FeatureUsers:"); 2839 pw.increaseIndent(); 2840 for (Object requester : mFeatureUsers) { 2841 pw.println(requester.toString()); 2842 } 2843 pw.println(); 2844 pw.decreaseIndent(); 2845 2846 synchronized (this) { 2847 pw.println("NetworkTranstionWakeLock is currently " + 2848 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held."); 2849 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy); 2850 } 2851 pw.println(); 2852 2853 mTethering.dump(fd, pw, args); 2854 2855 if (mInetLog != null) { 2856 pw.println(); 2857 pw.println("Inet condition reports:"); 2858 pw.increaseIndent(); 2859 for(int i = 0; i < mInetLog.size(); i++) { 2860 pw.println(mInetLog.get(i)); 2861 } 2862 pw.decreaseIndent(); 2863 } 2864 } 2865 2866 // must be stateless - things change under us. 2867 private class NetworkStateTrackerHandler extends Handler { 2868 public NetworkStateTrackerHandler(Looper looper) { 2869 super(looper); 2870 } 2871 2872 @Override 2873 public void handleMessage(Message msg) { 2874 NetworkInfo info; 2875 switch (msg.what) { 2876 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: { 2877 handleAsyncChannelHalfConnect(msg); 2878 break; 2879 } 2880 case AsyncChannel.CMD_CHANNEL_DISCONNECT: { 2881 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 2882 if (nai != null) nai.asyncChannel.disconnect(); 2883 break; 2884 } 2885 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: { 2886 handleAsyncChannelDisconnected(msg); 2887 break; 2888 } 2889 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: { 2890 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 2891 if (nai == null) { 2892 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent"); 2893 } else { 2894 updateCapabilities(nai, (NetworkCapabilities)msg.obj); 2895 } 2896 break; 2897 } 2898 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: { 2899 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 2900 if (nai == null) { 2901 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED"); 2902 } else { 2903 LinkProperties oldLp = nai.linkProperties; 2904 nai.linkProperties = (LinkProperties)msg.obj; 2905 updateLinkProperties(nai, oldLp); 2906 } 2907 break; 2908 } 2909 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: { 2910 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 2911 if (nai == null) { 2912 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent"); 2913 break; 2914 } 2915 info = (NetworkInfo) msg.obj; 2916 updateNetworkInfo(nai, info); 2917 break; 2918 } 2919 case NetworkMonitor.EVENT_NETWORK_VALIDATED: { 2920 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj; 2921 handleConnectionValidated(nai); 2922 break; 2923 } 2924 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: { 2925 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj; 2926 handleLingerComplete(nai); 2927 break; 2928 } 2929 case NetworkStateTracker.EVENT_STATE_CHANGED: { 2930 info = (NetworkInfo) msg.obj; 2931 NetworkInfo.State state = info.getState(); 2932 2933 if (VDBG || (state == NetworkInfo.State.CONNECTED) || 2934 (state == NetworkInfo.State.DISCONNECTED) || 2935 (state == NetworkInfo.State.SUSPENDED)) { 2936 log("ConnectivityChange for " + 2937 info.getTypeName() + ": " + 2938 state + "/" + info.getDetailedState()); 2939 } 2940 2941 // Since mobile has the notion of a network/apn that can be used for 2942 // provisioning we need to check every time we're connected as 2943 // CaptiveProtalTracker won't detected it because DCT doesn't report it 2944 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its 2945 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which 2946 // is received by MDST and sent here as EVENT_STATE_CHANGED. 2947 if (ConnectivityManager.isNetworkTypeMobile(info.getType()) 2948 && (0 != Settings.Global.getInt(mContext.getContentResolver(), 2949 Settings.Global.DEVICE_PROVISIONED, 0)) 2950 && (((state == NetworkInfo.State.CONNECTED) 2951 && (info.getType() == ConnectivityManager.TYPE_MOBILE)) 2952 || info.isConnectedToProvisioningNetwork())) { 2953 log("ConnectivityChange checkMobileProvisioning for" 2954 + " TYPE_MOBILE or ProvisioningNetwork"); 2955 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS); 2956 } 2957 2958 EventLogTags.writeConnectivityStateChanged( 2959 info.getType(), info.getSubtype(), info.getDetailedState().ordinal()); 2960 2961 if (info.isConnectedToProvisioningNetwork()) { 2962 /** 2963 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING 2964 * for now its an in between network, its a network that 2965 * is actually a default network but we don't want it to be 2966 * announced as such to keep background applications from 2967 * trying to use it. It turns out that some still try so we 2968 * take the additional step of clearing any default routes 2969 * to the link that may have incorrectly setup by the lower 2970 * levels. 2971 */ 2972 LinkProperties lp = getLinkProperties(info.getType()); 2973 if (DBG) { 2974 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp); 2975 } 2976 2977 // Clear any default routes setup by the radio so 2978 // any activity by applications trying to use this 2979 // connection will fail until the provisioning network 2980 // is enabled. 2981 for (RouteInfo r : lp.getRoutes()) { 2982 removeRoute(lp, r, TO_DEFAULT_TABLE, 2983 mNetTrackers[info.getType()].getNetwork().netId); 2984 } 2985 } else if (state == NetworkInfo.State.DISCONNECTED) { 2986 } else if (state == NetworkInfo.State.SUSPENDED) { 2987 } else if (state == NetworkInfo.State.CONNECTED) { 2988 // handleConnect(info); 2989 } 2990 if (mLockdownTracker != null) { 2991 mLockdownTracker.onNetworkInfoChanged(info); 2992 } 2993 break; 2994 } 2995 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: { 2996 info = (NetworkInfo) msg.obj; 2997 // TODO: Temporary allowing network configuration 2998 // change not resetting sockets. 2999 // @see bug/4455071 3000 handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()], 3001 false); 3002 break; 3003 } 3004 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: { 3005 info = (NetworkInfo) msg.obj; 3006 int type = info.getType(); 3007 if (mNetConfigs[type].isDefault()) updateNetworkSettings(mNetTrackers[type]); 3008 break; 3009 } 3010 } 3011 } 3012 } 3013 3014 private void handleAsyncChannelHalfConnect(Message msg) { 3015 AsyncChannel ac = (AsyncChannel) msg.obj; 3016 if (mNetworkFactories.contains(ac)) { 3017 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 3018 if (VDBG) log("NetworkFactory connected"); 3019 // A network factory has connected. Send it all current NetworkRequests. 3020 for (int i = 0; i < mNetworkRequests.size(); i++) { 3021 NetworkRequest request = mNetworkRequests.valueAt(i); 3022 NetworkAgentInfo nai = mNetworkForRequestId.get(request.requestId); 3023 ac.sendMessage(NetworkFactoryProtocol.CMD_REQUEST_NETWORK, 3024 (nai != null ? nai.currentScore : 0), 0, request); 3025 } 3026 } else { 3027 loge("Error connecting NetworkFactory"); 3028 mNetworkFactories.remove(ac); 3029 } 3030 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) { 3031 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 3032 if (VDBG) log("NetworkAgent connected"); 3033 // A network agent has requested a connection. Establish the connection. 3034 mNetworkAgentInfos.get(msg.replyTo).asyncChannel. 3035 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION); 3036 } else { 3037 loge("Error connecting NetworkAgent"); 3038 mNetworkAgentInfos.remove(msg.replyTo); 3039 } 3040 } 3041 } 3042 private void handleAsyncChannelDisconnected(Message msg) { 3043 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3044 if (nai != null) { 3045 if (DBG) log(nai.name() + " got DISCONNECTED"); 3046 // A network agent has disconnected. 3047 // Tell netd to clean up the configuration for this network 3048 // (routing rules, DNS, etc). 3049 try { 3050 mNetd.removeNetwork(nai.network.netId); 3051 } catch (Exception e) { 3052 loge("Exception removing network: " + e); 3053 } 3054 notifyNetworkCallbacks(nai, NetworkCallbacks.LOST); 3055 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED); 3056 mNetworkAgentInfos.remove(msg.replyTo); 3057 updateClat(null, nai.linkProperties, nai); 3058 // Since we've lost the network, go through all the requests that 3059 // it was satisfying and see if any other factory can satisfy them. 3060 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>(); 3061 for (int i = 0; i < nai.networkRequests.size(); i++) { 3062 NetworkRequest request = nai.networkRequests.valueAt(i); 3063 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId); 3064 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) { 3065 mNetworkForRequestId.remove(request.requestId); 3066 sendUpdatedScoreToFactories(request, 0); 3067 NetworkAgentInfo alternative = null; 3068 for (Map.Entry entry : mNetworkAgentInfos.entrySet()) { 3069 NetworkAgentInfo existing = (NetworkAgentInfo)entry.getValue(); 3070 if (existing.networkInfo.isConnected() && 3071 request.networkCapabilities.satisfiedByNetworkCapabilities( 3072 existing.networkCapabilities) && 3073 (alternative == null || 3074 alternative.currentScore < existing.currentScore)) { 3075 alternative = existing; 3076 } 3077 } 3078 if (alternative != null && !toActivate.contains(alternative)) { 3079 toActivate.add(alternative); 3080 } 3081 } 3082 } 3083 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 3084 removeDataActivityTracking(nai); 3085 } 3086 for (NetworkAgentInfo networkToActivate : toActivate) { 3087 networkToActivate.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 3088 } 3089 } 3090 } 3091 3092 3093 private class InternalHandler extends Handler { 3094 public InternalHandler(Looper looper) { 3095 super(looper); 3096 } 3097 3098 @Override 3099 public void handleMessage(Message msg) { 3100 NetworkInfo info; 3101 switch (msg.what) { 3102 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: { 3103 String causedBy = null; 3104 synchronized (ConnectivityService.this) { 3105 if (msg.arg1 == mNetTransitionWakeLockSerialNumber && 3106 mNetTransitionWakeLock.isHeld()) { 3107 mNetTransitionWakeLock.release(); 3108 causedBy = mNetTransitionWakeLockCausedBy; 3109 } 3110 } 3111 if (causedBy != null) { 3112 log("NetTransition Wakelock for " + causedBy + " released by timeout"); 3113 } 3114 break; 3115 } 3116 case EVENT_RESTORE_DEFAULT_NETWORK: { 3117 FeatureUser u = (FeatureUser)msg.obj; 3118 u.expire(); 3119 break; 3120 } 3121 case EVENT_INET_CONDITION_CHANGE: { 3122 int netType = msg.arg1; 3123 int condition = msg.arg2; 3124 handleInetConditionChange(netType, condition); 3125 break; 3126 } 3127 case EVENT_INET_CONDITION_HOLD_END: { 3128 int netType = msg.arg1; 3129 int sequence = msg.arg2; 3130 handleInetConditionHoldEnd(netType, sequence); 3131 break; 3132 } 3133 case EVENT_SET_MOBILE_DATA: { 3134 boolean enabled = (msg.arg1 == ENABLED); 3135 handleSetMobileData(enabled); 3136 break; 3137 } 3138 case EVENT_APPLY_GLOBAL_HTTP_PROXY: { 3139 handleDeprecatedGlobalHttpProxy(); 3140 break; 3141 } 3142 case EVENT_SET_DEPENDENCY_MET: { 3143 boolean met = (msg.arg1 == ENABLED); 3144 handleSetDependencyMet(msg.arg2, met); 3145 break; 3146 } 3147 case EVENT_SEND_STICKY_BROADCAST_INTENT: { 3148 Intent intent = (Intent)msg.obj; 3149 sendStickyBroadcast(intent); 3150 break; 3151 } 3152 case EVENT_SET_POLICY_DATA_ENABLE: { 3153 final int networkType = msg.arg1; 3154 final boolean enabled = msg.arg2 == ENABLED; 3155 handleSetPolicyDataEnable(networkType, enabled); 3156 break; 3157 } 3158 case EVENT_VPN_STATE_CHANGED: { 3159 if (mLockdownTracker != null) { 3160 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj); 3161 } 3162 break; 3163 } 3164 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: { 3165 int tag = mEnableFailFastMobileDataTag.get(); 3166 if (msg.arg1 == tag) { 3167 MobileDataStateTracker mobileDst = 3168 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 3169 if (mobileDst != null) { 3170 mobileDst.setEnableFailFastMobileData(msg.arg2); 3171 } 3172 } else { 3173 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1 3174 + " != tag:" + tag); 3175 } 3176 break; 3177 } 3178 case EVENT_SAMPLE_INTERVAL_ELAPSED: { 3179 handleNetworkSamplingTimeout(); 3180 break; 3181 } 3182 case EVENT_PROXY_HAS_CHANGED: { 3183 handleApplyDefaultProxy((ProxyInfo)msg.obj); 3184 break; 3185 } 3186 case EVENT_REGISTER_NETWORK_FACTORY: { 3187 handleRegisterNetworkFactory((Messenger)msg.obj); 3188 break; 3189 } 3190 case EVENT_REGISTER_NETWORK_AGENT: { 3191 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj); 3192 break; 3193 } 3194 } 3195 } 3196 } 3197 3198 // javadoc from interface 3199 public int tether(String iface) { 3200 enforceTetherChangePermission(); 3201 3202 if (isTetheringSupported()) { 3203 return mTethering.tether(iface); 3204 } else { 3205 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3206 } 3207 } 3208 3209 // javadoc from interface 3210 public int untether(String iface) { 3211 enforceTetherChangePermission(); 3212 3213 if (isTetheringSupported()) { 3214 return mTethering.untether(iface); 3215 } else { 3216 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3217 } 3218 } 3219 3220 // javadoc from interface 3221 public int getLastTetherError(String iface) { 3222 enforceTetherAccessPermission(); 3223 3224 if (isTetheringSupported()) { 3225 return mTethering.getLastTetherError(iface); 3226 } else { 3227 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3228 } 3229 } 3230 3231 // TODO - proper iface API for selection by property, inspection, etc 3232 public String[] getTetherableUsbRegexs() { 3233 enforceTetherAccessPermission(); 3234 if (isTetheringSupported()) { 3235 return mTethering.getTetherableUsbRegexs(); 3236 } else { 3237 return new String[0]; 3238 } 3239 } 3240 3241 public String[] getTetherableWifiRegexs() { 3242 enforceTetherAccessPermission(); 3243 if (isTetheringSupported()) { 3244 return mTethering.getTetherableWifiRegexs(); 3245 } else { 3246 return new String[0]; 3247 } 3248 } 3249 3250 public String[] getTetherableBluetoothRegexs() { 3251 enforceTetherAccessPermission(); 3252 if (isTetheringSupported()) { 3253 return mTethering.getTetherableBluetoothRegexs(); 3254 } else { 3255 return new String[0]; 3256 } 3257 } 3258 3259 public int setUsbTethering(boolean enable) { 3260 enforceTetherChangePermission(); 3261 if (isTetheringSupported()) { 3262 return mTethering.setUsbTethering(enable); 3263 } else { 3264 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3265 } 3266 } 3267 3268 // TODO - move iface listing, queries, etc to new module 3269 // javadoc from interface 3270 public String[] getTetherableIfaces() { 3271 enforceTetherAccessPermission(); 3272 return mTethering.getTetherableIfaces(); 3273 } 3274 3275 public String[] getTetheredIfaces() { 3276 enforceTetherAccessPermission(); 3277 return mTethering.getTetheredIfaces(); 3278 } 3279 3280 public String[] getTetheringErroredIfaces() { 3281 enforceTetherAccessPermission(); 3282 return mTethering.getErroredIfaces(); 3283 } 3284 3285 // if ro.tether.denied = true we default to no tethering 3286 // gservices could set the secure setting to 1 though to enable it on a build where it 3287 // had previously been turned off. 3288 public boolean isTetheringSupported() { 3289 enforceTetherAccessPermission(); 3290 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 3291 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(), 3292 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0); 3293 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 || 3294 mTethering.getTetherableWifiRegexs().length != 0 || 3295 mTethering.getTetherableBluetoothRegexs().length != 0) && 3296 mTethering.getUpstreamIfaceTypes().length != 0); 3297 } 3298 3299 // An API NetworkStateTrackers can call when they lose their network. 3300 // This will automatically be cleared after X seconds or a network becomes CONNECTED, 3301 // whichever happens first. The timer is started by the first caller and not 3302 // restarted by subsequent callers. 3303 public void requestNetworkTransitionWakelock(String forWhom) { 3304 enforceConnectivityInternalPermission(); 3305 synchronized (this) { 3306 if (mNetTransitionWakeLock.isHeld()) return; 3307 mNetTransitionWakeLockSerialNumber++; 3308 mNetTransitionWakeLock.acquire(); 3309 mNetTransitionWakeLockCausedBy = forWhom; 3310 } 3311 mHandler.sendMessageDelayed(mHandler.obtainMessage( 3312 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 3313 mNetTransitionWakeLockSerialNumber, 0), 3314 mNetTransitionWakeLockTimeout); 3315 return; 3316 } 3317 3318 // 100 percent is full good, 0 is full bad. 3319 public void reportInetCondition(int networkType, int percentage) { 3320 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")"); 3321 mContext.enforceCallingOrSelfPermission( 3322 android.Manifest.permission.STATUS_BAR, 3323 "ConnectivityService"); 3324 3325 if (DBG) { 3326 int pid = getCallingPid(); 3327 int uid = getCallingUid(); 3328 String s = pid + "(" + uid + ") reports inet is " + 3329 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " + 3330 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime(); 3331 mInetLog.add(s); 3332 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) { 3333 mInetLog.remove(0); 3334 } 3335 } 3336 mHandler.sendMessage(mHandler.obtainMessage( 3337 EVENT_INET_CONDITION_CHANGE, networkType, percentage)); 3338 } 3339 3340 private void handleInetConditionChange(int netType, int condition) { 3341 if (mActiveDefaultNetwork == -1) { 3342 if (DBG) log("handleInetConditionChange: no active default network - ignore"); 3343 return; 3344 } 3345 if (mActiveDefaultNetwork != netType) { 3346 if (DBG) log("handleInetConditionChange: net=" + netType + 3347 " != default=" + mActiveDefaultNetwork + " - ignore"); 3348 return; 3349 } 3350 if (VDBG) { 3351 log("handleInetConditionChange: net=" + 3352 netType + ", condition=" + condition + 3353 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork); 3354 } 3355 mDefaultInetCondition = condition; 3356 int delay; 3357 if (mInetConditionChangeInFlight == false) { 3358 if (VDBG) log("handleInetConditionChange: starting a change hold"); 3359 // setup a new hold to debounce this 3360 if (mDefaultInetCondition > 50) { 3361 delay = Settings.Global.getInt(mContext.getContentResolver(), 3362 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500); 3363 } else { 3364 delay = Settings.Global.getInt(mContext.getContentResolver(), 3365 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000); 3366 } 3367 mInetConditionChangeInFlight = true; 3368 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END, 3369 mActiveDefaultNetwork, mDefaultConnectionSequence), delay); 3370 } else { 3371 // we've set the new condition, when this hold ends that will get picked up 3372 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt"); 3373 } 3374 } 3375 3376 private void handleInetConditionHoldEnd(int netType, int sequence) { 3377 if (DBG) { 3378 log("handleInetConditionHoldEnd: net=" + netType + 3379 ", condition=" + mDefaultInetCondition + 3380 ", published condition=" + mDefaultInetConditionPublished); 3381 } 3382 mInetConditionChangeInFlight = false; 3383 3384 if (mActiveDefaultNetwork == -1) { 3385 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring"); 3386 return; 3387 } 3388 if (mDefaultConnectionSequence != sequence) { 3389 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring"); 3390 return; 3391 } 3392 // TODO: Figure out why this optimization sometimes causes a 3393 // change in mDefaultInetCondition to be missed and the 3394 // UI to not be updated. 3395 //if (mDefaultInetConditionPublished == mDefaultInetCondition) { 3396 // if (DBG) log("no change in condition - aborting"); 3397 // return; 3398 //} 3399 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(); 3400 if (networkInfo.isConnected() == false) { 3401 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring"); 3402 return; 3403 } 3404 mDefaultInetConditionPublished = mDefaultInetCondition; 3405 sendInetConditionBroadcast(networkInfo); 3406 return; 3407 } 3408 3409 public ProxyInfo getProxy() { 3410 // this information is already available as a world read/writable jvm property 3411 // so this API change wouldn't have a benifit. It also breaks the passing 3412 // of proxy info to all the JVMs. 3413 // enforceAccessPermission(); 3414 synchronized (mProxyLock) { 3415 ProxyInfo ret = mGlobalProxy; 3416 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy; 3417 return ret; 3418 } 3419 } 3420 3421 public void setGlobalProxy(ProxyInfo proxyProperties) { 3422 enforceConnectivityInternalPermission(); 3423 3424 synchronized (mProxyLock) { 3425 if (proxyProperties == mGlobalProxy) return; 3426 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return; 3427 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return; 3428 3429 String host = ""; 3430 int port = 0; 3431 String exclList = ""; 3432 String pacFileUrl = ""; 3433 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) || 3434 (proxyProperties.getPacFileUrl() != null))) { 3435 if (!proxyProperties.isValid()) { 3436 if (DBG) 3437 log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3438 return; 3439 } 3440 mGlobalProxy = new ProxyInfo(proxyProperties); 3441 host = mGlobalProxy.getHost(); 3442 port = mGlobalProxy.getPort(); 3443 exclList = mGlobalProxy.getExclusionListAsString(); 3444 if (proxyProperties.getPacFileUrl() != null) { 3445 pacFileUrl = proxyProperties.getPacFileUrl().toString(); 3446 } 3447 } else { 3448 mGlobalProxy = null; 3449 } 3450 ContentResolver res = mContext.getContentResolver(); 3451 final long token = Binder.clearCallingIdentity(); 3452 try { 3453 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host); 3454 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port); 3455 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 3456 exclList); 3457 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl); 3458 } finally { 3459 Binder.restoreCallingIdentity(token); 3460 } 3461 } 3462 3463 if (mGlobalProxy == null) { 3464 proxyProperties = mDefaultProxy; 3465 } 3466 sendProxyBroadcast(proxyProperties); 3467 } 3468 3469 private void loadGlobalProxy() { 3470 ContentResolver res = mContext.getContentResolver(); 3471 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST); 3472 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0); 3473 String exclList = Settings.Global.getString(res, 3474 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST); 3475 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC); 3476 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) { 3477 ProxyInfo proxyProperties; 3478 if (!TextUtils.isEmpty(pacFileUrl)) { 3479 proxyProperties = new ProxyInfo(pacFileUrl); 3480 } else { 3481 proxyProperties = new ProxyInfo(host, port, exclList); 3482 } 3483 if (!proxyProperties.isValid()) { 3484 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3485 return; 3486 } 3487 3488 synchronized (mProxyLock) { 3489 mGlobalProxy = proxyProperties; 3490 } 3491 } 3492 } 3493 3494 public ProxyInfo getGlobalProxy() { 3495 // this information is already available as a world read/writable jvm property 3496 // so this API change wouldn't have a benifit. It also breaks the passing 3497 // of proxy info to all the JVMs. 3498 // enforceAccessPermission(); 3499 synchronized (mProxyLock) { 3500 return mGlobalProxy; 3501 } 3502 } 3503 3504 private void handleApplyDefaultProxy(ProxyInfo proxy) { 3505 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 3506 && (proxy.getPacFileUrl() == null)) { 3507 proxy = null; 3508 } 3509 synchronized (mProxyLock) { 3510 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return; 3511 if (mDefaultProxy == proxy) return; // catches repeated nulls 3512 if (proxy != null && !proxy.isValid()) { 3513 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString()); 3514 return; 3515 } 3516 3517 // This call could be coming from the PacManager, containing the port of the local 3518 // proxy. If this new proxy matches the global proxy then copy this proxy to the 3519 // global (to get the correct local port), and send a broadcast. 3520 // TODO: Switch PacManager to have its own message to send back rather than 3521 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy. 3522 if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null) 3523 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) { 3524 mGlobalProxy = proxy; 3525 sendProxyBroadcast(mGlobalProxy); 3526 return; 3527 } 3528 mDefaultProxy = proxy; 3529 3530 if (mGlobalProxy != null) return; 3531 if (!mDefaultProxyDisabled) { 3532 sendProxyBroadcast(proxy); 3533 } 3534 } 3535 } 3536 3537 private void handleDeprecatedGlobalHttpProxy() { 3538 String proxy = Settings.Global.getString(mContext.getContentResolver(), 3539 Settings.Global.HTTP_PROXY); 3540 if (!TextUtils.isEmpty(proxy)) { 3541 String data[] = proxy.split(":"); 3542 if (data.length == 0) { 3543 return; 3544 } 3545 3546 String proxyHost = data[0]; 3547 int proxyPort = 8080; 3548 if (data.length > 1) { 3549 try { 3550 proxyPort = Integer.parseInt(data[1]); 3551 } catch (NumberFormatException e) { 3552 return; 3553 } 3554 } 3555 ProxyInfo p = new ProxyInfo(data[0], proxyPort, ""); 3556 setGlobalProxy(p); 3557 } 3558 } 3559 3560 private void sendProxyBroadcast(ProxyInfo proxy) { 3561 if (proxy == null) proxy = new ProxyInfo("", 0, ""); 3562 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return; 3563 if (DBG) log("sending Proxy Broadcast for " + proxy); 3564 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); 3565 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 3566 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3567 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy); 3568 final long ident = Binder.clearCallingIdentity(); 3569 try { 3570 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 3571 } finally { 3572 Binder.restoreCallingIdentity(ident); 3573 } 3574 } 3575 3576 private static class SettingsObserver extends ContentObserver { 3577 private int mWhat; 3578 private Handler mHandler; 3579 SettingsObserver(Handler handler, int what) { 3580 super(handler); 3581 mHandler = handler; 3582 mWhat = what; 3583 } 3584 3585 void observe(Context context) { 3586 ContentResolver resolver = context.getContentResolver(); 3587 resolver.registerContentObserver(Settings.Global.getUriFor( 3588 Settings.Global.HTTP_PROXY), false, this); 3589 } 3590 3591 @Override 3592 public void onChange(boolean selfChange) { 3593 mHandler.obtainMessage(mWhat).sendToTarget(); 3594 } 3595 } 3596 3597 private static void log(String s) { 3598 Slog.d(TAG, s); 3599 } 3600 3601 private static void loge(String s) { 3602 Slog.e(TAG, s); 3603 } 3604 3605 int convertFeatureToNetworkType(int networkType, String feature) { 3606 int usedNetworkType = networkType; 3607 3608 if(networkType == ConnectivityManager.TYPE_MOBILE) { 3609 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) { 3610 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS; 3611 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) { 3612 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL; 3613 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) || 3614 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) { 3615 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN; 3616 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) { 3617 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI; 3618 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) { 3619 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA; 3620 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) { 3621 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS; 3622 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) { 3623 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS; 3624 } else { 3625 Slog.e(TAG, "Can't match any mobile netTracker!"); 3626 } 3627 } else if (networkType == ConnectivityManager.TYPE_WIFI) { 3628 if (TextUtils.equals(feature, "p2p")) { 3629 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P; 3630 } else { 3631 Slog.e(TAG, "Can't match any wifi netTracker!"); 3632 } 3633 } else { 3634 Slog.e(TAG, "Unexpected network type"); 3635 } 3636 return usedNetworkType; 3637 } 3638 3639 private static <T> T checkNotNull(T value, String message) { 3640 if (value == null) { 3641 throw new NullPointerException(message); 3642 } 3643 return value; 3644 } 3645 3646 /** 3647 * Protect a socket from VPN routing rules. This method is used by 3648 * VpnBuilder and not available in ConnectivityManager. Permissions 3649 * are checked in Vpn class. 3650 * @hide 3651 */ 3652 @Override 3653 public boolean protectVpn(ParcelFileDescriptor socket) { 3654 throwIfLockdownEnabled(); 3655 try { 3656 int type = mActiveDefaultNetwork; 3657 int user = UserHandle.getUserId(Binder.getCallingUid()); 3658 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) { 3659 synchronized(mVpns) { 3660 mVpns.get(user).protect(socket); 3661 } 3662 return true; 3663 } 3664 } catch (Exception e) { 3665 // ignore 3666 } finally { 3667 try { 3668 socket.close(); 3669 } catch (Exception e) { 3670 // ignore 3671 } 3672 } 3673 return false; 3674 } 3675 3676 /** 3677 * Prepare for a VPN application. This method is used by VpnDialogs 3678 * and not available in ConnectivityManager. Permissions are checked 3679 * in Vpn class. 3680 * @hide 3681 */ 3682 @Override 3683 public boolean prepareVpn(String oldPackage, String newPackage) { 3684 throwIfLockdownEnabled(); 3685 int user = UserHandle.getUserId(Binder.getCallingUid()); 3686 synchronized(mVpns) { 3687 return mVpns.get(user).prepare(oldPackage, newPackage); 3688 } 3689 } 3690 3691 @Override 3692 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) { 3693 enforceMarkNetworkSocketPermission(); 3694 final long token = Binder.clearCallingIdentity(); 3695 try { 3696 int mark = mNetd.getMarkForUid(uid); 3697 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues 3698 if (mark == -1) { 3699 mark = 0; 3700 } 3701 NetworkUtils.markSocket(socket.getFd(), mark); 3702 } catch (RemoteException e) { 3703 } finally { 3704 Binder.restoreCallingIdentity(token); 3705 } 3706 } 3707 3708 /** 3709 * Configure a TUN interface and return its file descriptor. Parameters 3710 * are encoded and opaque to this class. This method is used by VpnBuilder 3711 * and not available in ConnectivityManager. Permissions are checked in 3712 * Vpn class. 3713 * @hide 3714 */ 3715 @Override 3716 public ParcelFileDescriptor establishVpn(VpnConfig config) { 3717 throwIfLockdownEnabled(); 3718 int user = UserHandle.getUserId(Binder.getCallingUid()); 3719 synchronized(mVpns) { 3720 return mVpns.get(user).establish(config); 3721 } 3722 } 3723 3724 /** 3725 * Start legacy VPN, controlling native daemons as needed. Creates a 3726 * secondary thread to perform connection work, returning quickly. 3727 */ 3728 @Override 3729 public void startLegacyVpn(VpnProfile profile) { 3730 throwIfLockdownEnabled(); 3731 final LinkProperties egress = getActiveLinkProperties(); 3732 if (egress == null) { 3733 throw new IllegalStateException("Missing active network connection"); 3734 } 3735 int user = UserHandle.getUserId(Binder.getCallingUid()); 3736 synchronized(mVpns) { 3737 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress); 3738 } 3739 } 3740 3741 /** 3742 * Return the information of the ongoing legacy VPN. This method is used 3743 * by VpnSettings and not available in ConnectivityManager. Permissions 3744 * are checked in Vpn class. 3745 * @hide 3746 */ 3747 @Override 3748 public LegacyVpnInfo getLegacyVpnInfo() { 3749 throwIfLockdownEnabled(); 3750 int user = UserHandle.getUserId(Binder.getCallingUid()); 3751 synchronized(mVpns) { 3752 return mVpns.get(user).getLegacyVpnInfo(); 3753 } 3754 } 3755 3756 /** 3757 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and 3758 * not available in ConnectivityManager. 3759 * Permissions are checked in Vpn class. 3760 * @hide 3761 */ 3762 @Override 3763 public VpnConfig getVpnConfig() { 3764 int user = UserHandle.getUserId(Binder.getCallingUid()); 3765 synchronized(mVpns) { 3766 return mVpns.get(user).getVpnConfig(); 3767 } 3768 } 3769 3770 /** 3771 * Callback for VPN subsystem. Currently VPN is not adapted to the service 3772 * through NetworkStateTracker since it works differently. For example, it 3773 * needs to override DNS servers but never takes the default routes. It 3774 * relies on another data network, and it could keep existing connections 3775 * alive after reconnecting, switching between networks, or even resuming 3776 * from deep sleep. Calls from applications should be done synchronously 3777 * to avoid race conditions. As these are all hidden APIs, refactoring can 3778 * be done whenever a better abstraction is developed. 3779 */ 3780 public class VpnCallback { 3781 private VpnCallback() { 3782 } 3783 3784 public void onStateChanged(NetworkInfo info) { 3785 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget(); 3786 } 3787 3788 public void override(String iface, List<String> dnsServers, List<String> searchDomains) { 3789 if (dnsServers == null) { 3790 restore(); 3791 return; 3792 } 3793 3794 // Convert DNS servers into addresses. 3795 List<InetAddress> addresses = new ArrayList<InetAddress>(); 3796 for (String address : dnsServers) { 3797 // Double check the addresses and remove invalid ones. 3798 try { 3799 addresses.add(InetAddress.parseNumericAddress(address)); 3800 } catch (Exception e) { 3801 // ignore 3802 } 3803 } 3804 if (addresses.isEmpty()) { 3805 restore(); 3806 return; 3807 } 3808 3809 // Concatenate search domains into a string. 3810 StringBuilder buffer = new StringBuilder(); 3811 if (searchDomains != null) { 3812 for (String domain : searchDomains) { 3813 buffer.append(domain).append(' '); 3814 } 3815 } 3816 String domains = buffer.toString().trim(); 3817 3818 // Apply DNS changes. 3819 synchronized (mDnsLock) { 3820 // TODO: Re-enable this when the netId of the VPN is known. 3821 // updateDnsLocked("VPN", netId, addresses, domains); 3822 } 3823 3824 // Temporarily disable the default proxy (not global). 3825 synchronized (mProxyLock) { 3826 mDefaultProxyDisabled = true; 3827 if (mGlobalProxy == null && mDefaultProxy != null) { 3828 sendProxyBroadcast(null); 3829 } 3830 } 3831 3832 // TODO: support proxy per network. 3833 } 3834 3835 public void restore() { 3836 synchronized (mProxyLock) { 3837 mDefaultProxyDisabled = false; 3838 if (mGlobalProxy == null && mDefaultProxy != null) { 3839 sendProxyBroadcast(mDefaultProxy); 3840 } 3841 } 3842 } 3843 3844 public void protect(ParcelFileDescriptor socket) { 3845 try { 3846 final int mark = mNetd.getMarkForProtect(); 3847 NetworkUtils.markSocket(socket.getFd(), mark); 3848 } catch (RemoteException e) { 3849 } 3850 } 3851 3852 public void setRoutes(String interfaze, List<RouteInfo> routes) { 3853 for (RouteInfo route : routes) { 3854 try { 3855 mNetd.setMarkedForwardingRoute(interfaze, route); 3856 } catch (RemoteException e) { 3857 } 3858 } 3859 } 3860 3861 public void setMarkedForwarding(String interfaze) { 3862 try { 3863 mNetd.setMarkedForwarding(interfaze); 3864 } catch (RemoteException e) { 3865 } 3866 } 3867 3868 public void clearMarkedForwarding(String interfaze) { 3869 try { 3870 mNetd.clearMarkedForwarding(interfaze); 3871 } catch (RemoteException e) { 3872 } 3873 } 3874 3875 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) { 3876 int uidStart = uid * UserHandle.PER_USER_RANGE; 3877 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1; 3878 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns); 3879 } 3880 3881 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) { 3882 int uidStart = uid * UserHandle.PER_USER_RANGE; 3883 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1; 3884 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns); 3885 } 3886 3887 public void addUidForwarding(String interfaze, int uidStart, int uidEnd, 3888 boolean forwardDns) { 3889 // TODO: Re-enable this when the netId of the VPN is known. 3890 // try { 3891 // mNetd.setUidRangeRoute(netId, uidStart, uidEnd, forwardDns); 3892 // } catch (RemoteException e) { 3893 // } 3894 3895 } 3896 3897 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd, 3898 boolean forwardDns) { 3899 // TODO: Re-enable this when the netId of the VPN is known. 3900 // try { 3901 // mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd); 3902 // } catch (RemoteException e) { 3903 // } 3904 3905 } 3906 } 3907 3908 @Override 3909 public boolean updateLockdownVpn() { 3910 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 3911 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM"); 3912 return false; 3913 } 3914 3915 // Tear down existing lockdown if profile was removed 3916 mLockdownEnabled = LockdownVpnTracker.isEnabled(); 3917 if (mLockdownEnabled) { 3918 if (!mKeyStore.isUnlocked()) { 3919 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker"); 3920 return false; 3921 } 3922 3923 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN)); 3924 final VpnProfile profile = VpnProfile.decode( 3925 profileName, mKeyStore.get(Credentials.VPN + profileName)); 3926 int user = UserHandle.getUserId(Binder.getCallingUid()); 3927 synchronized(mVpns) { 3928 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user), 3929 profile)); 3930 } 3931 } else { 3932 setLockdownTracker(null); 3933 } 3934 3935 return true; 3936 } 3937 3938 /** 3939 * Internally set new {@link LockdownVpnTracker}, shutting down any existing 3940 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown. 3941 */ 3942 private void setLockdownTracker(LockdownVpnTracker tracker) { 3943 // Shutdown any existing tracker 3944 final LockdownVpnTracker existing = mLockdownTracker; 3945 mLockdownTracker = null; 3946 if (existing != null) { 3947 existing.shutdown(); 3948 } 3949 3950 try { 3951 if (tracker != null) { 3952 mNetd.setFirewallEnabled(true); 3953 mNetd.setFirewallInterfaceRule("lo", true); 3954 mLockdownTracker = tracker; 3955 mLockdownTracker.init(); 3956 } else { 3957 mNetd.setFirewallEnabled(false); 3958 } 3959 } catch (RemoteException e) { 3960 // ignored; NMS lives inside system_server 3961 } 3962 } 3963 3964 private void throwIfLockdownEnabled() { 3965 if (mLockdownEnabled) { 3966 throw new IllegalStateException("Unavailable in lockdown mode"); 3967 } 3968 } 3969 3970 public void supplyMessenger(int networkType, Messenger messenger) { 3971 enforceConnectivityInternalPermission(); 3972 3973 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) { 3974 mNetTrackers[networkType].supplyMessenger(messenger); 3975 } 3976 } 3977 3978 public int findConnectionTypeForIface(String iface) { 3979 enforceConnectivityInternalPermission(); 3980 3981 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE; 3982 for (NetworkStateTracker tracker : mNetTrackers) { 3983 if (tracker != null) { 3984 LinkProperties lp = tracker.getLinkProperties(); 3985 if (lp != null && iface.equals(lp.getInterfaceName())) { 3986 return tracker.getNetworkInfo().getType(); 3987 } 3988 } 3989 } 3990 return ConnectivityManager.TYPE_NONE; 3991 } 3992 3993 /** 3994 * Have mobile data fail fast if enabled. 3995 * 3996 * @param enabled DctConstants.ENABLED/DISABLED 3997 */ 3998 private void setEnableFailFastMobileData(int enabled) { 3999 int tag; 4000 4001 if (enabled == DctConstants.ENABLED) { 4002 tag = mEnableFailFastMobileDataTag.incrementAndGet(); 4003 } else { 4004 tag = mEnableFailFastMobileDataTag.get(); 4005 } 4006 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag, 4007 enabled)); 4008 } 4009 4010 private boolean isMobileDataStateTrackerReady() { 4011 MobileDataStateTracker mdst = 4012 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4013 return (mdst != null) && (mdst.isReady()); 4014 } 4015 4016 /** 4017 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE) 4018 */ 4019 4020 /** 4021 * No connection was possible to the network. 4022 * This is NOT a warm sim. 4023 */ 4024 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0; 4025 4026 /** 4027 * A connection was made to the internet, all is well. 4028 * This is NOT a warm sim. 4029 */ 4030 private static final int CMP_RESULT_CODE_CONNECTABLE = 1; 4031 4032 /** 4033 * A connection was made but no dns server was available to resolve a name to address. 4034 * This is NOT a warm sim since provisioning network is supported. 4035 */ 4036 private static final int CMP_RESULT_CODE_NO_DNS = 2; 4037 4038 /** 4039 * A connection was made but could not open a TCP connection. 4040 * This is NOT a warm sim since provisioning network is supported. 4041 */ 4042 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3; 4043 4044 /** 4045 * A connection was made but there was a redirection, we appear to be in walled garden. 4046 * This is an indication of a warm sim on a mobile network such as T-Mobile. 4047 */ 4048 private static final int CMP_RESULT_CODE_REDIRECTED = 4; 4049 4050 /** 4051 * The mobile network is a provisioning network. 4052 * This is an indication of a warm sim on a mobile network such as AT&T. 4053 */ 4054 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5; 4055 4056 /** 4057 * The mobile network is provisioning 4058 */ 4059 private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6; 4060 4061 private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false); 4062 private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false); 4063 4064 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false); 4065 4066 @Override 4067 public int checkMobileProvisioning(int suggestedTimeOutMs) { 4068 int timeOutMs = -1; 4069 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs); 4070 enforceConnectivityInternalPermission(); 4071 4072 final long token = Binder.clearCallingIdentity(); 4073 try { 4074 timeOutMs = suggestedTimeOutMs; 4075 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) { 4076 timeOutMs = CheckMp.MAX_TIMEOUT_MS; 4077 } 4078 4079 // Check that mobile networks are supported 4080 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE) 4081 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) { 4082 if (DBG) log("checkMobileProvisioning: X no mobile network"); 4083 return timeOutMs; 4084 } 4085 4086 // If we're already checking don't do it again 4087 // TODO: Add a queue of results... 4088 if (mIsCheckingMobileProvisioning.getAndSet(true)) { 4089 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment"); 4090 return timeOutMs; 4091 } 4092 4093 // Start off with mobile notification off 4094 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null); 4095 4096 CheckMp checkMp = new CheckMp(mContext, this); 4097 CheckMp.CallBack cb = new CheckMp.CallBack() { 4098 @Override 4099 void onComplete(Integer result) { 4100 if (DBG) log("CheckMp.onComplete: result=" + result); 4101 NetworkInfo ni = 4102 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo(); 4103 switch(result) { 4104 case CMP_RESULT_CODE_CONNECTABLE: 4105 case CMP_RESULT_CODE_NO_CONNECTION: 4106 case CMP_RESULT_CODE_NO_DNS: 4107 case CMP_RESULT_CODE_NO_TCP_CONNECTION: { 4108 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection"); 4109 break; 4110 } 4111 case CMP_RESULT_CODE_REDIRECTED: { 4112 if (DBG) log("CheckMp.onComplete: warm sim"); 4113 String url = getMobileProvisioningUrl(); 4114 if (TextUtils.isEmpty(url)) { 4115 url = getMobileRedirectedProvisioningUrl(); 4116 } 4117 if (TextUtils.isEmpty(url) == false) { 4118 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url); 4119 setProvNotificationVisible(true, 4120 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(), 4121 url); 4122 } else { 4123 if (DBG) log("CheckMp.onComplete: warm (redirected), no url"); 4124 } 4125 break; 4126 } 4127 case CMP_RESULT_CODE_PROVISIONING_NETWORK: { 4128 String url = getMobileProvisioningUrl(); 4129 if (TextUtils.isEmpty(url) == false) { 4130 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url); 4131 setProvNotificationVisible(true, 4132 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(), 4133 url); 4134 // Mark that we've got a provisioning network and 4135 // Disable Mobile Data until user actually starts provisioning. 4136 mIsProvisioningNetwork.set(true); 4137 MobileDataStateTracker mdst = (MobileDataStateTracker) 4138 mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4139 mdst.setInternalDataEnable(false); 4140 } else { 4141 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url"); 4142 } 4143 break; 4144 } 4145 case CMP_RESULT_CODE_IS_PROVISIONING: { 4146 // FIXME: Need to know when provisioning is done. Probably we can 4147 // check the completion status if successful we're done if we 4148 // "timedout" or still connected to provisioning APN turn off data? 4149 if (DBG) log("CheckMp.onComplete: provisioning started"); 4150 mIsStartingProvisioning.set(false); 4151 break; 4152 } 4153 default: { 4154 loge("CheckMp.onComplete: ignore unexpected result=" + result); 4155 break; 4156 } 4157 } 4158 mIsCheckingMobileProvisioning.set(false); 4159 } 4160 }; 4161 CheckMp.Params params = 4162 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb); 4163 if (DBG) log("checkMobileProvisioning: params=" + params); 4164 // TODO: Reenable when calls to the now defunct 4165 // MobileDataStateTracker.isProvisioningNetwork() are removed. 4166 // This code should be moved to the Telephony code. 4167 // checkMp.execute(params); 4168 } finally { 4169 Binder.restoreCallingIdentity(token); 4170 if (DBG) log("checkMobileProvisioning: X"); 4171 } 4172 return timeOutMs; 4173 } 4174 4175 static class CheckMp extends 4176 AsyncTask<CheckMp.Params, Void, Integer> { 4177 private static final String CHECKMP_TAG = "CheckMp"; 4178 4179 // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures 4180 private static boolean mTestingFailures; 4181 4182 // Choosing 4 loops as half of them will use HTTPS and the other half HTTP 4183 private static final int MAX_LOOPS = 4; 4184 4185 // Number of milli-seconds to complete all of the retires 4186 public static final int MAX_TIMEOUT_MS = 60000; 4187 4188 // The socket should retry only 5 seconds, the default is longer 4189 private static final int SOCKET_TIMEOUT_MS = 5000; 4190 4191 // Sleep time for network errors 4192 private static final int NET_ERROR_SLEEP_SEC = 3; 4193 4194 // Sleep time for network route establishment 4195 private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3; 4196 4197 // Short sleep time for polling :( 4198 private static final int POLLING_SLEEP_SEC = 1; 4199 4200 private Context mContext; 4201 private ConnectivityService mCs; 4202 private TelephonyManager mTm; 4203 private Params mParams; 4204 4205 /** 4206 * Parameters for AsyncTask.execute 4207 */ 4208 static class Params { 4209 private String mUrl; 4210 private long mTimeOutMs; 4211 private CallBack mCb; 4212 4213 Params(String url, long timeOutMs, CallBack cb) { 4214 mUrl = url; 4215 mTimeOutMs = timeOutMs; 4216 mCb = cb; 4217 } 4218 4219 @Override 4220 public String toString() { 4221 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}"; 4222 } 4223 } 4224 4225 // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be 4226 // issued by name or ip address, for Google its by name so when we construct 4227 // this HostnameVerifier we'll pass the original Uri and use it to verify 4228 // the host. If the host name in the original uril fails we'll test the 4229 // hostname parameter just incase things change. 4230 static class CheckMpHostnameVerifier implements HostnameVerifier { 4231 Uri mOrgUri; 4232 4233 CheckMpHostnameVerifier(Uri orgUri) { 4234 mOrgUri = orgUri; 4235 } 4236 4237 @Override 4238 public boolean verify(String hostname, SSLSession session) { 4239 HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); 4240 String orgUriHost = mOrgUri.getHost(); 4241 boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session); 4242 if (DBG) { 4243 log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname 4244 + " orgUriHost=" + orgUriHost); 4245 } 4246 return retVal; 4247 } 4248 } 4249 4250 /** 4251 * The call back object passed in Params. onComplete will be called 4252 * on the main thread. 4253 */ 4254 abstract static class CallBack { 4255 // Called on the main thread. 4256 abstract void onComplete(Integer result); 4257 } 4258 4259 public CheckMp(Context context, ConnectivityService cs) { 4260 if (Build.IS_DEBUGGABLE) { 4261 mTestingFailures = 4262 SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1; 4263 } else { 4264 mTestingFailures = false; 4265 } 4266 4267 mContext = context; 4268 mCs = cs; 4269 4270 // Setup access to TelephonyService we'll be using. 4271 mTm = (TelephonyManager) mContext.getSystemService( 4272 Context.TELEPHONY_SERVICE); 4273 } 4274 4275 /** 4276 * Get the default url to use for the test. 4277 */ 4278 public String getDefaultUrl() { 4279 // See http://go/clientsdns for usage approval 4280 String server = Settings.Global.getString(mContext.getContentResolver(), 4281 Settings.Global.CAPTIVE_PORTAL_SERVER); 4282 if (server == null) { 4283 server = "clients3.google.com"; 4284 } 4285 return "http://" + server + "/generate_204"; 4286 } 4287 4288 /** 4289 * Detect if its possible to connect to the http url. DNS based detection techniques 4290 * do not work at all hotspots. The best way to check is to perform a request to 4291 * a known address that fetches the data we expect. 4292 */ 4293 private synchronized Integer isMobileOk(Params params) { 4294 Integer result = CMP_RESULT_CODE_NO_CONNECTION; 4295 Uri orgUri = Uri.parse(params.mUrl); 4296 Random rand = new Random(); 4297 mParams = params; 4298 4299 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) { 4300 result = CMP_RESULT_CODE_NO_CONNECTION; 4301 log("isMobileOk: X not mobile capable result=" + result); 4302 return result; 4303 } 4304 4305 if (mCs.mIsStartingProvisioning.get()) { 4306 result = CMP_RESULT_CODE_IS_PROVISIONING; 4307 log("isMobileOk: X is provisioning result=" + result); 4308 return result; 4309 } 4310 4311 // See if we've already determined we've got a provisioning connection, 4312 // if so we don't need to do anything active. 4313 MobileDataStateTracker mdstDefault = (MobileDataStateTracker) 4314 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4315 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork(); 4316 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning); 4317 4318 MobileDataStateTracker mdstHipri = (MobileDataStateTracker) 4319 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4320 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork(); 4321 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning); 4322 4323 if (isDefaultProvisioning || isHipriProvisioning) { 4324 result = CMP_RESULT_CODE_PROVISIONING_NETWORK; 4325 log("isMobileOk: X default || hipri is provisioning result=" + result); 4326 return result; 4327 } 4328 4329 try { 4330 // Continue trying to connect until time has run out 4331 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs; 4332 4333 if (!mCs.isMobileDataStateTrackerReady()) { 4334 // Wait for MobileDataStateTracker to be ready. 4335 if (DBG) log("isMobileOk: mdst is not ready"); 4336 while(SystemClock.elapsedRealtime() < endTime) { 4337 if (mCs.isMobileDataStateTrackerReady()) { 4338 // Enable fail fast as we'll do retries here and use a 4339 // hipri connection so the default connection stays active. 4340 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data"); 4341 mCs.setEnableFailFastMobileData(DctConstants.ENABLED); 4342 break; 4343 } 4344 sleep(POLLING_SLEEP_SEC); 4345 } 4346 } 4347 4348 log("isMobileOk: start hipri url=" + params.mUrl); 4349 4350 // First wait until we can start using hipri 4351 Binder binder = new Binder(); 4352 while(SystemClock.elapsedRealtime() < endTime) { 4353 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, 4354 Phone.FEATURE_ENABLE_HIPRI, binder); 4355 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE) 4356 || (ret == PhoneConstants.APN_REQUEST_STARTED)) { 4357 log("isMobileOk: hipri started"); 4358 break; 4359 } 4360 if (VDBG) log("isMobileOk: hipri not started yet"); 4361 result = CMP_RESULT_CODE_NO_CONNECTION; 4362 sleep(POLLING_SLEEP_SEC); 4363 } 4364 4365 // Continue trying to connect until time has run out 4366 while(SystemClock.elapsedRealtime() < endTime) { 4367 try { 4368 // Wait for hipri to connect. 4369 // TODO: Don't poll and handle situation where hipri fails 4370 // because default is retrying. See b/9569540 4371 NetworkInfo.State state = mCs 4372 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); 4373 if (state != NetworkInfo.State.CONNECTED) { 4374 if (true/*VDBG*/) { 4375 log("isMobileOk: not connected ni=" + 4376 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI)); 4377 } 4378 sleep(POLLING_SLEEP_SEC); 4379 result = CMP_RESULT_CODE_NO_CONNECTION; 4380 continue; 4381 } 4382 4383 // Hipri has started check if this is a provisioning url 4384 MobileDataStateTracker mdst = (MobileDataStateTracker) 4385 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4386 if (mdst.isProvisioningNetwork()) { 4387 result = CMP_RESULT_CODE_PROVISIONING_NETWORK; 4388 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result); 4389 return result; 4390 } else { 4391 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue"); 4392 } 4393 4394 // Get of the addresses associated with the url host. We need to use the 4395 // address otherwise HttpURLConnection object will use the name to get 4396 // the addresses and will try every address but that will bypass the 4397 // route to host we setup and the connection could succeed as the default 4398 // interface might be connected to the internet via wifi or other interface. 4399 InetAddress[] addresses; 4400 try { 4401 addresses = InetAddress.getAllByName(orgUri.getHost()); 4402 } catch (UnknownHostException e) { 4403 result = CMP_RESULT_CODE_NO_DNS; 4404 log("isMobileOk: X UnknownHostException result=" + result); 4405 return result; 4406 } 4407 log("isMobileOk: addresses=" + inetAddressesToString(addresses)); 4408 4409 // Get the type of addresses supported by this link 4410 LinkProperties lp = mCs.getLinkProperties( 4411 ConnectivityManager.TYPE_MOBILE_HIPRI); 4412 boolean linkHasIpv4 = lp.hasIPv4Address(); 4413 boolean linkHasIpv6 = lp.hasIPv6Address(); 4414 log("isMobileOk: linkHasIpv4=" + linkHasIpv4 4415 + " linkHasIpv6=" + linkHasIpv6); 4416 4417 final ArrayList<InetAddress> validAddresses = 4418 new ArrayList<InetAddress>(addresses.length); 4419 4420 for (InetAddress addr : addresses) { 4421 if (((addr instanceof Inet4Address) && linkHasIpv4) || 4422 ((addr instanceof Inet6Address) && linkHasIpv6)) { 4423 validAddresses.add(addr); 4424 } 4425 } 4426 4427 if (validAddresses.size() == 0) { 4428 return CMP_RESULT_CODE_NO_CONNECTION; 4429 } 4430 4431 int addrTried = 0; 4432 while (true) { 4433 // Loop through at most MAX_LOOPS valid addresses or until 4434 // we run out of time 4435 if (addrTried++ >= MAX_LOOPS) { 4436 log("isMobileOk: too many loops tried - giving up"); 4437 break; 4438 } 4439 if (SystemClock.elapsedRealtime() >= endTime) { 4440 log("isMobileOk: spend too much time - giving up"); 4441 break; 4442 } 4443 4444 InetAddress hostAddr = validAddresses.get(rand.nextInt( 4445 validAddresses.size())); 4446 4447 // Make a route to host so we check the specific interface. 4448 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI, 4449 hostAddr.getAddress(), null)) { 4450 // Wait a short time to be sure the route is established ?? 4451 log("isMobileOk:" 4452 + " wait to establish route to hostAddr=" + hostAddr); 4453 sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC); 4454 } else { 4455 log("isMobileOk:" 4456 + " could not establish route to hostAddr=" + hostAddr); 4457 // Wait a short time before the next attempt 4458 sleep(NET_ERROR_SLEEP_SEC); 4459 continue; 4460 } 4461 4462 // Rewrite the url to have numeric address to use the specific route 4463 // using http for half the attempts and https for the other half. 4464 // Doing https first and http second as on a redirected walled garden 4465 // such as t-mobile uses we get a SocketTimeoutException: "SSL 4466 // handshake timed out" which we declare as 4467 // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by 4468 // having http second we will be using logic used for some time. 4469 URL newUrl; 4470 String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http"; 4471 newUrl = new URL(scheme, hostAddr.getHostAddress(), 4472 orgUri.getPath()); 4473 log("isMobileOk: newUrl=" + newUrl); 4474 4475 HttpURLConnection urlConn = null; 4476 try { 4477 // Open the connection set the request headers and get the response 4478 urlConn = (HttpURLConnection)newUrl.openConnection( 4479 java.net.Proxy.NO_PROXY); 4480 if (scheme.equals("https")) { 4481 ((HttpsURLConnection)urlConn).setHostnameVerifier( 4482 new CheckMpHostnameVerifier(orgUri)); 4483 } 4484 urlConn.setInstanceFollowRedirects(false); 4485 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS); 4486 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS); 4487 urlConn.setUseCaches(false); 4488 urlConn.setAllowUserInteraction(false); 4489 // Set the "Connection" to "Close" as by default "Keep-Alive" 4490 // is used which is useless in this case. 4491 urlConn.setRequestProperty("Connection", "close"); 4492 int responseCode = urlConn.getResponseCode(); 4493 4494 // For debug display the headers 4495 Map<String, List<String>> headers = urlConn.getHeaderFields(); 4496 log("isMobileOk: headers=" + headers); 4497 4498 // Close the connection 4499 urlConn.disconnect(); 4500 urlConn = null; 4501 4502 if (mTestingFailures) { 4503 // Pretend no connection, this tests using http and https 4504 result = CMP_RESULT_CODE_NO_CONNECTION; 4505 log("isMobileOk: TESTING_FAILURES, pretend no connction"); 4506 continue; 4507 } 4508 4509 if (responseCode == 204) { 4510 // Return 4511 result = CMP_RESULT_CODE_CONNECTABLE; 4512 log("isMobileOk: X got expected responseCode=" + responseCode 4513 + " result=" + result); 4514 return result; 4515 } else { 4516 // Retry to be sure this was redirected, we've gotten 4517 // occasions where a server returned 200 even though 4518 // the device didn't have a "warm" sim. 4519 log("isMobileOk: not expected responseCode=" + responseCode); 4520 // TODO - it would be nice in the single-address case to do 4521 // another DNS resolve here, but flushing the cache is a bit 4522 // heavy-handed. 4523 result = CMP_RESULT_CODE_REDIRECTED; 4524 } 4525 } catch (Exception e) { 4526 log("isMobileOk: HttpURLConnection Exception" + e); 4527 result = CMP_RESULT_CODE_NO_TCP_CONNECTION; 4528 if (urlConn != null) { 4529 urlConn.disconnect(); 4530 urlConn = null; 4531 } 4532 sleep(NET_ERROR_SLEEP_SEC); 4533 continue; 4534 } 4535 } 4536 log("isMobileOk: X loops|timed out result=" + result); 4537 return result; 4538 } catch (Exception e) { 4539 log("isMobileOk: Exception e=" + e); 4540 continue; 4541 } 4542 } 4543 log("isMobileOk: timed out"); 4544 } finally { 4545 log("isMobileOk: F stop hipri"); 4546 mCs.setEnableFailFastMobileData(DctConstants.DISABLED); 4547 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, 4548 Phone.FEATURE_ENABLE_HIPRI); 4549 4550 // Wait for hipri to disconnect. 4551 long endTime = SystemClock.elapsedRealtime() + 5000; 4552 4553 while(SystemClock.elapsedRealtime() < endTime) { 4554 NetworkInfo.State state = mCs 4555 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); 4556 if (state != NetworkInfo.State.DISCONNECTED) { 4557 if (VDBG) { 4558 log("isMobileOk: connected ni=" + 4559 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI)); 4560 } 4561 sleep(POLLING_SLEEP_SEC); 4562 continue; 4563 } 4564 } 4565 4566 log("isMobileOk: X result=" + result); 4567 } 4568 return result; 4569 } 4570 4571 @Override 4572 protected Integer doInBackground(Params... params) { 4573 return isMobileOk(params[0]); 4574 } 4575 4576 @Override 4577 protected void onPostExecute(Integer result) { 4578 log("onPostExecute: result=" + result); 4579 if ((mParams != null) && (mParams.mCb != null)) { 4580 mParams.mCb.onComplete(result); 4581 } 4582 } 4583 4584 private String inetAddressesToString(InetAddress[] addresses) { 4585 StringBuffer sb = new StringBuffer(); 4586 boolean firstTime = true; 4587 for(InetAddress addr : addresses) { 4588 if (firstTime) { 4589 firstTime = false; 4590 } else { 4591 sb.append(","); 4592 } 4593 sb.append(addr); 4594 } 4595 return sb.toString(); 4596 } 4597 4598 private void printNetworkInfo() { 4599 boolean hasIccCard = mTm.hasIccCard(); 4600 int simState = mTm.getSimState(); 4601 log("hasIccCard=" + hasIccCard 4602 + " simState=" + simState); 4603 NetworkInfo[] ni = mCs.getAllNetworkInfo(); 4604 if (ni != null) { 4605 log("ni.length=" + ni.length); 4606 for (NetworkInfo netInfo: ni) { 4607 log("netInfo=" + netInfo.toString()); 4608 } 4609 } else { 4610 log("no network info ni=null"); 4611 } 4612 } 4613 4614 /** 4615 * Sleep for a few seconds then return. 4616 * @param seconds 4617 */ 4618 private static void sleep(int seconds) { 4619 long stopTime = System.nanoTime() + (seconds * 1000000000); 4620 long sleepTime; 4621 while ((sleepTime = stopTime - System.nanoTime()) > 0) { 4622 try { 4623 Thread.sleep(sleepTime / 1000000); 4624 } catch (InterruptedException ignored) { 4625 } 4626 } 4627 } 4628 4629 private static void log(String s) { 4630 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s); 4631 } 4632 } 4633 4634 // TODO: Move to ConnectivityManager and make public? 4635 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION = 4636 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION"; 4637 4638 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() { 4639 @Override 4640 public void onReceive(Context context, Intent intent) { 4641 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) { 4642 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL")); 4643 } 4644 } 4645 }; 4646 4647 private void handleMobileProvisioningAction(String url) { 4648 // Mark notification as not visible 4649 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null); 4650 4651 // If provisioning network handle as a special case, 4652 // otherwise launch browser with the intent directly. 4653 if (mIsProvisioningNetwork.get()) { 4654 if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch"); 4655 mIsStartingProvisioning.set(true); 4656 MobileDataStateTracker mdst = (MobileDataStateTracker) 4657 mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4658 mdst.setEnableFailFastMobileData(DctConstants.ENABLED); 4659 mdst.enableMobileProvisioning(url); 4660 } else { 4661 if (DBG) log("handleMobileProvisioningAction: not prov network"); 4662 // Check for apps that can handle provisioning first 4663 Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP); 4664 provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX 4665 + mTelephonyManager.getSimOperator()); 4666 if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */) 4667 != null) { 4668 provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 4669 Intent.FLAG_ACTIVITY_NEW_TASK); 4670 mContext.startActivity(provisioningIntent); 4671 } else { 4672 // If no apps exist, use standard URL ACTION_VIEW method 4673 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, 4674 Intent.CATEGORY_APP_BROWSER); 4675 newIntent.setData(Uri.parse(url)); 4676 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 4677 Intent.FLAG_ACTIVITY_NEW_TASK); 4678 try { 4679 mContext.startActivity(newIntent); 4680 } catch (ActivityNotFoundException e) { 4681 loge("handleMobileProvisioningAction: startActivity failed" + e); 4682 } 4683 } 4684 } 4685 } 4686 4687 private static final String NOTIFICATION_ID = "CaptivePortal.Notification"; 4688 private volatile boolean mIsNotificationVisible = false; 4689 4690 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo, 4691 String url) { 4692 if (DBG) { 4693 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType 4694 + " extraInfo=" + extraInfo + " url=" + url); 4695 } 4696 4697 Resources r = Resources.getSystem(); 4698 NotificationManager notificationManager = (NotificationManager) mContext 4699 .getSystemService(Context.NOTIFICATION_SERVICE); 4700 4701 if (visible) { 4702 CharSequence title; 4703 CharSequence details; 4704 int icon; 4705 Intent intent; 4706 Notification notification = new Notification(); 4707 switch (networkType) { 4708 case ConnectivityManager.TYPE_WIFI: 4709 title = r.getString(R.string.wifi_available_sign_in, 0); 4710 details = r.getString(R.string.network_available_sign_in_detailed, 4711 extraInfo); 4712 icon = R.drawable.stat_notify_wifi_in_range; 4713 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 4714 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 4715 Intent.FLAG_ACTIVITY_NEW_TASK); 4716 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0); 4717 break; 4718 case ConnectivityManager.TYPE_MOBILE: 4719 case ConnectivityManager.TYPE_MOBILE_HIPRI: 4720 title = r.getString(R.string.network_available_sign_in, 0); 4721 // TODO: Change this to pull from NetworkInfo once a printable 4722 // name has been added to it 4723 details = mTelephonyManager.getNetworkOperatorName(); 4724 icon = R.drawable.stat_notify_rssi_in_range; 4725 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION); 4726 intent.putExtra("EXTRA_URL", url); 4727 intent.setFlags(0); 4728 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); 4729 break; 4730 default: 4731 title = r.getString(R.string.network_available_sign_in, 0); 4732 details = r.getString(R.string.network_available_sign_in_detailed, 4733 extraInfo); 4734 icon = R.drawable.stat_notify_rssi_in_range; 4735 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 4736 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 4737 Intent.FLAG_ACTIVITY_NEW_TASK); 4738 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0); 4739 break; 4740 } 4741 4742 notification.when = 0; 4743 notification.icon = icon; 4744 notification.flags = Notification.FLAG_AUTO_CANCEL; 4745 notification.tickerText = title; 4746 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent); 4747 4748 try { 4749 notificationManager.notify(NOTIFICATION_ID, networkType, notification); 4750 } catch (NullPointerException npe) { 4751 loge("setNotificaitionVisible: visible notificationManager npe=" + npe); 4752 npe.printStackTrace(); 4753 } 4754 } else { 4755 try { 4756 notificationManager.cancel(NOTIFICATION_ID, networkType); 4757 } catch (NullPointerException npe) { 4758 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe); 4759 npe.printStackTrace(); 4760 } 4761 } 4762 mIsNotificationVisible = visible; 4763 } 4764 4765 /** Location to an updatable file listing carrier provisioning urls. 4766 * An example: 4767 * 4768 * <?xml version="1.0" encoding="utf-8"?> 4769 * <provisioningUrls> 4770 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl> 4771 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl> 4772 * </provisioningUrls> 4773 */ 4774 private static final String PROVISIONING_URL_PATH = 4775 "/data/misc/radio/provisioning_urls.xml"; 4776 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH); 4777 4778 /** XML tag for root element. */ 4779 private static final String TAG_PROVISIONING_URLS = "provisioningUrls"; 4780 /** XML tag for individual url */ 4781 private static final String TAG_PROVISIONING_URL = "provisioningUrl"; 4782 /** XML tag for redirected url */ 4783 private static final String TAG_REDIRECTED_URL = "redirectedUrl"; 4784 /** XML attribute for mcc */ 4785 private static final String ATTR_MCC = "mcc"; 4786 /** XML attribute for mnc */ 4787 private static final String ATTR_MNC = "mnc"; 4788 4789 private static final int REDIRECTED_PROVISIONING = 1; 4790 private static final int PROVISIONING = 2; 4791 4792 private String getProvisioningUrlBaseFromFile(int type) { 4793 FileReader fileReader = null; 4794 XmlPullParser parser = null; 4795 Configuration config = mContext.getResources().getConfiguration(); 4796 String tagType; 4797 4798 switch (type) { 4799 case PROVISIONING: 4800 tagType = TAG_PROVISIONING_URL; 4801 break; 4802 case REDIRECTED_PROVISIONING: 4803 tagType = TAG_REDIRECTED_URL; 4804 break; 4805 default: 4806 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " + 4807 type); 4808 } 4809 4810 try { 4811 fileReader = new FileReader(mProvisioningUrlFile); 4812 parser = Xml.newPullParser(); 4813 parser.setInput(fileReader); 4814 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS); 4815 4816 while (true) { 4817 XmlUtils.nextElement(parser); 4818 4819 String element = parser.getName(); 4820 if (element == null) break; 4821 4822 if (element.equals(tagType)) { 4823 String mcc = parser.getAttributeValue(null, ATTR_MCC); 4824 try { 4825 if (mcc != null && Integer.parseInt(mcc) == config.mcc) { 4826 String mnc = parser.getAttributeValue(null, ATTR_MNC); 4827 if (mnc != null && Integer.parseInt(mnc) == config.mnc) { 4828 parser.next(); 4829 if (parser.getEventType() == XmlPullParser.TEXT) { 4830 return parser.getText(); 4831 } 4832 } 4833 } 4834 } catch (NumberFormatException e) { 4835 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e); 4836 } 4837 } 4838 } 4839 return null; 4840 } catch (FileNotFoundException e) { 4841 loge("Carrier Provisioning Urls file not found"); 4842 } catch (XmlPullParserException e) { 4843 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e); 4844 } catch (IOException e) { 4845 loge("I/O exception reading Carrier Provisioning Urls file: " + e); 4846 } finally { 4847 if (fileReader != null) { 4848 try { 4849 fileReader.close(); 4850 } catch (IOException e) {} 4851 } 4852 } 4853 return null; 4854 } 4855 4856 @Override 4857 public String getMobileRedirectedProvisioningUrl() { 4858 enforceConnectivityInternalPermission(); 4859 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING); 4860 if (TextUtils.isEmpty(url)) { 4861 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url); 4862 } 4863 return url; 4864 } 4865 4866 @Override 4867 public String getMobileProvisioningUrl() { 4868 enforceConnectivityInternalPermission(); 4869 String url = getProvisioningUrlBaseFromFile(PROVISIONING); 4870 if (TextUtils.isEmpty(url)) { 4871 url = mContext.getResources().getString(R.string.mobile_provisioning_url); 4872 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url); 4873 } else { 4874 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url); 4875 } 4876 // populate the iccid, imei and phone number in the provisioning url. 4877 if (!TextUtils.isEmpty(url)) { 4878 String phoneNumber = mTelephonyManager.getLine1Number(); 4879 if (TextUtils.isEmpty(phoneNumber)) { 4880 phoneNumber = "0000000000"; 4881 } 4882 url = String.format(url, 4883 mTelephonyManager.getSimSerialNumber() /* ICCID */, 4884 mTelephonyManager.getDeviceId() /* IMEI */, 4885 phoneNumber /* Phone numer */); 4886 } 4887 4888 return url; 4889 } 4890 4891 @Override 4892 public void setProvisioningNotificationVisible(boolean visible, int networkType, 4893 String extraInfo, String url) { 4894 enforceConnectivityInternalPermission(); 4895 setProvNotificationVisible(visible, networkType, extraInfo, url); 4896 } 4897 4898 @Override 4899 public void setAirplaneMode(boolean enable) { 4900 enforceConnectivityInternalPermission(); 4901 final long ident = Binder.clearCallingIdentity(); 4902 try { 4903 final ContentResolver cr = mContext.getContentResolver(); 4904 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 4905 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 4906 intent.putExtra("state", enable); 4907 mContext.sendBroadcast(intent); 4908 } finally { 4909 Binder.restoreCallingIdentity(ident); 4910 } 4911 } 4912 4913 private void onUserStart(int userId) { 4914 synchronized(mVpns) { 4915 Vpn userVpn = mVpns.get(userId); 4916 if (userVpn != null) { 4917 loge("Starting user already has a VPN"); 4918 return; 4919 } 4920 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId); 4921 mVpns.put(userId, userVpn); 4922 userVpn.startMonitoring(mContext, mTrackerHandler); 4923 } 4924 } 4925 4926 private void onUserStop(int userId) { 4927 synchronized(mVpns) { 4928 Vpn userVpn = mVpns.get(userId); 4929 if (userVpn == null) { 4930 loge("Stopping user has no VPN"); 4931 return; 4932 } 4933 mVpns.delete(userId); 4934 } 4935 } 4936 4937 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() { 4938 @Override 4939 public void onReceive(Context context, Intent intent) { 4940 final String action = intent.getAction(); 4941 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 4942 if (userId == UserHandle.USER_NULL) return; 4943 4944 if (Intent.ACTION_USER_STARTING.equals(action)) { 4945 onUserStart(userId); 4946 } else if (Intent.ACTION_USER_STOPPING.equals(action)) { 4947 onUserStop(userId); 4948 } 4949 } 4950 }; 4951 4952 @Override 4953 public LinkQualityInfo getLinkQualityInfo(int networkType) { 4954 enforceAccessPermission(); 4955 if (isNetworkTypeValid(networkType)) { 4956 return mNetTrackers[networkType].getLinkQualityInfo(); 4957 } else { 4958 return null; 4959 } 4960 } 4961 4962 @Override 4963 public LinkQualityInfo getActiveLinkQualityInfo() { 4964 enforceAccessPermission(); 4965 if (isNetworkTypeValid(mActiveDefaultNetwork)) { 4966 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo(); 4967 } else { 4968 return null; 4969 } 4970 } 4971 4972 @Override 4973 public LinkQualityInfo[] getAllLinkQualityInfo() { 4974 enforceAccessPermission(); 4975 final ArrayList<LinkQualityInfo> result = Lists.newArrayList(); 4976 for (NetworkStateTracker tracker : mNetTrackers) { 4977 if (tracker != null) { 4978 LinkQualityInfo li = tracker.getLinkQualityInfo(); 4979 if (li != null) { 4980 result.add(li); 4981 } 4982 } 4983 } 4984 4985 return result.toArray(new LinkQualityInfo[result.size()]); 4986 } 4987 4988 /* Infrastructure for network sampling */ 4989 4990 private void handleNetworkSamplingTimeout() { 4991 4992 log("Sampling interval elapsed, updating statistics .."); 4993 4994 // initialize list of interfaces .. 4995 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample = 4996 new HashMap<String, SamplingDataTracker.SamplingSnapshot>(); 4997 for (NetworkStateTracker tracker : mNetTrackers) { 4998 if (tracker != null) { 4999 String ifaceName = tracker.getNetworkInterfaceName(); 5000 if (ifaceName != null) { 5001 mapIfaceToSample.put(ifaceName, null); 5002 } 5003 } 5004 } 5005 5006 // Read samples for all interfaces 5007 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample); 5008 5009 // process samples for all networks 5010 for (NetworkStateTracker tracker : mNetTrackers) { 5011 if (tracker != null) { 5012 String ifaceName = tracker.getNetworkInterfaceName(); 5013 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName); 5014 if (ss != null) { 5015 // end the previous sampling cycle 5016 tracker.stopSampling(ss); 5017 // start a new sampling cycle .. 5018 tracker.startSampling(ss); 5019 } 5020 } 5021 } 5022 5023 log("Done."); 5024 5025 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(), 5026 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS, 5027 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS); 5028 5029 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds"); 5030 5031 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent); 5032 } 5033 5034 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) { 5035 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds; 5036 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent); 5037 } 5038 5039 private final ArrayList<AsyncChannel> mNetworkFactories = new ArrayList<AsyncChannel>(); 5040 5041 public void registerNetworkFactory(Messenger messenger) { 5042 enforceConnectivityInternalPermission(); 5043 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, messenger)); 5044 } 5045 5046 private void handleRegisterNetworkFactory(Messenger messenger) { 5047 if (VDBG) log("Got NetworkFactory Messenger"); 5048 AsyncChannel ac = new AsyncChannel(); 5049 mNetworkFactories.add(ac); 5050 ac.connect(mContext, mTrackerHandler, messenger); 5051 } 5052 5053 // NetworkRequest by requestId 5054 private final SparseArray<NetworkRequest> mNetworkRequests = new SparseArray<NetworkRequest>(); 5055 5056 /** 5057 * NetworkAgentInfo supporting a request by requestId. 5058 * These have already been vetted (their Capabilities satisfy the request) 5059 * and the are the highest scored network available. 5060 * the are keyed off the Requests requestId. 5061 */ 5062 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = 5063 new SparseArray<NetworkAgentInfo>(); 5064 5065 // NetworkAgentInfo keyed off its connecting messenger 5066 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays 5067 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = 5068 new HashMap<Messenger, NetworkAgentInfo>(); 5069 5070 private final NetworkRequest mDefaultRequest; 5071 5072 public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo, 5073 LinkProperties linkProperties, NetworkCapabilities networkCapabilities, 5074 int currentScore) { 5075 enforceConnectivityInternalPermission(); 5076 5077 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), nextNetId(), 5078 new NetworkInfo(networkInfo), new LinkProperties(linkProperties), 5079 new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler); 5080 5081 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai)); 5082 } 5083 5084 private void handleRegisterNetworkAgent(NetworkAgentInfo na) { 5085 if (VDBG) log("Got NetworkAgent Messenger"); 5086 mNetworkAgentInfos.put(na.messenger, na); 5087 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger); 5088 NetworkInfo networkInfo = na.networkInfo; 5089 na.networkInfo = null; 5090 updateNetworkInfo(na, networkInfo); 5091 } 5092 5093 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) { 5094 LinkProperties newLp = networkAgent.linkProperties; 5095 int netId = networkAgent.network.netId; 5096 5097 updateInterfaces(newLp, oldLp, netId); 5098 updateMtu(newLp, oldLp); 5099 // TODO - figure out what to do for clat 5100// for (LinkProperties lp : newLp.getStackedLinks()) { 5101// updateMtu(lp, null); 5102// } 5103 updateRoutes(newLp, oldLp, netId); 5104 updateDnses(newLp, oldLp, netId); 5105 updateClat(newLp, oldLp, networkAgent); 5106 } 5107 5108 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) { 5109 // Update 464xlat state. 5110 if (mClat.requiresClat(na)) { 5111 5112 // If the connection was previously using clat, but is not using it now, stop the clat 5113 // daemon. Normally, this happens automatically when the connection disconnects, but if 5114 // the disconnect is not reported, or if the connection's LinkProperties changed for 5115 // some other reason (e.g., handoff changes the IP addresses on the link), it would 5116 // still be running. If it's not running, then stopping it is a no-op. 5117 if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) { 5118 mClat.stopClat(); 5119 } 5120 // If the link requires clat to be running, then start the daemon now. 5121 if (newLp != null && na.networkInfo.isConnected()) { 5122 mClat.startClat(na); 5123 } else { 5124 mClat.stopClat(); 5125 } 5126 } 5127 } 5128 5129 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) { 5130 CompareResult<String> interfaceDiff = new CompareResult<String>(); 5131 if (oldLp != null) { 5132 interfaceDiff = oldLp.compareAllInterfaceNames(newLp); 5133 } else if (newLp != null) { 5134 interfaceDiff.added = newLp.getAllInterfaceNames(); 5135 } 5136 for (String iface : interfaceDiff.added) { 5137 try { 5138 mNetd.addInterfaceToNetwork(iface, netId); 5139 } catch (Exception e) { 5140 loge("Exception adding interface: " + e); 5141 } 5142 } 5143 for (String iface : interfaceDiff.removed) { 5144 try { 5145 mNetd.removeInterfaceFromNetwork(iface, netId); 5146 } catch (Exception e) { 5147 loge("Exception removing interface: " + e); 5148 } 5149 } 5150 } 5151 5152 private void updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) { 5153 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 5154 if (oldLp != null) { 5155 routeDiff = oldLp.compareAllRoutes(newLp); 5156 } else if (newLp != null) { 5157 routeDiff.added = newLp.getAllRoutes(); 5158 } 5159 5160 // add routes before removing old in case it helps with continuous connectivity 5161 5162 // do this twice, adding non-nexthop routes first, then routes they are dependent on 5163 for (RouteInfo route : routeDiff.added) { 5164 if (route.hasGateway()) continue; 5165 try { 5166 mNetd.addRoute(netId, route); 5167 } catch (Exception e) { 5168 loge("Exception in addRoute for non-gateway: " + e); 5169 } 5170 } 5171 for (RouteInfo route : routeDiff.added) { 5172 if (route.hasGateway() == false) continue; 5173 try { 5174 mNetd.addRoute(netId, route); 5175 } catch (Exception e) { 5176 loge("Exception in addRoute for gateway: " + e); 5177 } 5178 } 5179 5180 for (RouteInfo route : routeDiff.removed) { 5181 try { 5182 mNetd.removeRoute(netId, route); 5183 } catch (Exception e) { 5184 loge("Exception in removeRoute: " + e); 5185 } 5186 } 5187 } 5188 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) { 5189 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) { 5190 Collection<InetAddress> dnses = newLp.getDnses(); 5191 if (dnses.size() == 0 && mDefaultDns != null) { 5192 dnses = new ArrayList(); 5193 dnses.add(mDefaultDns); 5194 if (DBG) { 5195 loge("no dns provided for netId " + netId + ", so using defaults"); 5196 } 5197 } 5198 try { 5199 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), 5200 newLp.getDomains()); 5201 } catch (Exception e) { 5202 loge("Exception in setDnsServersForNetwork: " + e); 5203 } 5204 // TODO - setprop "net.dnsX" 5205 } 5206 } 5207 5208 private void updateCapabilities(NetworkAgentInfo networkAgent, 5209 NetworkCapabilities networkCapabilities) { 5210 // TODO - what else here? Verify still satisfies everybody? 5211 // Check if satisfies somebody new? call callbacks? 5212 networkAgent.networkCapabilities = networkCapabilities; 5213 } 5214 5215 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) { 5216 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString()); 5217 for (AsyncChannel ac : mNetworkFactories) { 5218 ac.sendMessage(NetworkFactoryProtocol.CMD_REQUEST_NETWORK, score, 0, networkRequest); 5219 } 5220 } 5221 5222 private void callCallbackForRequest(NetworkRequest networkRequest, 5223 NetworkAgentInfo networkAgent, int notificationType) { 5224 // TODO 5225 } 5226 5227 private void handleLingerComplete(NetworkAgentInfo oldNetwork) { 5228 if (oldNetwork == null) { 5229 loge("Unknown NetworkAgentInfo in handleLingerComplete"); 5230 return; 5231 } 5232 if (DBG) log("handleLingerComplete for " + oldNetwork.name()); 5233 if (DBG) { 5234 if (oldNetwork.networkRequests.size() != 0) { 5235 loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests"); 5236 } 5237 } 5238 oldNetwork.asyncChannel.disconnect(); 5239 } 5240 5241 private void handleConnectionValidated(NetworkAgentInfo newNetwork) { 5242 if (newNetwork == null) { 5243 loge("Unknown NetworkAgentInfo in handleConnectionValidated"); 5244 return; 5245 } 5246 boolean keep = false; 5247 boolean isNewDefault = false; 5248 if (DBG) log("handleConnectionValidated for "+newNetwork.name()); 5249 // check if any NetworkRequest wants this NetworkAgent 5250 // first check if it satisfies the NetworkCapabilities 5251 for (int i = 0; i < mNetworkRequests.size(); i++) { 5252 NetworkRequest nr = mNetworkRequests.valueAt(i); 5253 if (nr.networkCapabilities.satisfiedByNetworkCapabilities( 5254 newNetwork.networkCapabilities)) { 5255 // next check if it's better than any current network we're using for 5256 // this request 5257 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nr.requestId); 5258 if (VDBG) { 5259 log("currentScore = " + 5260 (currentNetwork != null ? currentNetwork.currentScore : 0) + 5261 ", newScore = " + newNetwork.currentScore); 5262 } 5263 if (currentNetwork == null || 5264 currentNetwork.currentScore < newNetwork.currentScore) { 5265 if (currentNetwork != null) { 5266 currentNetwork.networkRequests.remove(nr.requestId); 5267 currentNetwork.networkListens.add(nr); 5268 if (currentNetwork.networkRequests.size() == 0) { 5269 currentNetwork.networkMonitor.sendMessage( 5270 NetworkMonitor.CMD_NETWORK_LINGER); 5271 notifyNetworkCallbacks(currentNetwork, NetworkCallbacks.LOSING); 5272 } 5273 } 5274 mNetworkForRequestId.put(nr.requestId, newNetwork); 5275 newNetwork.networkRequests.put(nr.requestId, nr); 5276 keep = true; 5277 // TODO - this could get expensive if we have alot of requests for this 5278 // network. Think about if there is a way to reduce this. Push 5279 // netid->request mapping to each factory? 5280 sendUpdatedScoreToFactories(nr, newNetwork.currentScore); 5281 if (mDefaultRequest.requestId == nr.requestId) { 5282 isNewDefault = true; 5283 } 5284 } 5285 } 5286 } 5287 if (keep) { 5288 if (isNewDefault) { 5289 if (VDBG) log("Switching to new default network: " + newNetwork); 5290 setupDataActivityTracking(newNetwork); 5291 try { 5292 mNetd.setDefaultNetId(newNetwork.network.netId); 5293 } catch (Exception e) { 5294 loge("Exception setting default network :" + e); 5295 } 5296 if (newNetwork.equals(mNetworkForRequestId.get(mDefaultRequest.requestId))) { 5297 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy()); 5298 } 5299 synchronized (ConnectivityService.this) { 5300 // have a new default network, release the transition wakelock in 5301 // a second if it's held. The second pause is to allow apps 5302 // to reconnect over the new network 5303 if (mNetTransitionWakeLock.isHeld()) { 5304 mHandler.sendMessageDelayed(mHandler.obtainMessage( 5305 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 5306 mNetTransitionWakeLockSerialNumber, 0), 5307 1000); 5308 } 5309 } 5310 5311 // this will cause us to come up initially as unconnected and switching 5312 // to connected after our normal pause unless somebody reports us as 5313 // really disconnected 5314 mDefaultInetConditionPublished = 0; 5315 mDefaultConnectionSequence++; 5316 mInetConditionChangeInFlight = false; 5317 // TODO - read the tcp buffer size config string from somewhere 5318 // updateNetworkSettings(); 5319 } 5320 // notify battery stats service about this network 5321// try { 5322 // TODO 5323 //BatteryStatsService.getService().noteNetworkInterfaceType(iface, netType); 5324// } catch (RemoteException e) { } 5325 notifyNetworkCallbacks(newNetwork, NetworkCallbacks.AVAILABLE); 5326 } else if (newNetwork.networkRequests.size() == 0) { 5327 if (VDBG) log("Validated network turns out to be unwanted. Tear it down."); 5328 newNetwork.asyncChannel.disconnect(); 5329 } 5330 } 5331 5332 5333 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) { 5334 NetworkInfo.State state = newInfo.getState(); 5335 NetworkInfo oldInfo = networkAgent.networkInfo; 5336 networkAgent.networkInfo = newInfo; 5337 5338 if (oldInfo != null && oldInfo.getState() == state) { 5339 if (VDBG) log("ignoring duplicate network state non-change"); 5340 return; 5341 } 5342 if (DBG) { 5343 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " + 5344 (oldInfo == null ? "null" : oldInfo.getState()) + 5345 " to " + state); 5346 } 5347 if (state == NetworkInfo.State.CONNECTED) { 5348 // TODO - check if we want it (optimization) 5349 try { 5350 mNetd.createNetwork(networkAgent.network.netId); 5351 } catch (Exception e) { 5352 loge("Error creating Network " + networkAgent.network.netId); 5353 } 5354 updateLinkProperties(networkAgent, null); 5355 notifyNetworkCallbacks(networkAgent, NetworkCallbacks.PRECHECK); 5356 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 5357 } else if (state == NetworkInfo.State.DISCONNECTED || 5358 state == NetworkInfo.State.SUSPENDED) { 5359 networkAgent.asyncChannel.disconnect(); 5360 } 5361 } 5362 5363 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) { 5364 if (VDBG) log("notifyType " + notifyType + " for " + networkAgent.name()); 5365 boolean needsBroadcasts = false; 5366 for (int i = 0; i < networkAgent.networkRequests.size(); i++) { 5367 NetworkRequest request = networkAgent.networkRequests.valueAt(i); 5368 if (request == null) continue; 5369 if (request.needsBroadcasts) needsBroadcasts = true; 5370 callCallbackForRequest(request, networkAgent, notifyType); 5371 } 5372 for (NetworkRequest request : networkAgent.networkListens) { 5373 if (request.needsBroadcasts) needsBroadcasts = true; 5374 callCallbackForRequest(request, networkAgent, notifyType); 5375 } 5376 if (needsBroadcasts) { 5377 if (notifyType == NetworkCallbacks.AVAILABLE) { 5378 sendConnectedBroadcastDelayed(networkAgent.networkInfo, 5379 getConnectivityChangeDelay()); 5380 } else if (notifyType == NetworkCallbacks.LOST) { 5381 NetworkInfo info = new NetworkInfo(networkAgent.networkInfo); 5382 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 5383 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 5384 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 5385 if (info.isFailover()) { 5386 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 5387 networkAgent.networkInfo.setFailover(false); 5388 } 5389 if (info.getReason() != null) { 5390 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 5391 } 5392 if (info.getExtraInfo() != null) { 5393 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo()); 5394 } 5395 NetworkAgentInfo newDefaultAgent = null; 5396 if (networkAgent.networkRequests.get(mDefaultRequest.requestId) != null) { 5397 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId); 5398 if (newDefaultAgent != null) { 5399 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, 5400 newDefaultAgent.networkInfo); 5401 } else { 5402 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 5403 } 5404 } 5405 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, 5406 mDefaultInetConditionPublished); 5407 final Intent immediateIntent = new Intent(intent); 5408 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE); 5409 sendStickyBroadcast(immediateIntent); 5410 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay()); 5411 if (newDefaultAgent != null) { 5412 sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo, 5413 getConnectivityChangeDelay()); 5414 } 5415 } 5416 } 5417 } 5418} 5419