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