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