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