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