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