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