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