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