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