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