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