ConnectivityService.java revision 17c3e0fbfcd404fb253288b386d7b39368d5852a
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.DummyDataStateTracker; 64import android.net.IConnectivityManager; 65import android.net.INetworkManagementEventObserver; 66import android.net.INetworkPolicyListener; 67import android.net.INetworkPolicyManager; 68import android.net.INetworkStatsService; 69import android.net.LinkAddress; 70import android.net.LinkProperties; 71import android.net.LinkProperties.CompareResult; 72import android.net.LinkQualityInfo; 73import android.net.MobileDataStateTracker; 74import android.net.Network; 75import android.net.NetworkAgent; 76import android.net.NetworkCapabilities; 77import android.net.NetworkConfig; 78import android.net.NetworkInfo; 79import android.net.NetworkInfo.DetailedState; 80import android.net.NetworkFactory; 81import android.net.NetworkQuotaInfo; 82import android.net.NetworkRequest; 83import android.net.NetworkState; 84import android.net.NetworkStateTracker; 85import android.net.NetworkUtils; 86import android.net.Proxy; 87import android.net.ProxyDataTracker; 88import android.net.ProxyInfo; 89import android.net.RouteInfo; 90import android.net.SamplingDataTracker; 91import android.net.Uri; 92import android.net.wimax.WimaxManagerConstants; 93import android.os.AsyncTask; 94import android.os.Binder; 95import android.os.Build; 96import android.os.FileUtils; 97import android.os.Handler; 98import android.os.HandlerThread; 99import android.os.IBinder; 100import android.os.INetworkManagementService; 101import android.os.Looper; 102import android.os.Message; 103import android.os.Messenger; 104import android.os.ParcelFileDescriptor; 105import android.os.PowerManager; 106import android.os.Process; 107import android.os.RemoteException; 108import android.os.ServiceManager; 109import android.os.SystemClock; 110import android.os.SystemProperties; 111import android.os.UserHandle; 112import android.os.UserManager; 113import android.provider.Settings; 114import android.security.Credentials; 115import android.security.KeyStore; 116import android.telephony.TelephonyManager; 117import android.text.TextUtils; 118import android.util.Slog; 119import android.util.SparseArray; 120import android.util.SparseIntArray; 121import android.util.Xml; 122 123import com.android.internal.R; 124import com.android.internal.annotations.GuardedBy; 125import com.android.internal.net.LegacyVpnInfo; 126import com.android.internal.net.VpnConfig; 127import com.android.internal.net.VpnProfile; 128import com.android.internal.telephony.DctConstants; 129import com.android.internal.telephony.Phone; 130import com.android.internal.telephony.PhoneConstants; 131import com.android.internal.telephony.TelephonyIntents; 132import com.android.internal.util.AsyncChannel; 133import com.android.internal.util.IndentingPrintWriter; 134import com.android.internal.util.XmlUtils; 135import com.android.server.am.BatteryStatsService; 136import com.android.server.connectivity.DataConnectionStats; 137import com.android.server.connectivity.Nat464Xlat; 138import com.android.server.connectivity.NetworkAgentInfo; 139import com.android.server.connectivity.NetworkMonitor; 140import com.android.server.connectivity.PacManager; 141import com.android.server.connectivity.Tethering; 142import com.android.server.connectivity.Vpn; 143import com.android.server.net.BaseNetworkObserver; 144import com.android.server.net.LockdownVpnTracker; 145import com.google.android.collect.Lists; 146import com.google.android.collect.Sets; 147 148import dalvik.system.DexClassLoader; 149 150import org.xmlpull.v1.XmlPullParser; 151import org.xmlpull.v1.XmlPullParserException; 152 153import java.io.File; 154import java.io.FileDescriptor; 155import java.io.FileNotFoundException; 156import java.io.FileReader; 157import java.io.IOException; 158import java.io.PrintWriter; 159import java.lang.reflect.Constructor; 160import java.net.HttpURLConnection; 161import java.net.Inet4Address; 162import java.net.Inet6Address; 163import java.net.InetAddress; 164import java.net.URL; 165import java.net.UnknownHostException; 166import java.util.ArrayList; 167import java.util.Arrays; 168import java.util.Collection; 169import java.util.GregorianCalendar; 170import java.util.HashMap; 171import java.util.HashSet; 172import java.util.List; 173import java.util.Map; 174import java.util.Random; 175import java.util.concurrent.atomic.AtomicBoolean; 176import java.util.concurrent.atomic.AtomicInteger; 177 178import javax.net.ssl.HostnameVerifier; 179import javax.net.ssl.HttpsURLConnection; 180import javax.net.ssl.SSLSession; 181 182import static android.net.ConnectivityManager.INVALID_NET_ID; 183 184/** 185 * @hide 186 */ 187public class ConnectivityService extends IConnectivityManager.Stub { 188 private static final String TAG = "ConnectivityService"; 189 190 private static final boolean DBG = true; 191 private static final boolean VDBG = true; // STOPSHIP 192 193 // network sampling debugging 194 private static final boolean SAMPLE_DBG = false; 195 196 private static final boolean LOGD_RULES = false; 197 198 // TODO: create better separation between radio types and network types 199 200 // how long to wait before switching back to a radio's default network 201 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000; 202 // system property that can override the above value 203 private static final String NETWORK_RESTORE_DELAY_PROP_NAME = 204 "android.telephony.apn-restore"; 205 206 // Default value if FAIL_FAST_TIME_MS is not set 207 private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000; 208 // system property that can override DEFAULT_FAIL_FAST_TIME_MS 209 private static final String FAIL_FAST_TIME_MS = 210 "persist.radio.fail_fast_time_ms"; 211 212 private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED = 213 "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED"; 214 215 private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0; 216 217 private PendingIntent mSampleIntervalElapsedIntent; 218 219 // Set network sampling interval at 12 minutes, this way, even if the timers get 220 // aggregated, it will fire at around 15 minutes, which should allow us to 221 // aggregate this timer with other timers (specially the socket keep alive timers) 222 private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 12 * 60); 223 224 // start network sampling a minute after booting ... 225 private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 60); 226 227 AlarmManager mAlarmManager; 228 229 // used in recursive route setting to add gateways for the host for which 230 // a host route was requested. 231 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10; 232 233 private Tethering mTethering; 234 235 private KeyStore mKeyStore; 236 237 @GuardedBy("mVpns") 238 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>(); 239 private VpnCallback mVpnCallback = new VpnCallback(); 240 241 private boolean mLockdownEnabled; 242 private LockdownVpnTracker mLockdownTracker; 243 244 private Nat464Xlat mClat; 245 246 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */ 247 private Object mRulesLock = new Object(); 248 /** Currently active network rules by UID. */ 249 private SparseIntArray mUidRules = new SparseIntArray(); 250 /** Set of ifaces that are costly. */ 251 private HashSet<String> mMeteredIfaces = Sets.newHashSet(); 252 253 /** 254 * Sometimes we want to refer to the individual network state 255 * trackers separately, and sometimes we just want to treat them 256 * abstractly. 257 */ 258 private NetworkStateTracker mNetTrackers[]; 259 260 /* Handles captive portal check on a network */ 261 private CaptivePortalTracker mCaptivePortalTracker; 262 263 /** 264 * The link properties that define the current links 265 */ 266 private LinkProperties mCurrentLinkProperties[]; 267 268 /** 269 * A per Net list of the PID's that requested access to the net 270 * used both as a refcount and for per-PID DNS selection 271 */ 272 private List<Integer> mNetRequestersPids[]; 273 274 // priority order of the nettrackers 275 // (excluding dynamically set mNetworkPreference) 276 // TODO - move mNetworkTypePreference into this 277 private int[] mPriorityList; 278 279 private Context mContext; 280 private int mNetworkPreference; 281 private int mActiveDefaultNetwork = -1; 282 // 0 is full bad, 100 is full good 283 private int mDefaultInetCondition = 0; 284 private int mDefaultInetConditionPublished = 0; 285 private boolean mInetConditionChangeInFlight = false; 286 private int mDefaultConnectionSequence = 0; 287 288 private Object mDnsLock = new Object(); 289 private int mNumDnsEntries; 290 291 private boolean mTestMode; 292 private static ConnectivityService sServiceInstance; 293 294 private INetworkManagementService mNetd; 295 private INetworkPolicyManager mPolicyManager; 296 297 private static final int ENABLED = 1; 298 private static final int DISABLED = 0; 299 300 private static final boolean ADD = true; 301 private static final boolean REMOVE = false; 302 303 private static final boolean TO_DEFAULT_TABLE = true; 304 private static final boolean TO_SECONDARY_TABLE = false; 305 306 private static final boolean EXEMPT = true; 307 private static final boolean UNEXEMPT = false; 308 309 /** 310 * used internally as a delayed event to make us switch back to the 311 * default network 312 */ 313 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1; 314 315 /** 316 * used internally to change our mobile data enabled flag 317 */ 318 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2; 319 320 /** 321 * used internally to synchronize inet condition reports 322 * arg1 = networkType 323 * arg2 = condition (0 bad, 100 good) 324 */ 325 private static final int EVENT_INET_CONDITION_CHANGE = 4; 326 327 /** 328 * used internally to mark the end of inet condition hold periods 329 * arg1 = networkType 330 */ 331 private static final int EVENT_INET_CONDITION_HOLD_END = 5; 332 333 /** 334 * used internally to clear a wakelock when transitioning 335 * from one net to another. Clear happens when we get a new 336 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens 337 * after a timeout if no network is found (typically 1 min). 338 */ 339 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8; 340 341 /** 342 * used internally to reload global proxy settings 343 */ 344 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9; 345 346 /** 347 * used internally to set external dependency met/unmet 348 * arg1 = ENABLED (met) or DISABLED (unmet) 349 * arg2 = NetworkType 350 */ 351 private static final int EVENT_SET_DEPENDENCY_MET = 10; 352 353 /** 354 * used internally to send a sticky broadcast delayed. 355 */ 356 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11; 357 358 /** 359 * Used internally to 360 * {@link NetworkStateTracker#setPolicyDataEnable(boolean)}. 361 */ 362 private static final int EVENT_SET_POLICY_DATA_ENABLE = 12; 363 364 private static final int EVENT_VPN_STATE_CHANGED = 13; 365 366 /** 367 * Used internally to disable fail fast of mobile data 368 */ 369 private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14; 370 371 /** 372 * used internally to indicate that data sampling interval is up 373 */ 374 private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15; 375 376 /** 377 * PAC manager has received new port. 378 */ 379 private static final int EVENT_PROXY_HAS_CHANGED = 16; 380 381 /** 382 * used internally when registering NetworkFactories 383 * obj = NetworkFactoryInfo 384 */ 385 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17; 386 387 /** 388 * used internally when registering NetworkAgents 389 * obj = Messenger 390 */ 391 private static final int EVENT_REGISTER_NETWORK_AGENT = 18; 392 393 /** 394 * used to add a network request 395 * includes a NetworkRequestInfo 396 */ 397 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19; 398 399 /** 400 * indicates a timeout period is over - check if we had a network yet or not 401 * and if not, call the timeout calback (but leave the request live until they 402 * cancel it. 403 * includes a NetworkRequestInfo 404 */ 405 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20; 406 407 /** 408 * used to add a network listener - no request 409 * includes a NetworkRequestInfo 410 */ 411 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21; 412 413 /** 414 * used to remove a network request, either a listener or a real request 415 * arg1 = UID of caller 416 * obj = NetworkRequest 417 */ 418 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22; 419 420 /** 421 * used internally when registering NetworkFactories 422 * obj = Messenger 423 */ 424 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23; 425 426 /** 427 * used internally to expire a wakelock when transitioning 428 * from one net to another. Expire happens when we fail to find 429 * a new network (typically after 1 minute) - 430 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found 431 * a replacement network. 432 */ 433 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24; 434 435 436 /** Handler used for internal events. */ 437 final private InternalHandler mHandler; 438 /** Handler used for incoming {@link NetworkStateTracker} events. */ 439 final private NetworkStateTrackerHandler mTrackerHandler; 440 441 // list of DeathRecipients used to make sure features are turned off when 442 // a process dies 443 private List<FeatureUser> mFeatureUsers; 444 445 private boolean mSystemReady; 446 private Intent mInitialBroadcast; 447 448 private PowerManager.WakeLock mNetTransitionWakeLock; 449 private String mNetTransitionWakeLockCausedBy = ""; 450 private int mNetTransitionWakeLockSerialNumber; 451 private int mNetTransitionWakeLockTimeout; 452 453 private InetAddress mDefaultDns; 454 455 // Lock for protecting access to mAddedRoutes and mExemptAddresses 456 private final Object mRoutesLock = new Object(); 457 458 // this collection is used to refcount the added routes - if there are none left 459 // it's time to remove the route from the route table 460 @GuardedBy("mRoutesLock") 461 private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>(); 462 463 // this collection corresponds to the entries of mAddedRoutes that have routing exemptions 464 // used to handle cleanup of exempt rules 465 @GuardedBy("mRoutesLock") 466 private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>(); 467 468 // used in DBG mode to track inet condition reports 469 private static final int INET_CONDITION_LOG_MAX_SIZE = 15; 470 private ArrayList mInetLog; 471 472 // track the current default http proxy - tell the world if we get a new one (real change) 473 private ProxyInfo mDefaultProxy = null; 474 private Object mProxyLock = new Object(); 475 private boolean mDefaultProxyDisabled = false; 476 477 // track the global proxy. 478 private ProxyInfo mGlobalProxy = null; 479 480 private PacManager mPacManager = null; 481 482 private SettingsObserver mSettingsObserver; 483 484 private AppOpsManager mAppOpsManager; 485 486 private UserManager mUserManager; 487 488 NetworkConfig[] mNetConfigs; 489 int mNetworksDefined; 490 491 private static class RadioAttributes { 492 public int mSimultaneity; 493 public int mType; 494 public RadioAttributes(String init) { 495 String fragments[] = init.split(","); 496 mType = Integer.parseInt(fragments[0]); 497 mSimultaneity = Integer.parseInt(fragments[1]); 498 } 499 } 500 RadioAttributes[] mRadioAttributes; 501 502 // the set of network types that can only be enabled by system/sig apps 503 List mProtectedNetworks; 504 505 private DataConnectionStats mDataConnectionStats; 506 507 private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0); 508 509 TelephonyManager mTelephonyManager; 510 511 // sequence number for Networks 512 private final static int MIN_NET_ID = 10; // some reserved marks 513 private final static int MAX_NET_ID = 65535; 514 private int mNextNetId = MIN_NET_ID; 515 516 // sequence number of NetworkRequests 517 private int mNextNetworkRequestId = 1; 518 519 private static final int UID_UNUSED = -1; 520 521 /** 522 * Implements support for the legacy "one network per network type" model. 523 * 524 * We used to have a static array of NetworkStateTrackers, one for each 525 * network type, but that doesn't work any more now that we can have, 526 * for example, more that one wifi network. This class stores all the 527 * NetworkAgentInfo objects that support a given type, but the legacy 528 * API will only see the first one. 529 * 530 * It serves two main purposes: 531 * 532 * 1. Provide information about "the network for a given type" (since this 533 * API only supports one). 534 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if 535 * the first network for a given type changes, or if the default network 536 * changes. 537 */ 538 private class LegacyTypeTracker { 539 /** 540 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS). 541 * Each list holds references to all NetworkAgentInfos that are used to 542 * satisfy requests for that network type. 543 * 544 * This array is built out at startup such that an unsupported network 545 * doesn't get an ArrayList instance, making this a tristate: 546 * unsupported, supported but not active and active. 547 * 548 * The actual lists are populated when we scan the network types that 549 * are supported on this device. 550 */ 551 private ArrayList<NetworkAgentInfo> mTypeLists[]; 552 553 public LegacyTypeTracker() { 554 mTypeLists = (ArrayList<NetworkAgentInfo>[]) 555 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1]; 556 } 557 558 public void addSupportedType(int type) { 559 if (mTypeLists[type] != null) { 560 throw new IllegalStateException( 561 "legacy list for type " + type + "already initialized"); 562 } 563 mTypeLists[type] = new ArrayList<NetworkAgentInfo>(); 564 } 565 566 private boolean isDefaultNetwork(NetworkAgentInfo nai) { 567 return mNetworkForRequestId.get(mDefaultRequest.requestId) == nai; 568 } 569 570 public boolean isTypeSupported(int type) { 571 return isNetworkTypeValid(type) && mTypeLists[type] != null; 572 } 573 574 public NetworkAgentInfo getNetworkForType(int type) { 575 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) { 576 return mTypeLists[type].get(0); 577 } else { 578 return null; 579 } 580 } 581 582 public void add(int type, NetworkAgentInfo nai) { 583 if (!isTypeSupported(type)) { 584 return; // Invalid network type. 585 } 586 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type); 587 588 ArrayList<NetworkAgentInfo> list = mTypeLists[type]; 589 if (list.contains(nai)) { 590 loge("Attempting to register duplicate agent for type " + type + ": " + nai); 591 return; 592 } 593 594 if (list.isEmpty() || isDefaultNetwork(nai)) { 595 if (VDBG) log("Sending connected broadcast for type " + type + 596 "isDefaultNetwork=" + isDefaultNetwork(nai)); 597 sendLegacyNetworkBroadcast(nai, true, type); 598 } 599 list.add(nai); 600 } 601 602 public void remove(NetworkAgentInfo nai) { 603 if (VDBG) log("Removing agent " + nai); 604 for (int type = 0; type < mTypeLists.length; type++) { 605 ArrayList<NetworkAgentInfo> list = mTypeLists[type]; 606 if (list == null || list.isEmpty()) { 607 continue; 608 } 609 610 boolean wasFirstNetwork = false; 611 if (list.get(0).equals(nai)) { 612 // This network was the first in the list. Send broadcast. 613 wasFirstNetwork = true; 614 } 615 list.remove(nai); 616 617 if (wasFirstNetwork || isDefaultNetwork(nai)) { 618 if (VDBG) log("Sending disconnected broadcast for type " + type + 619 "isDefaultNetwork=" + isDefaultNetwork(nai)); 620 sendLegacyNetworkBroadcast(nai, false, type); 621 } 622 623 if (!list.isEmpty() && wasFirstNetwork) { 624 if (VDBG) log("Other network available for type " + type + 625 ", sending connected broadcast"); 626 sendLegacyNetworkBroadcast(list.get(0), false, type); 627 } 628 } 629 } 630 } 631 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(); 632 633 public ConnectivityService(Context context, INetworkManagementService netd, 634 INetworkStatsService statsService, INetworkPolicyManager policyManager) { 635 // Currently, omitting a NetworkFactory will create one internally 636 // TODO: create here when we have cleaner WiMAX support 637 this(context, netd, statsService, policyManager, null); 638 } 639 640 public ConnectivityService(Context context, INetworkManagementService netManager, 641 INetworkStatsService statsService, INetworkPolicyManager policyManager, 642 NetworkFactory netFactory) { 643 if (DBG) log("ConnectivityService starting up"); 644 645 NetworkCapabilities netCap = new NetworkCapabilities(); 646 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); 647 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED); 648 mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId()); 649 NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(), 650 NetworkRequestInfo.REQUEST); 651 mNetworkRequests.put(mDefaultRequest, nri); 652 653 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread"); 654 handlerThread.start(); 655 mHandler = new InternalHandler(handlerThread.getLooper()); 656 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper()); 657 658 if (netFactory == null) { 659 netFactory = new DefaultNetworkFactory(context, mTrackerHandler); 660 } 661 662 // setup our unique device name 663 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) { 664 String id = Settings.Secure.getString(context.getContentResolver(), 665 Settings.Secure.ANDROID_ID); 666 if (id != null && id.length() > 0) { 667 String name = new String("android-").concat(id); 668 SystemProperties.set("net.hostname", name); 669 } 670 } 671 672 // read our default dns server ip 673 String dns = Settings.Global.getString(context.getContentResolver(), 674 Settings.Global.DEFAULT_DNS_SERVER); 675 if (dns == null || dns.length() == 0) { 676 dns = context.getResources().getString( 677 com.android.internal.R.string.config_default_dns_server); 678 } 679 try { 680 mDefaultDns = NetworkUtils.numericToInetAddress(dns); 681 } catch (IllegalArgumentException e) { 682 loge("Error setting defaultDns using " + dns); 683 } 684 685 mContext = checkNotNull(context, "missing Context"); 686 mNetd = checkNotNull(netManager, "missing INetworkManagementService"); 687 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager"); 688 mKeyStore = KeyStore.getInstance(); 689 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 690 691 try { 692 mPolicyManager.registerListener(mPolicyListener); 693 } catch (RemoteException e) { 694 // ouch, no rules updates means some processes may never get network 695 loge("unable to register INetworkPolicyListener" + e.toString()); 696 } 697 698 final PowerManager powerManager = (PowerManager) context.getSystemService( 699 Context.POWER_SERVICE); 700 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); 701 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger( 702 com.android.internal.R.integer.config_networkTransitionTimeout); 703 704 mNetTrackers = new NetworkStateTracker[ 705 ConnectivityManager.MAX_NETWORK_TYPE+1]; 706 mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1]; 707 708 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1]; 709 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1]; 710 711 // Load device network attributes from resources 712 String[] raStrings = context.getResources().getStringArray( 713 com.android.internal.R.array.radioAttributes); 714 for (String raString : raStrings) { 715 RadioAttributes r = new RadioAttributes(raString); 716 if (VDBG) log("raString=" + raString + " r=" + r); 717 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) { 718 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType); 719 continue; 720 } 721 if (mRadioAttributes[r.mType] != null) { 722 loge("Error in radioAttributes - ignoring attempt to redefine type " + 723 r.mType); 724 continue; 725 } 726 mRadioAttributes[r.mType] = r; 727 } 728 729 // TODO: What is the "correct" way to do determine if this is a wifi only device? 730 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false); 731 log("wifiOnly=" + wifiOnly); 732 String[] naStrings = context.getResources().getStringArray( 733 com.android.internal.R.array.networkAttributes); 734 for (String naString : naStrings) { 735 try { 736 NetworkConfig n = new NetworkConfig(naString); 737 if (VDBG) log("naString=" + naString + " config=" + n); 738 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) { 739 loge("Error in networkAttributes - ignoring attempt to define type " + 740 n.type); 741 continue; 742 } 743 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) { 744 log("networkAttributes - ignoring mobile as this dev is wifiOnly " + 745 n.type); 746 continue; 747 } 748 if (mNetConfigs[n.type] != null) { 749 loge("Error in networkAttributes - ignoring attempt to redefine type " + 750 n.type); 751 continue; 752 } 753 if (mRadioAttributes[n.radio] == null) { 754 loge("Error in networkAttributes - ignoring attempt to use undefined " + 755 "radio " + n.radio + " in network type " + n.type); 756 continue; 757 } 758 mLegacyTypeTracker.addSupportedType(n.type); 759 760 mNetConfigs[n.type] = n; 761 mNetworksDefined++; 762 } catch(Exception e) { 763 // ignore it - leave the entry null 764 } 765 } 766 if (VDBG) log("mNetworksDefined=" + mNetworksDefined); 767 768 mProtectedNetworks = new ArrayList<Integer>(); 769 int[] protectedNetworks = context.getResources().getIntArray( 770 com.android.internal.R.array.config_protectedNetworks); 771 for (int p : protectedNetworks) { 772 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) { 773 mProtectedNetworks.add(p); 774 } else { 775 if (DBG) loge("Ignoring protectedNetwork " + p); 776 } 777 } 778 779 // high priority first 780 mPriorityList = new int[mNetworksDefined]; 781 { 782 int insertionPoint = mNetworksDefined-1; 783 int currentLowest = 0; 784 int nextLowest = 0; 785 while (insertionPoint > -1) { 786 for (NetworkConfig na : mNetConfigs) { 787 if (na == null) continue; 788 if (na.priority < currentLowest) continue; 789 if (na.priority > currentLowest) { 790 if (na.priority < nextLowest || nextLowest == 0) { 791 nextLowest = na.priority; 792 } 793 continue; 794 } 795 mPriorityList[insertionPoint--] = na.type; 796 } 797 currentLowest = nextLowest; 798 nextLowest = 0; 799 } 800 } 801 802 mNetRequestersPids = 803 (List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1]; 804 for (int i : mPriorityList) { 805 mNetRequestersPids[i] = new ArrayList<Integer>(); 806 } 807 808 mFeatureUsers = new ArrayList<FeatureUser>(); 809 810 mTestMode = SystemProperties.get("cm.test.mode").equals("true") 811 && SystemProperties.get("ro.build.type").equals("eng"); 812 813 // Create and start trackers for hard-coded networks 814 for (int targetNetworkType : mPriorityList) { 815 final NetworkConfig config = mNetConfigs[targetNetworkType]; 816 final NetworkStateTracker tracker; 817 try { 818 tracker = netFactory.createTracker(targetNetworkType, config); 819 mNetTrackers[targetNetworkType] = tracker; 820 } catch (IllegalArgumentException e) { 821 Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType) 822 + " tracker: " + e); 823 continue; 824 } 825 826 tracker.startMonitoring(context, mTrackerHandler); 827 if (config.isDefault()) { 828 tracker.reconnect(); 829 } 830 } 831 832 mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper()); 833 834 //set up the listener for user state for creating user VPNs 835 IntentFilter intentFilter = new IntentFilter(); 836 intentFilter.addAction(Intent.ACTION_USER_STARTING); 837 intentFilter.addAction(Intent.ACTION_USER_STOPPING); 838 mContext.registerReceiverAsUser( 839 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null); 840 mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler); 841 842 try { 843 mNetd.registerObserver(mTethering); 844 mNetd.registerObserver(mDataActivityObserver); 845 mNetd.registerObserver(mClat); 846 } catch (RemoteException e) { 847 loge("Error registering observer :" + e); 848 } 849 850 if (DBG) { 851 mInetLog = new ArrayList(); 852 } 853 854 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY); 855 mSettingsObserver.observe(mContext); 856 857 mDataConnectionStats = new DataConnectionStats(mContext); 858 mDataConnectionStats.startMonitoring(); 859 860 // start network sampling .. 861 Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null); 862 mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext, 863 SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0); 864 865 mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE); 866 setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent); 867 868 IntentFilter filter = new IntentFilter(); 869 filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED); 870 mContext.registerReceiver( 871 new BroadcastReceiver() { 872 @Override 873 public void onReceive(Context context, Intent intent) { 874 String action = intent.getAction(); 875 if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) { 876 mHandler.sendMessage(mHandler.obtainMessage 877 (EVENT_SAMPLE_INTERVAL_ELAPSED)); 878 } 879 } 880 }, 881 new IntentFilter(filter)); 882 883 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED); 884 885 filter = new IntentFilter(); 886 filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION); 887 mContext.registerReceiver(mProvisioningReceiver, filter); 888 889 mAppOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); 890 891 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE); 892 } 893 894 private synchronized int nextNetworkRequestId() { 895 return mNextNetworkRequestId++; 896 } 897 898 private synchronized int nextNetId() { 899 int netId = mNextNetId; 900 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID; 901 return netId; 902 } 903 904 /** 905 * Factory that creates {@link NetworkStateTracker} instances using given 906 * {@link NetworkConfig}. 907 * 908 * TODO - this is obsolete and will be deleted. It's replaced by the 909 * registerNetworkFactory call and protocol. 910 * @Deprecated in favor of registerNetworkFactory dynamic bindings 911 */ 912 public interface NetworkFactory { 913 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config); 914 } 915 916 private static class DefaultNetworkFactory implements NetworkFactory { 917 private final Context mContext; 918 private final Handler mTrackerHandler; 919 920 public DefaultNetworkFactory(Context context, Handler trackerHandler) { 921 mContext = context; 922 mTrackerHandler = trackerHandler; 923 } 924 925 @Override 926 public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) { 927 switch (config.radio) { 928 case TYPE_DUMMY: 929 return new DummyDataStateTracker(targetNetworkType, config.name); 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 mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this); 2344 loadGlobalProxy(); 2345 2346 synchronized(this) { 2347 mSystemReady = true; 2348 if (mInitialBroadcast != null) { 2349 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL); 2350 mInitialBroadcast = null; 2351 } 2352 } 2353 // load the global proxy at startup 2354 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY)); 2355 2356 // Try bringing up tracker, but if KeyStore isn't ready yet, wait 2357 // for user to unlock device. 2358 if (!updateLockdownVpn()) { 2359 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT); 2360 mContext.registerReceiver(mUserPresentReceiver, filter); 2361 } 2362 } 2363 2364 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() { 2365 @Override 2366 public void onReceive(Context context, Intent intent) { 2367 // Try creating lockdown tracker, since user present usually means 2368 // unlocked keystore. 2369 if (updateLockdownVpn()) { 2370 mContext.unregisterReceiver(this); 2371 } 2372 } 2373 }; 2374 2375 private boolean isNewNetTypePreferredOverCurrentNetType(int type) { 2376 if (((type != mNetworkPreference) 2377 && (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority)) 2378 || (mNetworkPreference == mActiveDefaultNetwork)) { 2379 return false; 2380 } 2381 return true; 2382 } 2383 2384 private void handleConnect(NetworkInfo info) { 2385 final int newNetType = info.getType(); 2386 2387 // snapshot isFailover, because sendConnectedBroadcast() resets it 2388 boolean isFailover = info.isFailover(); 2389 final NetworkStateTracker thisNet = mNetTrackers[newNetType]; 2390 final String thisIface = thisNet.getLinkProperties().getInterfaceName(); 2391 2392 if (VDBG) { 2393 log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface 2394 + " isFailover" + isFailover); 2395 } 2396 2397 // if this is a default net and other default is running 2398 // kill the one not preferred 2399 if (mNetConfigs[newNetType].isDefault()) { 2400 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) { 2401 if (isNewNetTypePreferredOverCurrentNetType(newNetType)) { 2402 String teardownPolicy = SystemProperties.get("net.teardownPolicy"); 2403 if (TextUtils.equals(teardownPolicy, "keep") == false) { 2404 // tear down the other 2405 NetworkStateTracker otherNet = 2406 mNetTrackers[mActiveDefaultNetwork]; 2407 if (DBG) { 2408 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() + 2409 " teardown"); 2410 } 2411 if (!teardown(otherNet)) { 2412 loge("Network declined teardown request"); 2413 teardown(thisNet); 2414 return; 2415 } 2416 } else { 2417 //TODO - remove 2418 loge("network teardown skipped due to net.teardownPolicy setting"); 2419 } 2420 } else { 2421 // don't accept this one 2422 if (VDBG) { 2423 log("Not broadcasting CONNECT_ACTION " + 2424 "to torn down network " + info.getTypeName()); 2425 } 2426 teardown(thisNet); 2427 return; 2428 } 2429 } 2430 int thisNetId = nextNetId(); 2431 thisNet.setNetId(thisNetId); 2432 try { 2433// mNetd.createNetwork(thisNetId, thisIface); 2434 } catch (Exception e) { 2435 loge("Exception creating network :" + e); 2436 teardown(thisNet); 2437 return; 2438 } 2439// Already in place in new function. This is dead code. 2440// setupDataActivityTracking(newNetType); 2441 synchronized (ConnectivityService.this) { 2442 // have a new default network, release the transition wakelock in a second 2443 // if it's held. The second pause is to allow apps to reconnect over the 2444 // new network 2445 if (mNetTransitionWakeLock.isHeld()) { 2446 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2447 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 2448 mNetTransitionWakeLockSerialNumber, 0), 2449 1000); 2450 } 2451 } 2452 mActiveDefaultNetwork = newNetType; 2453 try { 2454 mNetd.setDefaultNetId(thisNetId); 2455 } catch (Exception e) { 2456 loge("Exception setting default network :" + e); 2457 } 2458 // this will cause us to come up initially as unconnected and switching 2459 // to connected after our normal pause unless somebody reports us as reall 2460 // disconnected 2461 mDefaultInetConditionPublished = 0; 2462 mDefaultConnectionSequence++; 2463 mInetConditionChangeInFlight = false; 2464 // Don't do this - if we never sign in stay, grey 2465 //reportNetworkCondition(mActiveDefaultNetwork, 100); 2466 updateNetworkSettings(thisNet); 2467 } else { 2468 int thisNetId = nextNetId(); 2469 thisNet.setNetId(thisNetId); 2470 try { 2471// mNetd.createNetwork(thisNetId, thisIface); 2472 } catch (Exception e) { 2473 loge("Exception creating network :" + e); 2474 teardown(thisNet); 2475 return; 2476 } 2477 } 2478 thisNet.setTeardownRequested(false); 2479// Already in place in new function. This is dead code. 2480// updateMtuSizeSettings(thisNet); 2481// handleConnectivityChange(newNetType, false); 2482 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay()); 2483 2484 // notify battery stats service about this network 2485 if (thisIface != null) { 2486 try { 2487 BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType); 2488 } catch (RemoteException e) { 2489 // ignored; service lives in system_server 2490 } 2491 } 2492 } 2493 2494 /** @hide */ 2495 @Override 2496 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) { 2497 enforceConnectivityInternalPermission(); 2498 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal); 2499// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal); 2500 } 2501 2502 /** 2503 * Setup data activity tracking for the given network. 2504 * 2505 * Every {@code setupDataActivityTracking} should be paired with a 2506 * {@link #removeDataActivityTracking} for cleanup. 2507 */ 2508 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) { 2509 final String iface = networkAgent.linkProperties.getInterfaceName(); 2510 2511 final int timeout; 2512 int type = ConnectivityManager.TYPE_NONE; 2513 2514 if (networkAgent.networkCapabilities.hasTransport( 2515 NetworkCapabilities.TRANSPORT_CELLULAR)) { 2516 timeout = Settings.Global.getInt(mContext.getContentResolver(), 2517 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE, 2518 5); 2519 type = ConnectivityManager.TYPE_MOBILE; 2520 } else if (networkAgent.networkCapabilities.hasTransport( 2521 NetworkCapabilities.TRANSPORT_WIFI)) { 2522 timeout = Settings.Global.getInt(mContext.getContentResolver(), 2523 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI, 2524 0); 2525 type = ConnectivityManager.TYPE_WIFI; 2526 } else { 2527 // do not track any other networks 2528 timeout = 0; 2529 } 2530 2531 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) { 2532 try { 2533 mNetd.addIdleTimer(iface, timeout, type); 2534 } catch (Exception e) { 2535 // You shall not crash! 2536 loge("Exception in setupDataActivityTracking " + e); 2537 } 2538 } 2539 } 2540 2541 /** 2542 * Remove data activity tracking when network disconnects. 2543 */ 2544 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) { 2545 final String iface = networkAgent.linkProperties.getInterfaceName(); 2546 final NetworkCapabilities caps = networkAgent.networkCapabilities; 2547 2548 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || 2549 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) { 2550 try { 2551 // the call fails silently if no idletimer setup for this interface 2552 mNetd.removeIdleTimer(iface); 2553 } catch (Exception e) { 2554 loge("Exception in removeDataActivityTracking " + e); 2555 } 2556 } 2557 } 2558 2559 /** 2560 * After a change in the connectivity state of a network. We're mainly 2561 * concerned with making sure that the list of DNS servers is set up 2562 * according to which networks are connected, and ensuring that the 2563 * right routing table entries exist. 2564 * 2565 * TODO - delete when we're sure all this functionallity is captured. 2566 */ 2567 private void handleConnectivityChange(int netType, LinkProperties curLp, boolean doReset) { 2568 int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0; 2569 boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType); 2570 if (VDBG) { 2571 log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset 2572 + " resetMask=" + resetMask); 2573 } 2574 2575 /* 2576 * If a non-default network is enabled, add the host routes that 2577 * will allow it's DNS servers to be accessed. 2578 */ 2579 handleDnsConfigurationChange(netType); 2580 2581 LinkProperties newLp = null; 2582 2583 if (mNetTrackers[netType].getNetworkInfo().isConnected()) { 2584 newLp = mNetTrackers[netType].getLinkProperties(); 2585 if (VDBG) { 2586 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" + 2587 " doReset=" + doReset + " resetMask=" + resetMask + 2588 "\n curLp=" + curLp + 2589 "\n newLp=" + newLp); 2590 } 2591 2592 if (curLp != null) { 2593 if (curLp.isIdenticalInterfaceName(newLp)) { 2594 CompareResult<LinkAddress> car = curLp.compareAddresses(newLp); 2595 if ((car.removed.size() != 0) || (car.added.size() != 0)) { 2596 for (LinkAddress linkAddr : car.removed) { 2597 if (linkAddr.getAddress() instanceof Inet4Address) { 2598 resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES; 2599 } 2600 if (linkAddr.getAddress() instanceof Inet6Address) { 2601 resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES; 2602 } 2603 } 2604 if (DBG) { 2605 log("handleConnectivityChange: addresses changed" + 2606 " linkProperty[" + netType + "]:" + " resetMask=" + resetMask + 2607 "\n car=" + car); 2608 } 2609 } else { 2610 if (VDBG) { 2611 log("handleConnectivityChange: addresses are the same reset per" + 2612 " doReset linkProperty[" + netType + "]:" + 2613 " resetMask=" + resetMask); 2614 } 2615 } 2616 } else { 2617 resetMask = NetworkUtils.RESET_ALL_ADDRESSES; 2618 if (DBG) { 2619 log("handleConnectivityChange: interface not not equivalent reset both" + 2620 " linkProperty[" + netType + "]:" + 2621 " resetMask=" + resetMask); 2622 } 2623 } 2624 } 2625 if (mNetConfigs[netType].isDefault()) { 2626 handleApplyDefaultProxy(newLp.getHttpProxy()); 2627 } 2628 } else { 2629 if (VDBG) { 2630 log("handleConnectivityChange: changed linkProperty[" + netType + "]:" + 2631 " doReset=" + doReset + " resetMask=" + resetMask + 2632 "\n curLp=" + curLp + 2633 "\n newLp= null"); 2634 } 2635 } 2636 mCurrentLinkProperties[netType] = newLp; 2637 boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt, 2638 mNetTrackers[netType].getNetwork().netId); 2639 2640 if (resetMask != 0 || resetDns) { 2641 if (VDBG) log("handleConnectivityChange: resetting"); 2642 if (curLp != null) { 2643 if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp); 2644 for (String iface : curLp.getAllInterfaceNames()) { 2645 if (TextUtils.isEmpty(iface) == false) { 2646 if (resetMask != 0) { 2647 if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")"); 2648 NetworkUtils.resetConnections(iface, resetMask); 2649 2650 // Tell VPN the interface is down. It is a temporary 2651 // but effective fix to make VPN aware of the change. 2652 if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) { 2653 synchronized(mVpns) { 2654 for (int i = 0; i < mVpns.size(); i++) { 2655 mVpns.valueAt(i).interfaceStatusChanged(iface, false); 2656 } 2657 } 2658 } 2659 } 2660 } else { 2661 loge("Can't reset connection for type "+netType); 2662 } 2663 } 2664 if (resetDns) { 2665 flushVmDnsCache(); 2666 if (VDBG) log("resetting DNS cache for type " + netType); 2667 try { 2668 mNetd.flushNetworkDnsCache(mNetTrackers[netType].getNetwork().netId); 2669 } catch (Exception e) { 2670 // never crash - catch them all 2671 if (DBG) loge("Exception resetting dns cache: " + e); 2672 } 2673 } 2674 } 2675 } 2676 2677 // TODO: Temporary notifying upstread change to Tethering. 2678 // @see bug/4455071 2679 /** Notify TetheringService if interface name has been changed. */ 2680 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(), 2681 PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) { 2682 if (isTetheringSupported()) { 2683 mTethering.handleTetherIfaceChange(); 2684 } 2685 } 2686 } 2687 2688 /** 2689 * Add and remove routes using the old properties (null if not previously connected), 2690 * new properties (null if becoming disconnected). May even be double null, which 2691 * is a noop. 2692 * Uses isLinkDefault to determine if default routes should be set or conversely if 2693 * host routes should be set to the dns servers 2694 * returns a boolean indicating the routes changed 2695 */ 2696 private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp, 2697 boolean isLinkDefault, boolean exempt, int netId) { 2698 Collection<RouteInfo> routesToAdd = null; 2699 CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>(); 2700 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 2701 if (curLp != null) { 2702 // check for the delta between the current set and the new 2703 routeDiff = curLp.compareAllRoutes(newLp); 2704 dnsDiff = curLp.compareDnses(newLp); 2705 } else if (newLp != null) { 2706 routeDiff.added = newLp.getAllRoutes(); 2707 dnsDiff.added = newLp.getDnsServers(); 2708 } 2709 2710 boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0); 2711 2712 for (RouteInfo r : routeDiff.removed) { 2713 if (isLinkDefault || ! r.isDefaultRoute()) { 2714 if (VDBG) log("updateRoutes: default remove route r=" + r); 2715 removeRoute(curLp, r, TO_DEFAULT_TABLE, netId); 2716 } 2717 if (isLinkDefault == false) { 2718 // remove from a secondary route table 2719 removeRoute(curLp, r, TO_SECONDARY_TABLE, netId); 2720 } 2721 } 2722 2723 for (RouteInfo r : routeDiff.added) { 2724 if (isLinkDefault || ! r.isDefaultRoute()) { 2725 addRoute(newLp, r, TO_DEFAULT_TABLE, exempt, netId); 2726 } else { 2727 // add to a secondary route table 2728 addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT, netId); 2729 2730 // many radios add a default route even when we don't want one. 2731 // remove the default route unless somebody else has asked for it 2732 String ifaceName = newLp.getInterfaceName(); 2733 synchronized (mRoutesLock) { 2734 if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) { 2735 if (VDBG) log("Removing " + r + " for interface " + ifaceName); 2736 try { 2737 mNetd.removeRoute(netId, r); 2738 } catch (Exception e) { 2739 // never crash - catch them all 2740 if (DBG) loge("Exception trying to remove a route: " + e); 2741 } 2742 } 2743 } 2744 } 2745 } 2746 2747 return routesChanged; 2748 } 2749 2750 /** 2751 * Reads the network specific MTU size from reources. 2752 * and set it on it's iface. 2753 */ 2754 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) { 2755 final String iface = newLp.getInterfaceName(); 2756 final int mtu = newLp.getMtu(); 2757 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) { 2758 if (VDBG) log("identical MTU - not setting"); 2759 return; 2760 } 2761 2762 if (mtu < 68 || mtu > 10000) { 2763 loge("Unexpected mtu value: " + mtu + ", " + iface); 2764 return; 2765 } 2766 2767 try { 2768 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu); 2769 mNetd.setMtu(iface, mtu); 2770 } catch (Exception e) { 2771 Slog.e(TAG, "exception in setMtu()" + e); 2772 } 2773 } 2774 2775 /** 2776 * Reads the network specific TCP buffer sizes from SystemProperties 2777 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system 2778 * wide use 2779 */ 2780 private void updateNetworkSettings(NetworkStateTracker nt) { 2781 String key = nt.getTcpBufferSizesPropName(); 2782 String bufferSizes = key == null ? null : SystemProperties.get(key); 2783 2784 if (TextUtils.isEmpty(bufferSizes)) { 2785 if (VDBG) log(key + " not found in system properties. Using defaults"); 2786 2787 // Setting to default values so we won't be stuck to previous values 2788 key = "net.tcp.buffersize.default"; 2789 bufferSizes = SystemProperties.get(key); 2790 } 2791 2792 // Set values in kernel 2793 if (bufferSizes.length() != 0) { 2794 if (VDBG) { 2795 log("Setting TCP values: [" + bufferSizes 2796 + "] which comes from [" + key + "]"); 2797 } 2798 setBufferSize(bufferSizes); 2799 } 2800 2801 final String defaultRwndKey = "net.tcp.default_init_rwnd"; 2802 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0); 2803 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(), 2804 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue); 2805 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd"; 2806 if (rwndValue != 0) { 2807 SystemProperties.set(sysctlKey, rwndValue.toString()); 2808 } 2809 } 2810 2811 /** 2812 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max] 2813 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem 2814 * 2815 * @param bufferSizes in the format of "readMin, readInitial, readMax, 2816 * writeMin, writeInitial, writeMax" 2817 */ 2818 private void setBufferSize(String bufferSizes) { 2819 try { 2820 String[] values = bufferSizes.split(","); 2821 2822 if (values.length == 6) { 2823 final String prefix = "/sys/kernel/ipv4/tcp_"; 2824 FileUtils.stringToFile(prefix + "rmem_min", values[0]); 2825 FileUtils.stringToFile(prefix + "rmem_def", values[1]); 2826 FileUtils.stringToFile(prefix + "rmem_max", values[2]); 2827 FileUtils.stringToFile(prefix + "wmem_min", values[3]); 2828 FileUtils.stringToFile(prefix + "wmem_def", values[4]); 2829 FileUtils.stringToFile(prefix + "wmem_max", values[5]); 2830 } else { 2831 loge("Invalid buffersize string: " + bufferSizes); 2832 } 2833 } catch (IOException e) { 2834 loge("Can't set tcp buffer sizes:" + e); 2835 } 2836 } 2837 2838 /** 2839 * Adjust the per-process dns entries (net.dns<x>.<pid>) based 2840 * on the highest priority active net which this process requested. 2841 * If there aren't any, clear it out 2842 */ 2843 private void reassessPidDns(int pid, boolean doBump) 2844 { 2845 if (VDBG) log("reassessPidDns for pid " + pid); 2846 Integer myPid = new Integer(pid); 2847 for(int i : mPriorityList) { 2848 if (mNetConfigs[i].isDefault()) { 2849 continue; 2850 } 2851 NetworkStateTracker nt = mNetTrackers[i]; 2852 if (nt.getNetworkInfo().isConnected() && 2853 !nt.isTeardownRequested()) { 2854 LinkProperties p = nt.getLinkProperties(); 2855 if (p == null) continue; 2856 if (mNetRequestersPids[i].contains(myPid)) { 2857 try { 2858 // TODO: Reimplement this via local variable in bionic. 2859 // mNetd.setDnsNetworkForPid(nt.getNetwork().netId, pid); 2860 } catch (Exception e) { 2861 Slog.e(TAG, "exception reasseses pid dns: " + e); 2862 } 2863 return; 2864 } 2865 } 2866 } 2867 // nothing found - delete 2868 try { 2869 // TODO: Reimplement this via local variable in bionic. 2870 // mNetd.clearDnsNetworkForPid(pid); 2871 } catch (Exception e) { 2872 Slog.e(TAG, "exception clear interface from pid: " + e); 2873 } 2874 } 2875 2876 private void flushVmDnsCache() { 2877 /* 2878 * Tell the VMs to toss their DNS caches 2879 */ 2880 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE); 2881 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 2882 /* 2883 * Connectivity events can happen before boot has completed ... 2884 */ 2885 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 2886 final long ident = Binder.clearCallingIdentity(); 2887 try { 2888 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 2889 } finally { 2890 Binder.restoreCallingIdentity(ident); 2891 } 2892 } 2893 2894 // Caller must grab mDnsLock. 2895 private void updateDnsLocked(String network, int netId, 2896 Collection<InetAddress> dnses, String domains) { 2897 int last = 0; 2898 if (dnses.size() == 0 && mDefaultDns != null) { 2899 dnses = new ArrayList(); 2900 dnses.add(mDefaultDns); 2901 if (DBG) { 2902 loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress()); 2903 } 2904 } 2905 2906 try { 2907 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), domains); 2908 2909 for (InetAddress dns : dnses) { 2910 ++last; 2911 String key = "net.dns" + last; 2912 String value = dns.getHostAddress(); 2913 SystemProperties.set(key, value); 2914 } 2915 for (int i = last + 1; i <= mNumDnsEntries; ++i) { 2916 String key = "net.dns" + i; 2917 SystemProperties.set(key, ""); 2918 } 2919 mNumDnsEntries = last; 2920 } catch (Exception e) { 2921 loge("exception setting default dns interface: " + e); 2922 } 2923 } 2924 2925 private void handleDnsConfigurationChange(int netType) { 2926 // add default net's dns entries 2927 NetworkStateTracker nt = mNetTrackers[netType]; 2928 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) { 2929 LinkProperties p = nt.getLinkProperties(); 2930 if (p == null) return; 2931 Collection<InetAddress> dnses = p.getDnsServers(); 2932 int netId = nt.getNetwork().netId; 2933 if (mNetConfigs[netType].isDefault()) { 2934 String network = nt.getNetworkInfo().getTypeName(); 2935 synchronized (mDnsLock) { 2936 updateDnsLocked(network, netId, dnses, p.getDomains()); 2937 } 2938 } else { 2939 try { 2940 mNetd.setDnsServersForNetwork(netId, 2941 NetworkUtils.makeStrings(dnses), p.getDomains()); 2942 } catch (Exception e) { 2943 if (DBG) loge("exception setting dns servers: " + e); 2944 } 2945 // set per-pid dns for attached secondary nets 2946 List<Integer> pids = mNetRequestersPids[netType]; 2947 for (Integer pid : pids) { 2948 try { 2949 // TODO: Reimplement this via local variable in bionic. 2950 // mNetd.setDnsNetworkForPid(netId, pid); 2951 } catch (Exception e) { 2952 Slog.e(TAG, "exception setting interface for pid: " + e); 2953 } 2954 } 2955 } 2956 flushVmDnsCache(); 2957 } 2958 } 2959 2960 @Override 2961 public int getRestoreDefaultNetworkDelay(int networkType) { 2962 String restoreDefaultNetworkDelayStr = SystemProperties.get( 2963 NETWORK_RESTORE_DELAY_PROP_NAME); 2964 if(restoreDefaultNetworkDelayStr != null && 2965 restoreDefaultNetworkDelayStr.length() != 0) { 2966 try { 2967 return Integer.valueOf(restoreDefaultNetworkDelayStr); 2968 } catch (NumberFormatException e) { 2969 } 2970 } 2971 // if the system property isn't set, use the value for the apn type 2972 int ret = RESTORE_DEFAULT_NETWORK_DELAY; 2973 2974 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) && 2975 (mNetConfigs[networkType] != null)) { 2976 ret = mNetConfigs[networkType].restoreTime; 2977 } 2978 return ret; 2979 } 2980 2981 @Override 2982 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) { 2983 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); 2984 if (mContext.checkCallingOrSelfPermission( 2985 android.Manifest.permission.DUMP) 2986 != PackageManager.PERMISSION_GRANTED) { 2987 pw.println("Permission Denial: can't dump ConnectivityService " + 2988 "from from pid=" + Binder.getCallingPid() + ", uid=" + 2989 Binder.getCallingUid()); 2990 return; 2991 } 2992 2993 pw.println("NetworkFactories for:"); 2994 pw.increaseIndent(); 2995 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 2996 pw.println(nfi.name); 2997 } 2998 pw.decreaseIndent(); 2999 pw.println(); 3000 3001 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId); 3002 pw.print("Active default network: "); 3003 if (defaultNai == null) { 3004 pw.println("none"); 3005 } else { 3006 pw.println(defaultNai.network.netId); 3007 } 3008 pw.println(); 3009 3010 pw.println("Current Networks:"); 3011 pw.increaseIndent(); 3012 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 3013 pw.println(nai.toString()); 3014 pw.increaseIndent(); 3015 pw.println("Requests:"); 3016 pw.increaseIndent(); 3017 for (int i = 0; i < nai.networkRequests.size(); i++) { 3018 pw.println(nai.networkRequests.valueAt(i).toString()); 3019 } 3020 pw.decreaseIndent(); 3021 pw.println("Lingered:"); 3022 pw.increaseIndent(); 3023 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString()); 3024 pw.decreaseIndent(); 3025 pw.decreaseIndent(); 3026 } 3027 pw.decreaseIndent(); 3028 pw.println(); 3029 3030 pw.println("Network Requests:"); 3031 pw.increaseIndent(); 3032 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 3033 pw.println(nri.toString()); 3034 } 3035 pw.println(); 3036 pw.decreaseIndent(); 3037 3038 synchronized (this) { 3039 pw.println("NetworkTranstionWakeLock is currently " + 3040 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held."); 3041 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy); 3042 } 3043 pw.println(); 3044 3045 mTethering.dump(fd, pw, args); 3046 3047 if (mInetLog != null) { 3048 pw.println(); 3049 pw.println("Inet condition reports:"); 3050 pw.increaseIndent(); 3051 for(int i = 0; i < mInetLog.size(); i++) { 3052 pw.println(mInetLog.get(i)); 3053 } 3054 pw.decreaseIndent(); 3055 } 3056 } 3057 3058 // must be stateless - things change under us. 3059 private class NetworkStateTrackerHandler extends Handler { 3060 public NetworkStateTrackerHandler(Looper looper) { 3061 super(looper); 3062 } 3063 3064 @Override 3065 public void handleMessage(Message msg) { 3066 NetworkInfo info; 3067 switch (msg.what) { 3068 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: { 3069 handleAsyncChannelHalfConnect(msg); 3070 break; 3071 } 3072 case AsyncChannel.CMD_CHANNEL_DISCONNECT: { 3073 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3074 if (nai != null) nai.asyncChannel.disconnect(); 3075 break; 3076 } 3077 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: { 3078 handleAsyncChannelDisconnected(msg); 3079 break; 3080 } 3081 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: { 3082 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3083 if (nai == null) { 3084 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent"); 3085 } else { 3086 updateCapabilities(nai, (NetworkCapabilities)msg.obj); 3087 } 3088 break; 3089 } 3090 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: { 3091 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3092 if (nai == null) { 3093 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED"); 3094 } else { 3095 if (VDBG) log("Update of Linkproperties for " + nai.name()); 3096 LinkProperties oldLp = nai.linkProperties; 3097 nai.linkProperties = (LinkProperties)msg.obj; 3098 updateLinkProperties(nai, oldLp); 3099 } 3100 break; 3101 } 3102 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: { 3103 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3104 if (nai == null) { 3105 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent"); 3106 break; 3107 } 3108 info = (NetworkInfo) msg.obj; 3109 updateNetworkInfo(nai, info); 3110 break; 3111 } 3112 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: { 3113 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3114 if (nai == null) { 3115 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent"); 3116 break; 3117 } 3118 Integer score = (Integer) msg.obj; 3119 if (score != null) updateNetworkScore(nai, score.intValue()); 3120 break; 3121 } 3122 case NetworkMonitor.EVENT_NETWORK_VALIDATED: { 3123 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj; 3124 handleConnectionValidated(nai); 3125 break; 3126 } 3127 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: { 3128 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj; 3129 handleLingerComplete(nai); 3130 break; 3131 } 3132 case NetworkStateTracker.EVENT_STATE_CHANGED: { 3133 info = (NetworkInfo) msg.obj; 3134 NetworkInfo.State state = info.getState(); 3135 3136 if (VDBG || (state == NetworkInfo.State.CONNECTED) || 3137 (state == NetworkInfo.State.DISCONNECTED) || 3138 (state == NetworkInfo.State.SUSPENDED)) { 3139 log("ConnectivityChange for " + 3140 info.getTypeName() + ": " + 3141 state + "/" + info.getDetailedState()); 3142 } 3143 3144 // Since mobile has the notion of a network/apn that can be used for 3145 // provisioning we need to check every time we're connected as 3146 // CaptiveProtalTracker won't detected it because DCT doesn't report it 3147 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its 3148 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which 3149 // is received by MDST and sent here as EVENT_STATE_CHANGED. 3150 if (ConnectivityManager.isNetworkTypeMobile(info.getType()) 3151 && (0 != Settings.Global.getInt(mContext.getContentResolver(), 3152 Settings.Global.DEVICE_PROVISIONED, 0)) 3153 && (((state == NetworkInfo.State.CONNECTED) 3154 && (info.getType() == ConnectivityManager.TYPE_MOBILE)) 3155 || info.isConnectedToProvisioningNetwork())) { 3156 log("ConnectivityChange checkMobileProvisioning for" 3157 + " TYPE_MOBILE or ProvisioningNetwork"); 3158 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS); 3159 } 3160 3161 EventLogTags.writeConnectivityStateChanged( 3162 info.getType(), info.getSubtype(), info.getDetailedState().ordinal()); 3163 3164 if (info.isConnectedToProvisioningNetwork()) { 3165 /** 3166 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING 3167 * for now its an in between network, its a network that 3168 * is actually a default network but we don't want it to be 3169 * announced as such to keep background applications from 3170 * trying to use it. It turns out that some still try so we 3171 * take the additional step of clearing any default routes 3172 * to the link that may have incorrectly setup by the lower 3173 * levels. 3174 */ 3175 LinkProperties lp = getLinkPropertiesForTypeInternal(info.getType()); 3176 if (DBG) { 3177 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp); 3178 } 3179 3180 // Clear any default routes setup by the radio so 3181 // any activity by applications trying to use this 3182 // connection will fail until the provisioning network 3183 // is enabled. 3184 for (RouteInfo r : lp.getRoutes()) { 3185 removeRoute(lp, r, TO_DEFAULT_TABLE, 3186 mNetTrackers[info.getType()].getNetwork().netId); 3187 } 3188 } else if (state == NetworkInfo.State.DISCONNECTED) { 3189 } else if (state == NetworkInfo.State.SUSPENDED) { 3190 } else if (state == NetworkInfo.State.CONNECTED) { 3191 // handleConnect(info); 3192 } 3193 if (mLockdownTracker != null) { 3194 mLockdownTracker.onNetworkInfoChanged(info); 3195 } 3196 break; 3197 } 3198 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: { 3199 info = (NetworkInfo) msg.obj; 3200 // TODO: Temporary allowing network configuration 3201 // change not resetting sockets. 3202 // @see bug/4455071 3203 handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()], 3204 false); 3205 break; 3206 } 3207 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: { 3208 info = (NetworkInfo) msg.obj; 3209 int type = info.getType(); 3210 if (mNetConfigs[type].isDefault()) updateNetworkSettings(mNetTrackers[type]); 3211 break; 3212 } 3213 } 3214 } 3215 } 3216 3217 private void handleAsyncChannelHalfConnect(Message msg) { 3218 AsyncChannel ac = (AsyncChannel) msg.obj; 3219 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) { 3220 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 3221 if (VDBG) log("NetworkFactory connected"); 3222 // A network factory has connected. Send it all current NetworkRequests. 3223 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 3224 if (nri.isRequest == false) continue; 3225 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId); 3226 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, 3227 (nai != null ? nai.currentScore : 0), 0, nri.request); 3228 } 3229 } else { 3230 loge("Error connecting NetworkFactory"); 3231 mNetworkFactoryInfos.remove(msg.obj); 3232 } 3233 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) { 3234 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 3235 if (VDBG) log("NetworkAgent connected"); 3236 // A network agent has requested a connection. Establish the connection. 3237 mNetworkAgentInfos.get(msg.replyTo).asyncChannel. 3238 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION); 3239 } else { 3240 loge("Error connecting NetworkAgent"); 3241 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo); 3242 if (nai != null) { 3243 mNetworkForNetId.remove(nai.network.netId); 3244 mLegacyTypeTracker.remove(nai); 3245 } 3246 } 3247 } 3248 } 3249 private void handleAsyncChannelDisconnected(Message msg) { 3250 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3251 if (nai != null) { 3252 if (DBG) { 3253 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size()); 3254 } 3255 // A network agent has disconnected. 3256 // Tell netd to clean up the configuration for this network 3257 // (routing rules, DNS, etc). 3258 try { 3259 mNetd.removeNetwork(nai.network.netId); 3260 } catch (Exception e) { 3261 loge("Exception removing network: " + e); 3262 } 3263 // TODO - if we move the logic to the network agent (have them disconnect 3264 // because they lost all their requests or because their score isn't good) 3265 // then they would disconnect organically, report their new state and then 3266 // disconnect the channel. 3267 if (nai.networkInfo.isConnected()) { 3268 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, 3269 null, null); 3270 } 3271 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST); 3272 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED); 3273 mNetworkAgentInfos.remove(msg.replyTo); 3274 updateClat(null, nai.linkProperties, nai); 3275 mLegacyTypeTracker.remove(nai); 3276 mNetworkForNetId.remove(nai.network.netId); 3277 // Since we've lost the network, go through all the requests that 3278 // it was satisfying and see if any other factory can satisfy them. 3279 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>(); 3280 for (int i = 0; i < nai.networkRequests.size(); i++) { 3281 NetworkRequest request = nai.networkRequests.valueAt(i); 3282 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId); 3283 if (VDBG) { 3284 log(" checking request " + request + ", currentNetwork = " + 3285 (currentNetwork != null ? currentNetwork.name() : "null")); 3286 } 3287 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) { 3288 mNetworkForRequestId.remove(request.requestId); 3289 sendUpdatedScoreToFactories(request, 0); 3290 NetworkAgentInfo alternative = null; 3291 for (Map.Entry entry : mNetworkAgentInfos.entrySet()) { 3292 NetworkAgentInfo existing = (NetworkAgentInfo)entry.getValue(); 3293 if (existing.networkInfo.isConnected() && 3294 request.networkCapabilities.satisfiedByNetworkCapabilities( 3295 existing.networkCapabilities) && 3296 (alternative == null || 3297 alternative.currentScore < existing.currentScore)) { 3298 alternative = existing; 3299 } 3300 } 3301 if (alternative != null && !toActivate.contains(alternative)) { 3302 toActivate.add(alternative); 3303 } 3304 } 3305 } 3306 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 3307 removeDataActivityTracking(nai); 3308 mActiveDefaultNetwork = ConnectivityManager.TYPE_NONE; 3309 requestNetworkTransitionWakelock(nai.name()); 3310 } 3311 for (NetworkAgentInfo networkToActivate : toActivate) { 3312 networkToActivate.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 3313 } 3314 } 3315 } 3316 3317 private void handleRegisterNetworkRequest(Message msg) { 3318 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj); 3319 final NetworkCapabilities newCap = nri.request.networkCapabilities; 3320 int score = 0; 3321 3322 // Check for the best currently alive network that satisfies this request 3323 NetworkAgentInfo bestNetwork = null; 3324 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) { 3325 if (VDBG) log("handleRegisterNetworkRequest checking " + network.name()); 3326 if (newCap.satisfiedByNetworkCapabilities(network.networkCapabilities)) { 3327 if (VDBG) log("apparently satisfied. currentScore=" + network.currentScore); 3328 if ((bestNetwork == null) || bestNetwork.currentScore < network.currentScore) { 3329 bestNetwork = network; 3330 } 3331 } 3332 } 3333 if (bestNetwork != null) { 3334 if (VDBG) log("using " + bestNetwork.name()); 3335 bestNetwork.addRequest(nri.request); 3336 mNetworkForRequestId.put(nri.request.requestId, bestNetwork); 3337 int legacyType = nri.request.legacyType; 3338 if (legacyType != TYPE_NONE) { 3339 mLegacyTypeTracker.add(legacyType, bestNetwork); 3340 } 3341 notifyNetworkCallback(bestNetwork, nri); 3342 score = bestNetwork.currentScore; 3343 } 3344 mNetworkRequests.put(nri.request, nri); 3345 if (msg.what == EVENT_REGISTER_NETWORK_REQUEST) { 3346 if (DBG) log("sending new NetworkRequest to factories"); 3347 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 3348 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 3349 0, nri.request); 3350 } 3351 } 3352 } 3353 3354 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) { 3355 NetworkRequestInfo nri = mNetworkRequests.get(request); 3356 if (nri != null) { 3357 if (nri.mUid != callingUid) { 3358 if (DBG) log("Attempt to release unowned NetworkRequest " + request); 3359 return; 3360 } 3361 if (DBG) log("releasing NetworkRequest " + request); 3362 mNetworkRequests.remove(request); 3363 // tell the network currently servicing this that it's no longer interested 3364 NetworkAgentInfo affectedNetwork = mNetworkForRequestId.get(nri.request.requestId); 3365 if (affectedNetwork != null) { 3366 mNetworkForRequestId.remove(nri.request.requestId); 3367 affectedNetwork.networkRequests.remove(nri.request.requestId); 3368 if (VDBG) { 3369 log(" Removing from current network " + affectedNetwork.name() + ", leaving " + 3370 affectedNetwork.networkRequests.size() + " requests."); 3371 } 3372 } 3373 3374 if (nri.isRequest) { 3375 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 3376 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST, 3377 nri.request); 3378 } 3379 3380 if (affectedNetwork != null) { 3381 // check if this network still has live requests - otherwise, tear down 3382 // TODO - probably push this to the NF/NA 3383 boolean keep = false; 3384 for (int i = 0; i < affectedNetwork.networkRequests.size(); i++) { 3385 NetworkRequest r = affectedNetwork.networkRequests.valueAt(i); 3386 if (mNetworkRequests.get(r).isRequest) { 3387 keep = true; 3388 break; 3389 } 3390 } 3391 if (keep == false) { 3392 if (DBG) log("no live requests for " + affectedNetwork.name() + 3393 "; disconnecting"); 3394 affectedNetwork.asyncChannel.disconnect(); 3395 } 3396 } 3397 } 3398 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED); 3399 } 3400 } 3401 3402 private class InternalHandler extends Handler { 3403 public InternalHandler(Looper looper) { 3404 super(looper); 3405 } 3406 3407 @Override 3408 public void handleMessage(Message msg) { 3409 NetworkInfo info; 3410 switch (msg.what) { 3411 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK: 3412 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: { 3413 String causedBy = null; 3414 synchronized (ConnectivityService.this) { 3415 if (msg.arg1 == mNetTransitionWakeLockSerialNumber && 3416 mNetTransitionWakeLock.isHeld()) { 3417 mNetTransitionWakeLock.release(); 3418 causedBy = mNetTransitionWakeLockCausedBy; 3419 } else { 3420 break; 3421 } 3422 } 3423 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) { 3424 log("Failed to find a new network - expiring NetTransition Wakelock"); 3425 } else { 3426 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) + 3427 " cleared because we found a replacement network"); 3428 } 3429 break; 3430 } 3431 case EVENT_RESTORE_DEFAULT_NETWORK: { 3432 FeatureUser u = (FeatureUser)msg.obj; 3433 u.expire(); 3434 break; 3435 } 3436 case EVENT_INET_CONDITION_CHANGE: { 3437 int netType = msg.arg1; 3438 int condition = msg.arg2; 3439 handleInetConditionChange(netType, condition); 3440 break; 3441 } 3442 case EVENT_INET_CONDITION_HOLD_END: { 3443 int netType = msg.arg1; 3444 int sequence = msg.arg2; 3445 handleInetConditionHoldEnd(netType, sequence); 3446 break; 3447 } 3448 case EVENT_APPLY_GLOBAL_HTTP_PROXY: { 3449 handleDeprecatedGlobalHttpProxy(); 3450 break; 3451 } 3452 case EVENT_SET_DEPENDENCY_MET: { 3453 boolean met = (msg.arg1 == ENABLED); 3454 handleSetDependencyMet(msg.arg2, met); 3455 break; 3456 } 3457 case EVENT_SEND_STICKY_BROADCAST_INTENT: { 3458 Intent intent = (Intent)msg.obj; 3459 sendStickyBroadcast(intent); 3460 break; 3461 } 3462 case EVENT_SET_POLICY_DATA_ENABLE: { 3463 final int networkType = msg.arg1; 3464 final boolean enabled = msg.arg2 == ENABLED; 3465 handleSetPolicyDataEnable(networkType, enabled); 3466 break; 3467 } 3468 case EVENT_VPN_STATE_CHANGED: { 3469 if (mLockdownTracker != null) { 3470 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj); 3471 } 3472 break; 3473 } 3474 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: { 3475 int tag = mEnableFailFastMobileDataTag.get(); 3476 if (msg.arg1 == tag) { 3477 MobileDataStateTracker mobileDst = 3478 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 3479 if (mobileDst != null) { 3480 mobileDst.setEnableFailFastMobileData(msg.arg2); 3481 } 3482 } else { 3483 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1 3484 + " != tag:" + tag); 3485 } 3486 break; 3487 } 3488 case EVENT_SAMPLE_INTERVAL_ELAPSED: { 3489 handleNetworkSamplingTimeout(); 3490 break; 3491 } 3492 case EVENT_PROXY_HAS_CHANGED: { 3493 handleApplyDefaultProxy((ProxyInfo)msg.obj); 3494 break; 3495 } 3496 case EVENT_REGISTER_NETWORK_FACTORY: { 3497 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj); 3498 break; 3499 } 3500 case EVENT_UNREGISTER_NETWORK_FACTORY: { 3501 handleUnregisterNetworkFactory((Messenger)msg.obj); 3502 break; 3503 } 3504 case EVENT_REGISTER_NETWORK_AGENT: { 3505 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj); 3506 break; 3507 } 3508 case EVENT_REGISTER_NETWORK_REQUEST: 3509 case EVENT_REGISTER_NETWORK_LISTENER: { 3510 handleRegisterNetworkRequest(msg); 3511 break; 3512 } 3513 case EVENT_RELEASE_NETWORK_REQUEST: { 3514 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1); 3515 break; 3516 } 3517 } 3518 } 3519 } 3520 3521 // javadoc from interface 3522 public int tether(String iface) { 3523 enforceTetherChangePermission(); 3524 3525 if (isTetheringSupported()) { 3526 return mTethering.tether(iface); 3527 } else { 3528 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3529 } 3530 } 3531 3532 // javadoc from interface 3533 public int untether(String iface) { 3534 enforceTetherChangePermission(); 3535 3536 if (isTetheringSupported()) { 3537 return mTethering.untether(iface); 3538 } else { 3539 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3540 } 3541 } 3542 3543 // javadoc from interface 3544 public int getLastTetherError(String iface) { 3545 enforceTetherAccessPermission(); 3546 3547 if (isTetheringSupported()) { 3548 return mTethering.getLastTetherError(iface); 3549 } else { 3550 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3551 } 3552 } 3553 3554 // TODO - proper iface API for selection by property, inspection, etc 3555 public String[] getTetherableUsbRegexs() { 3556 enforceTetherAccessPermission(); 3557 if (isTetheringSupported()) { 3558 return mTethering.getTetherableUsbRegexs(); 3559 } else { 3560 return new String[0]; 3561 } 3562 } 3563 3564 public String[] getTetherableWifiRegexs() { 3565 enforceTetherAccessPermission(); 3566 if (isTetheringSupported()) { 3567 return mTethering.getTetherableWifiRegexs(); 3568 } else { 3569 return new String[0]; 3570 } 3571 } 3572 3573 public String[] getTetherableBluetoothRegexs() { 3574 enforceTetherAccessPermission(); 3575 if (isTetheringSupported()) { 3576 return mTethering.getTetherableBluetoothRegexs(); 3577 } else { 3578 return new String[0]; 3579 } 3580 } 3581 3582 public int setUsbTethering(boolean enable) { 3583 enforceTetherChangePermission(); 3584 if (isTetheringSupported()) { 3585 return mTethering.setUsbTethering(enable); 3586 } else { 3587 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3588 } 3589 } 3590 3591 // TODO - move iface listing, queries, etc to new module 3592 // javadoc from interface 3593 public String[] getTetherableIfaces() { 3594 enforceTetherAccessPermission(); 3595 return mTethering.getTetherableIfaces(); 3596 } 3597 3598 public String[] getTetheredIfaces() { 3599 enforceTetherAccessPermission(); 3600 return mTethering.getTetheredIfaces(); 3601 } 3602 3603 public String[] getTetheringErroredIfaces() { 3604 enforceTetherAccessPermission(); 3605 return mTethering.getErroredIfaces(); 3606 } 3607 3608 // if ro.tether.denied = true we default to no tethering 3609 // gservices could set the secure setting to 1 though to enable it on a build where it 3610 // had previously been turned off. 3611 public boolean isTetheringSupported() { 3612 enforceTetherAccessPermission(); 3613 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 3614 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(), 3615 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0) 3616 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING); 3617 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 || 3618 mTethering.getTetherableWifiRegexs().length != 0 || 3619 mTethering.getTetherableBluetoothRegexs().length != 0) && 3620 mTethering.getUpstreamIfaceTypes().length != 0); 3621 } 3622 3623 // Called when we lose the default network and have no replacement yet. 3624 // This will automatically be cleared after X seconds or a new default network 3625 // becomes CONNECTED, whichever happens first. The timer is started by the 3626 // first caller and not restarted by subsequent callers. 3627 private void requestNetworkTransitionWakelock(String forWhom) { 3628 int serialNum = 0; 3629 synchronized (this) { 3630 if (mNetTransitionWakeLock.isHeld()) return; 3631 serialNum = ++mNetTransitionWakeLockSerialNumber; 3632 mNetTransitionWakeLock.acquire(); 3633 mNetTransitionWakeLockCausedBy = forWhom; 3634 } 3635 mHandler.sendMessageDelayed(mHandler.obtainMessage( 3636 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0), 3637 mNetTransitionWakeLockTimeout); 3638 return; 3639 } 3640 3641 // 100 percent is full good, 0 is full bad. 3642 public void reportInetCondition(int networkType, int percentage) { 3643 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")"); 3644 mContext.enforceCallingOrSelfPermission( 3645 android.Manifest.permission.STATUS_BAR, 3646 "ConnectivityService"); 3647 3648 if (DBG) { 3649 int pid = getCallingPid(); 3650 int uid = getCallingUid(); 3651 String s = pid + "(" + uid + ") reports inet is " + 3652 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " + 3653 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime(); 3654 mInetLog.add(s); 3655 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) { 3656 mInetLog.remove(0); 3657 } 3658 } 3659 mHandler.sendMessage(mHandler.obtainMessage( 3660 EVENT_INET_CONDITION_CHANGE, networkType, percentage)); 3661 } 3662 3663 public void reportBadNetwork(Network network) { 3664 //TODO 3665 } 3666 3667 private void handleInetConditionChange(int netType, int condition) { 3668 if (mActiveDefaultNetwork == -1) { 3669 if (DBG) log("handleInetConditionChange: no active default network - ignore"); 3670 return; 3671 } 3672 if (mActiveDefaultNetwork != netType) { 3673 if (DBG) log("handleInetConditionChange: net=" + netType + 3674 " != default=" + mActiveDefaultNetwork + " - ignore"); 3675 return; 3676 } 3677 if (VDBG) { 3678 log("handleInetConditionChange: net=" + 3679 netType + ", condition=" + condition + 3680 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork); 3681 } 3682 mDefaultInetCondition = condition; 3683 int delay; 3684 if (mInetConditionChangeInFlight == false) { 3685 if (VDBG) log("handleInetConditionChange: starting a change hold"); 3686 // setup a new hold to debounce this 3687 if (mDefaultInetCondition > 50) { 3688 delay = Settings.Global.getInt(mContext.getContentResolver(), 3689 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500); 3690 } else { 3691 delay = Settings.Global.getInt(mContext.getContentResolver(), 3692 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000); 3693 } 3694 mInetConditionChangeInFlight = true; 3695 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END, 3696 mActiveDefaultNetwork, mDefaultConnectionSequence), delay); 3697 } else { 3698 // we've set the new condition, when this hold ends that will get picked up 3699 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt"); 3700 } 3701 } 3702 3703 private void handleInetConditionHoldEnd(int netType, int sequence) { 3704 if (DBG) { 3705 log("handleInetConditionHoldEnd: net=" + netType + 3706 ", condition=" + mDefaultInetCondition + 3707 ", published condition=" + mDefaultInetConditionPublished); 3708 } 3709 mInetConditionChangeInFlight = false; 3710 3711 if (mActiveDefaultNetwork == -1) { 3712 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring"); 3713 return; 3714 } 3715 if (mDefaultConnectionSequence != sequence) { 3716 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring"); 3717 return; 3718 } 3719 // TODO: Figure out why this optimization sometimes causes a 3720 // change in mDefaultInetCondition to be missed and the 3721 // UI to not be updated. 3722 //if (mDefaultInetConditionPublished == mDefaultInetCondition) { 3723 // if (DBG) log("no change in condition - aborting"); 3724 // return; 3725 //} 3726 NetworkInfo networkInfo = getNetworkInfoForType(mActiveDefaultNetwork); 3727 if (networkInfo.isConnected() == false) { 3728 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring"); 3729 return; 3730 } 3731 mDefaultInetConditionPublished = mDefaultInetCondition; 3732 sendInetConditionBroadcast(networkInfo); 3733 return; 3734 } 3735 3736 public ProxyInfo getProxy() { 3737 // this information is already available as a world read/writable jvm property 3738 // so this API change wouldn't have a benifit. It also breaks the passing 3739 // of proxy info to all the JVMs. 3740 // enforceAccessPermission(); 3741 synchronized (mProxyLock) { 3742 ProxyInfo ret = mGlobalProxy; 3743 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy; 3744 return ret; 3745 } 3746 } 3747 3748 public void setGlobalProxy(ProxyInfo proxyProperties) { 3749 enforceConnectivityInternalPermission(); 3750 3751 synchronized (mProxyLock) { 3752 if (proxyProperties == mGlobalProxy) return; 3753 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return; 3754 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return; 3755 3756 String host = ""; 3757 int port = 0; 3758 String exclList = ""; 3759 String pacFileUrl = ""; 3760 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) || 3761 (proxyProperties.getPacFileUrl() != null))) { 3762 if (!proxyProperties.isValid()) { 3763 if (DBG) 3764 log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3765 return; 3766 } 3767 mGlobalProxy = new ProxyInfo(proxyProperties); 3768 host = mGlobalProxy.getHost(); 3769 port = mGlobalProxy.getPort(); 3770 exclList = mGlobalProxy.getExclusionListAsString(); 3771 if (proxyProperties.getPacFileUrl() != null) { 3772 pacFileUrl = proxyProperties.getPacFileUrl().toString(); 3773 } 3774 } else { 3775 mGlobalProxy = null; 3776 } 3777 ContentResolver res = mContext.getContentResolver(); 3778 final long token = Binder.clearCallingIdentity(); 3779 try { 3780 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host); 3781 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port); 3782 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 3783 exclList); 3784 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl); 3785 } finally { 3786 Binder.restoreCallingIdentity(token); 3787 } 3788 } 3789 3790 if (mGlobalProxy == null) { 3791 proxyProperties = mDefaultProxy; 3792 } 3793 sendProxyBroadcast(proxyProperties); 3794 } 3795 3796 private void loadGlobalProxy() { 3797 ContentResolver res = mContext.getContentResolver(); 3798 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST); 3799 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0); 3800 String exclList = Settings.Global.getString(res, 3801 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST); 3802 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC); 3803 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) { 3804 ProxyInfo proxyProperties; 3805 if (!TextUtils.isEmpty(pacFileUrl)) { 3806 proxyProperties = new ProxyInfo(pacFileUrl); 3807 } else { 3808 proxyProperties = new ProxyInfo(host, port, exclList); 3809 } 3810 if (!proxyProperties.isValid()) { 3811 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3812 return; 3813 } 3814 3815 synchronized (mProxyLock) { 3816 mGlobalProxy = proxyProperties; 3817 } 3818 } 3819 } 3820 3821 public ProxyInfo getGlobalProxy() { 3822 // this information is already available as a world read/writable jvm property 3823 // so this API change wouldn't have a benifit. It also breaks the passing 3824 // of proxy info to all the JVMs. 3825 // enforceAccessPermission(); 3826 synchronized (mProxyLock) { 3827 return mGlobalProxy; 3828 } 3829 } 3830 3831 private void handleApplyDefaultProxy(ProxyInfo proxy) { 3832 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 3833 && (proxy.getPacFileUrl() == null)) { 3834 proxy = null; 3835 } 3836 synchronized (mProxyLock) { 3837 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return; 3838 if (mDefaultProxy == proxy) return; // catches repeated nulls 3839 if (proxy != null && !proxy.isValid()) { 3840 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString()); 3841 return; 3842 } 3843 3844 // This call could be coming from the PacManager, containing the port of the local 3845 // proxy. If this new proxy matches the global proxy then copy this proxy to the 3846 // global (to get the correct local port), and send a broadcast. 3847 // TODO: Switch PacManager to have its own message to send back rather than 3848 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy. 3849 if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null) 3850 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) { 3851 mGlobalProxy = proxy; 3852 sendProxyBroadcast(mGlobalProxy); 3853 return; 3854 } 3855 mDefaultProxy = proxy; 3856 3857 if (mGlobalProxy != null) return; 3858 if (!mDefaultProxyDisabled) { 3859 sendProxyBroadcast(proxy); 3860 } 3861 } 3862 } 3863 3864 private void handleDeprecatedGlobalHttpProxy() { 3865 String proxy = Settings.Global.getString(mContext.getContentResolver(), 3866 Settings.Global.HTTP_PROXY); 3867 if (!TextUtils.isEmpty(proxy)) { 3868 String data[] = proxy.split(":"); 3869 if (data.length == 0) { 3870 return; 3871 } 3872 3873 String proxyHost = data[0]; 3874 int proxyPort = 8080; 3875 if (data.length > 1) { 3876 try { 3877 proxyPort = Integer.parseInt(data[1]); 3878 } catch (NumberFormatException e) { 3879 return; 3880 } 3881 } 3882 ProxyInfo p = new ProxyInfo(data[0], proxyPort, ""); 3883 setGlobalProxy(p); 3884 } 3885 } 3886 3887 private void sendProxyBroadcast(ProxyInfo proxy) { 3888 if (proxy == null) proxy = new ProxyInfo("", 0, ""); 3889 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return; 3890 if (DBG) log("sending Proxy Broadcast for " + proxy); 3891 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); 3892 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 3893 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3894 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy); 3895 final long ident = Binder.clearCallingIdentity(); 3896 try { 3897 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 3898 } finally { 3899 Binder.restoreCallingIdentity(ident); 3900 } 3901 } 3902 3903 private static class SettingsObserver extends ContentObserver { 3904 private int mWhat; 3905 private Handler mHandler; 3906 SettingsObserver(Handler handler, int what) { 3907 super(handler); 3908 mHandler = handler; 3909 mWhat = what; 3910 } 3911 3912 void observe(Context context) { 3913 ContentResolver resolver = context.getContentResolver(); 3914 resolver.registerContentObserver(Settings.Global.getUriFor( 3915 Settings.Global.HTTP_PROXY), false, this); 3916 } 3917 3918 @Override 3919 public void onChange(boolean selfChange) { 3920 mHandler.obtainMessage(mWhat).sendToTarget(); 3921 } 3922 } 3923 3924 private static void log(String s) { 3925 Slog.d(TAG, s); 3926 } 3927 3928 private static void loge(String s) { 3929 Slog.e(TAG, s); 3930 } 3931 3932 int convertFeatureToNetworkType(int networkType, String feature) { 3933 int usedNetworkType = networkType; 3934 3935 if(networkType == ConnectivityManager.TYPE_MOBILE) { 3936 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) { 3937 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS; 3938 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) { 3939 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL; 3940 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) || 3941 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) { 3942 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN; 3943 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) { 3944 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI; 3945 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) { 3946 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA; 3947 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) { 3948 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS; 3949 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) { 3950 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS; 3951 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_EMERGENCY)) { 3952 usedNetworkType = ConnectivityManager.TYPE_MOBILE_EMERGENCY; 3953 } else { 3954 Slog.e(TAG, "Can't match any mobile netTracker!"); 3955 } 3956 } else if (networkType == ConnectivityManager.TYPE_WIFI) { 3957 if (TextUtils.equals(feature, "p2p")) { 3958 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P; 3959 } else { 3960 Slog.e(TAG, "Can't match any wifi netTracker!"); 3961 } 3962 } else { 3963 Slog.e(TAG, "Unexpected network type"); 3964 } 3965 return usedNetworkType; 3966 } 3967 3968 private static <T> T checkNotNull(T value, String message) { 3969 if (value == null) { 3970 throw new NullPointerException(message); 3971 } 3972 return value; 3973 } 3974 3975 /** 3976 * Protect a socket from VPN routing rules. This method is used by 3977 * VpnBuilder and not available in ConnectivityManager. Permissions 3978 * are checked in Vpn class. 3979 * @hide 3980 */ 3981 @Override 3982 public boolean protectVpn(ParcelFileDescriptor socket) { 3983 throwIfLockdownEnabled(); 3984 try { 3985 int type = mActiveDefaultNetwork; 3986 int user = UserHandle.getUserId(Binder.getCallingUid()); 3987 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) { 3988 synchronized(mVpns) { 3989 mVpns.get(user).protect(socket); 3990 } 3991 return true; 3992 } 3993 } catch (Exception e) { 3994 // ignore 3995 } finally { 3996 try { 3997 socket.close(); 3998 } catch (Exception e) { 3999 // ignore 4000 } 4001 } 4002 return false; 4003 } 4004 4005 /** 4006 * Prepare for a VPN application. This method is used by VpnDialogs 4007 * and not available in ConnectivityManager. Permissions are checked 4008 * in Vpn class. 4009 * @hide 4010 */ 4011 @Override 4012 public boolean prepareVpn(String oldPackage, String newPackage) { 4013 throwIfLockdownEnabled(); 4014 int user = UserHandle.getUserId(Binder.getCallingUid()); 4015 synchronized(mVpns) { 4016 return mVpns.get(user).prepare(oldPackage, newPackage); 4017 } 4018 } 4019 4020 @Override 4021 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) { 4022 enforceMarkNetworkSocketPermission(); 4023 final long token = Binder.clearCallingIdentity(); 4024 try { 4025 int mark = mNetd.getMarkForUid(uid); 4026 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues 4027 if (mark == -1) { 4028 mark = 0; 4029 } 4030 NetworkUtils.markSocket(socket.getFd(), mark); 4031 } catch (RemoteException e) { 4032 } finally { 4033 Binder.restoreCallingIdentity(token); 4034 } 4035 } 4036 4037 /** 4038 * Configure a TUN interface and return its file descriptor. Parameters 4039 * are encoded and opaque to this class. This method is used by VpnBuilder 4040 * and not available in ConnectivityManager. Permissions are checked in 4041 * Vpn class. 4042 * @hide 4043 */ 4044 @Override 4045 public ParcelFileDescriptor establishVpn(VpnConfig config) { 4046 throwIfLockdownEnabled(); 4047 int user = UserHandle.getUserId(Binder.getCallingUid()); 4048 synchronized(mVpns) { 4049 return mVpns.get(user).establish(config); 4050 } 4051 } 4052 4053 /** 4054 * Start legacy VPN, controlling native daemons as needed. Creates a 4055 * secondary thread to perform connection work, returning quickly. 4056 */ 4057 @Override 4058 public void startLegacyVpn(VpnProfile profile) { 4059 throwIfLockdownEnabled(); 4060 final LinkProperties egress = getActiveLinkProperties(); 4061 if (egress == null) { 4062 throw new IllegalStateException("Missing active network connection"); 4063 } 4064 int user = UserHandle.getUserId(Binder.getCallingUid()); 4065 synchronized(mVpns) { 4066 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress); 4067 } 4068 } 4069 4070 /** 4071 * Return the information of the ongoing legacy VPN. This method is used 4072 * by VpnSettings and not available in ConnectivityManager. Permissions 4073 * are checked in Vpn class. 4074 * @hide 4075 */ 4076 @Override 4077 public LegacyVpnInfo getLegacyVpnInfo() { 4078 throwIfLockdownEnabled(); 4079 int user = UserHandle.getUserId(Binder.getCallingUid()); 4080 synchronized(mVpns) { 4081 return mVpns.get(user).getLegacyVpnInfo(); 4082 } 4083 } 4084 4085 /** 4086 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and 4087 * not available in ConnectivityManager. 4088 * Permissions are checked in Vpn class. 4089 * @hide 4090 */ 4091 @Override 4092 public VpnConfig getVpnConfig() { 4093 int user = UserHandle.getUserId(Binder.getCallingUid()); 4094 synchronized(mVpns) { 4095 return mVpns.get(user).getVpnConfig(); 4096 } 4097 } 4098 4099 /** 4100 * Callback for VPN subsystem. Currently VPN is not adapted to the service 4101 * through NetworkStateTracker since it works differently. For example, it 4102 * needs to override DNS servers but never takes the default routes. It 4103 * relies on another data network, and it could keep existing connections 4104 * alive after reconnecting, switching between networks, or even resuming 4105 * from deep sleep. Calls from applications should be done synchronously 4106 * to avoid race conditions. As these are all hidden APIs, refactoring can 4107 * be done whenever a better abstraction is developed. 4108 */ 4109 public class VpnCallback { 4110 private VpnCallback() { 4111 } 4112 4113 public void onStateChanged(NetworkInfo info) { 4114 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget(); 4115 } 4116 4117 public void override(String iface, List<String> dnsServers, List<String> searchDomains) { 4118 if (dnsServers == null) { 4119 restore(); 4120 return; 4121 } 4122 4123 // Convert DNS servers into addresses. 4124 List<InetAddress> addresses = new ArrayList<InetAddress>(); 4125 for (String address : dnsServers) { 4126 // Double check the addresses and remove invalid ones. 4127 try { 4128 addresses.add(InetAddress.parseNumericAddress(address)); 4129 } catch (Exception e) { 4130 // ignore 4131 } 4132 } 4133 if (addresses.isEmpty()) { 4134 restore(); 4135 return; 4136 } 4137 4138 // Concatenate search domains into a string. 4139 StringBuilder buffer = new StringBuilder(); 4140 if (searchDomains != null) { 4141 for (String domain : searchDomains) { 4142 buffer.append(domain).append(' '); 4143 } 4144 } 4145 String domains = buffer.toString().trim(); 4146 4147 // Apply DNS changes. 4148 synchronized (mDnsLock) { 4149 // TODO: Re-enable this when the netId of the VPN is known. 4150 // updateDnsLocked("VPN", netId, addresses, domains); 4151 } 4152 4153 // Temporarily disable the default proxy (not global). 4154 synchronized (mProxyLock) { 4155 mDefaultProxyDisabled = true; 4156 if (mGlobalProxy == null && mDefaultProxy != null) { 4157 sendProxyBroadcast(null); 4158 } 4159 } 4160 4161 // TODO: support proxy per network. 4162 } 4163 4164 public void restore() { 4165 synchronized (mProxyLock) { 4166 mDefaultProxyDisabled = false; 4167 if (mGlobalProxy == null && mDefaultProxy != null) { 4168 sendProxyBroadcast(mDefaultProxy); 4169 } 4170 } 4171 } 4172 4173 public void protect(ParcelFileDescriptor socket) { 4174 try { 4175 final int mark = mNetd.getMarkForProtect(); 4176 NetworkUtils.markSocket(socket.getFd(), mark); 4177 } catch (RemoteException e) { 4178 } 4179 } 4180 4181 public void setRoutes(String interfaze, List<RouteInfo> routes) { 4182 for (RouteInfo route : routes) { 4183 try { 4184 mNetd.setMarkedForwardingRoute(interfaze, route); 4185 } catch (RemoteException e) { 4186 } 4187 } 4188 } 4189 4190 public void setMarkedForwarding(String interfaze) { 4191 try { 4192 mNetd.setMarkedForwarding(interfaze); 4193 } catch (RemoteException e) { 4194 } 4195 } 4196 4197 public void clearMarkedForwarding(String interfaze) { 4198 try { 4199 mNetd.clearMarkedForwarding(interfaze); 4200 } catch (RemoteException e) { 4201 } 4202 } 4203 4204 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) { 4205 int uidStart = uid * UserHandle.PER_USER_RANGE; 4206 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1; 4207 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns); 4208 } 4209 4210 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) { 4211 int uidStart = uid * UserHandle.PER_USER_RANGE; 4212 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1; 4213 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns); 4214 } 4215 4216 public void addUidForwarding(String interfaze, int uidStart, int uidEnd, 4217 boolean forwardDns) { 4218 // TODO: Re-enable this when the netId of the VPN is known. 4219 // try { 4220 // mNetd.setUidRangeRoute(netId, uidStart, uidEnd, forwardDns); 4221 // } catch (RemoteException e) { 4222 // } 4223 4224 } 4225 4226 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd, 4227 boolean forwardDns) { 4228 // TODO: Re-enable this when the netId of the VPN is known. 4229 // try { 4230 // mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd); 4231 // } catch (RemoteException e) { 4232 // } 4233 4234 } 4235 } 4236 4237 @Override 4238 public boolean updateLockdownVpn() { 4239 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 4240 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM"); 4241 return false; 4242 } 4243 4244 // Tear down existing lockdown if profile was removed 4245 mLockdownEnabled = LockdownVpnTracker.isEnabled(); 4246 if (mLockdownEnabled) { 4247 if (!mKeyStore.isUnlocked()) { 4248 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker"); 4249 return false; 4250 } 4251 4252 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN)); 4253 final VpnProfile profile = VpnProfile.decode( 4254 profileName, mKeyStore.get(Credentials.VPN + profileName)); 4255 int user = UserHandle.getUserId(Binder.getCallingUid()); 4256 synchronized(mVpns) { 4257 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user), 4258 profile)); 4259 } 4260 } else { 4261 setLockdownTracker(null); 4262 } 4263 4264 return true; 4265 } 4266 4267 /** 4268 * Internally set new {@link LockdownVpnTracker}, shutting down any existing 4269 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown. 4270 */ 4271 private void setLockdownTracker(LockdownVpnTracker tracker) { 4272 // Shutdown any existing tracker 4273 final LockdownVpnTracker existing = mLockdownTracker; 4274 mLockdownTracker = null; 4275 if (existing != null) { 4276 existing.shutdown(); 4277 } 4278 4279 try { 4280 if (tracker != null) { 4281 mNetd.setFirewallEnabled(true); 4282 mNetd.setFirewallInterfaceRule("lo", true); 4283 mLockdownTracker = tracker; 4284 mLockdownTracker.init(); 4285 } else { 4286 mNetd.setFirewallEnabled(false); 4287 } 4288 } catch (RemoteException e) { 4289 // ignored; NMS lives inside system_server 4290 } 4291 } 4292 4293 private void throwIfLockdownEnabled() { 4294 if (mLockdownEnabled) { 4295 throw new IllegalStateException("Unavailable in lockdown mode"); 4296 } 4297 } 4298 4299 public void supplyMessenger(int networkType, Messenger messenger) { 4300 enforceConnectivityInternalPermission(); 4301 4302 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) { 4303 mNetTrackers[networkType].supplyMessenger(messenger); 4304 } 4305 } 4306 4307 public int findConnectionTypeForIface(String iface) { 4308 enforceConnectivityInternalPermission(); 4309 4310 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE; 4311 for (NetworkStateTracker tracker : mNetTrackers) { 4312 if (tracker != null) { 4313 LinkProperties lp = tracker.getLinkProperties(); 4314 if (lp != null && iface.equals(lp.getInterfaceName())) { 4315 return tracker.getNetworkInfo().getType(); 4316 } 4317 } 4318 } 4319 return ConnectivityManager.TYPE_NONE; 4320 } 4321 4322 /** 4323 * Have mobile data fail fast if enabled. 4324 * 4325 * @param enabled DctConstants.ENABLED/DISABLED 4326 */ 4327 private void setEnableFailFastMobileData(int enabled) { 4328 int tag; 4329 4330 if (enabled == DctConstants.ENABLED) { 4331 tag = mEnableFailFastMobileDataTag.incrementAndGet(); 4332 } else { 4333 tag = mEnableFailFastMobileDataTag.get(); 4334 } 4335 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag, 4336 enabled)); 4337 } 4338 4339 private boolean isMobileDataStateTrackerReady() { 4340 MobileDataStateTracker mdst = 4341 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4342 return (mdst != null) && (mdst.isReady()); 4343 } 4344 4345 /** 4346 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE) 4347 */ 4348 4349 /** 4350 * No connection was possible to the network. 4351 * This is NOT a warm sim. 4352 */ 4353 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0; 4354 4355 /** 4356 * A connection was made to the internet, all is well. 4357 * This is NOT a warm sim. 4358 */ 4359 private static final int CMP_RESULT_CODE_CONNECTABLE = 1; 4360 4361 /** 4362 * A connection was made but no dns server was available to resolve a name to address. 4363 * This is NOT a warm sim since provisioning network is supported. 4364 */ 4365 private static final int CMP_RESULT_CODE_NO_DNS = 2; 4366 4367 /** 4368 * A connection was made but could not open a TCP connection. 4369 * This is NOT a warm sim since provisioning network is supported. 4370 */ 4371 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3; 4372 4373 /** 4374 * A connection was made but there was a redirection, we appear to be in walled garden. 4375 * This is an indication of a warm sim on a mobile network such as T-Mobile. 4376 */ 4377 private static final int CMP_RESULT_CODE_REDIRECTED = 4; 4378 4379 /** 4380 * The mobile network is a provisioning network. 4381 * This is an indication of a warm sim on a mobile network such as AT&T. 4382 */ 4383 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5; 4384 4385 /** 4386 * The mobile network is provisioning 4387 */ 4388 private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6; 4389 4390 private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false); 4391 private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false); 4392 4393 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false); 4394 4395 @Override 4396 public int checkMobileProvisioning(int suggestedTimeOutMs) { 4397 int timeOutMs = -1; 4398 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs); 4399 enforceConnectivityInternalPermission(); 4400 4401 final long token = Binder.clearCallingIdentity(); 4402 try { 4403 timeOutMs = suggestedTimeOutMs; 4404 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) { 4405 timeOutMs = CheckMp.MAX_TIMEOUT_MS; 4406 } 4407 4408 // Check that mobile networks are supported 4409 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE) 4410 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) { 4411 if (DBG) log("checkMobileProvisioning: X no mobile network"); 4412 return timeOutMs; 4413 } 4414 4415 // If we're already checking don't do it again 4416 // TODO: Add a queue of results... 4417 if (mIsCheckingMobileProvisioning.getAndSet(true)) { 4418 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment"); 4419 return timeOutMs; 4420 } 4421 4422 // Start off with mobile notification off 4423 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null); 4424 4425 CheckMp checkMp = new CheckMp(mContext, this); 4426 CheckMp.CallBack cb = new CheckMp.CallBack() { 4427 @Override 4428 void onComplete(Integer result) { 4429 if (DBG) log("CheckMp.onComplete: result=" + result); 4430 NetworkInfo ni = 4431 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo(); 4432 switch(result) { 4433 case CMP_RESULT_CODE_CONNECTABLE: 4434 case CMP_RESULT_CODE_NO_CONNECTION: 4435 case CMP_RESULT_CODE_NO_DNS: 4436 case CMP_RESULT_CODE_NO_TCP_CONNECTION: { 4437 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection"); 4438 break; 4439 } 4440 case CMP_RESULT_CODE_REDIRECTED: { 4441 if (DBG) log("CheckMp.onComplete: warm sim"); 4442 String url = getMobileProvisioningUrl(); 4443 if (TextUtils.isEmpty(url)) { 4444 url = getMobileRedirectedProvisioningUrl(); 4445 } 4446 if (TextUtils.isEmpty(url) == false) { 4447 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url); 4448 setProvNotificationVisible(true, 4449 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(), 4450 url); 4451 } else { 4452 if (DBG) log("CheckMp.onComplete: warm (redirected), no url"); 4453 } 4454 break; 4455 } 4456 case CMP_RESULT_CODE_PROVISIONING_NETWORK: { 4457 String url = getMobileProvisioningUrl(); 4458 if (TextUtils.isEmpty(url) == false) { 4459 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url); 4460 setProvNotificationVisible(true, 4461 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(), 4462 url); 4463 // Mark that we've got a provisioning network and 4464 // Disable Mobile Data until user actually starts provisioning. 4465 mIsProvisioningNetwork.set(true); 4466 MobileDataStateTracker mdst = (MobileDataStateTracker) 4467 mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4468 4469 // Disable radio until user starts provisioning 4470 mdst.setRadio(false); 4471 } else { 4472 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url"); 4473 } 4474 break; 4475 } 4476 case CMP_RESULT_CODE_IS_PROVISIONING: { 4477 // FIXME: Need to know when provisioning is done. Probably we can 4478 // check the completion status if successful we're done if we 4479 // "timedout" or still connected to provisioning APN turn off data? 4480 if (DBG) log("CheckMp.onComplete: provisioning started"); 4481 mIsStartingProvisioning.set(false); 4482 break; 4483 } 4484 default: { 4485 loge("CheckMp.onComplete: ignore unexpected result=" + result); 4486 break; 4487 } 4488 } 4489 mIsCheckingMobileProvisioning.set(false); 4490 } 4491 }; 4492 CheckMp.Params params = 4493 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb); 4494 if (DBG) log("checkMobileProvisioning: params=" + params); 4495 // TODO: Reenable when calls to the now defunct 4496 // MobileDataStateTracker.isProvisioningNetwork() are removed. 4497 // This code should be moved to the Telephony code. 4498 // checkMp.execute(params); 4499 } finally { 4500 Binder.restoreCallingIdentity(token); 4501 if (DBG) log("checkMobileProvisioning: X"); 4502 } 4503 return timeOutMs; 4504 } 4505 4506 static class CheckMp extends 4507 AsyncTask<CheckMp.Params, Void, Integer> { 4508 private static final String CHECKMP_TAG = "CheckMp"; 4509 4510 // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures 4511 private static boolean mTestingFailures; 4512 4513 // Choosing 4 loops as half of them will use HTTPS and the other half HTTP 4514 private static final int MAX_LOOPS = 4; 4515 4516 // Number of milli-seconds to complete all of the retires 4517 public static final int MAX_TIMEOUT_MS = 60000; 4518 4519 // The socket should retry only 5 seconds, the default is longer 4520 private static final int SOCKET_TIMEOUT_MS = 5000; 4521 4522 // Sleep time for network errors 4523 private static final int NET_ERROR_SLEEP_SEC = 3; 4524 4525 // Sleep time for network route establishment 4526 private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3; 4527 4528 // Short sleep time for polling :( 4529 private static final int POLLING_SLEEP_SEC = 1; 4530 4531 private Context mContext; 4532 private ConnectivityService mCs; 4533 private TelephonyManager mTm; 4534 private Params mParams; 4535 4536 /** 4537 * Parameters for AsyncTask.execute 4538 */ 4539 static class Params { 4540 private String mUrl; 4541 private long mTimeOutMs; 4542 private CallBack mCb; 4543 4544 Params(String url, long timeOutMs, CallBack cb) { 4545 mUrl = url; 4546 mTimeOutMs = timeOutMs; 4547 mCb = cb; 4548 } 4549 4550 @Override 4551 public String toString() { 4552 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}"; 4553 } 4554 } 4555 4556 // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be 4557 // issued by name or ip address, for Google its by name so when we construct 4558 // this HostnameVerifier we'll pass the original Uri and use it to verify 4559 // the host. If the host name in the original uril fails we'll test the 4560 // hostname parameter just incase things change. 4561 static class CheckMpHostnameVerifier implements HostnameVerifier { 4562 Uri mOrgUri; 4563 4564 CheckMpHostnameVerifier(Uri orgUri) { 4565 mOrgUri = orgUri; 4566 } 4567 4568 @Override 4569 public boolean verify(String hostname, SSLSession session) { 4570 HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); 4571 String orgUriHost = mOrgUri.getHost(); 4572 boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session); 4573 if (DBG) { 4574 log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname 4575 + " orgUriHost=" + orgUriHost); 4576 } 4577 return retVal; 4578 } 4579 } 4580 4581 /** 4582 * The call back object passed in Params. onComplete will be called 4583 * on the main thread. 4584 */ 4585 abstract static class CallBack { 4586 // Called on the main thread. 4587 abstract void onComplete(Integer result); 4588 } 4589 4590 public CheckMp(Context context, ConnectivityService cs) { 4591 if (Build.IS_DEBUGGABLE) { 4592 mTestingFailures = 4593 SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1; 4594 } else { 4595 mTestingFailures = false; 4596 } 4597 4598 mContext = context; 4599 mCs = cs; 4600 4601 // Setup access to TelephonyService we'll be using. 4602 mTm = (TelephonyManager) mContext.getSystemService( 4603 Context.TELEPHONY_SERVICE); 4604 } 4605 4606 /** 4607 * Get the default url to use for the test. 4608 */ 4609 public String getDefaultUrl() { 4610 // See http://go/clientsdns for usage approval 4611 String server = Settings.Global.getString(mContext.getContentResolver(), 4612 Settings.Global.CAPTIVE_PORTAL_SERVER); 4613 if (server == null) { 4614 server = "clients3.google.com"; 4615 } 4616 return "http://" + server + "/generate_204"; 4617 } 4618 4619 /** 4620 * Detect if its possible to connect to the http url. DNS based detection techniques 4621 * do not work at all hotspots. The best way to check is to perform a request to 4622 * a known address that fetches the data we expect. 4623 */ 4624 private synchronized Integer isMobileOk(Params params) { 4625 Integer result = CMP_RESULT_CODE_NO_CONNECTION; 4626 Uri orgUri = Uri.parse(params.mUrl); 4627 Random rand = new Random(); 4628 mParams = params; 4629 4630 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) { 4631 result = CMP_RESULT_CODE_NO_CONNECTION; 4632 log("isMobileOk: X not mobile capable result=" + result); 4633 return result; 4634 } 4635 4636 if (mCs.mIsStartingProvisioning.get()) { 4637 result = CMP_RESULT_CODE_IS_PROVISIONING; 4638 log("isMobileOk: X is provisioning result=" + result); 4639 return result; 4640 } 4641 4642 // See if we've already determined we've got a provisioning connection, 4643 // if so we don't need to do anything active. 4644 MobileDataStateTracker mdstDefault = (MobileDataStateTracker) 4645 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4646 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork(); 4647 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning); 4648 4649 MobileDataStateTracker mdstHipri = (MobileDataStateTracker) 4650 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4651 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork(); 4652 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning); 4653 4654 if (isDefaultProvisioning || isHipriProvisioning) { 4655 result = CMP_RESULT_CODE_PROVISIONING_NETWORK; 4656 log("isMobileOk: X default || hipri is provisioning result=" + result); 4657 return result; 4658 } 4659 4660 try { 4661 // Continue trying to connect until time has run out 4662 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs; 4663 4664 if (!mCs.isMobileDataStateTrackerReady()) { 4665 // Wait for MobileDataStateTracker to be ready. 4666 if (DBG) log("isMobileOk: mdst is not ready"); 4667 while(SystemClock.elapsedRealtime() < endTime) { 4668 if (mCs.isMobileDataStateTrackerReady()) { 4669 // Enable fail fast as we'll do retries here and use a 4670 // hipri connection so the default connection stays active. 4671 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data"); 4672 mCs.setEnableFailFastMobileData(DctConstants.ENABLED); 4673 break; 4674 } 4675 sleep(POLLING_SLEEP_SEC); 4676 } 4677 } 4678 4679 log("isMobileOk: start hipri url=" + params.mUrl); 4680 4681 // First wait until we can start using hipri 4682 Binder binder = new Binder(); 4683 while(SystemClock.elapsedRealtime() < endTime) { 4684 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, 4685 Phone.FEATURE_ENABLE_HIPRI, binder); 4686 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE) 4687 || (ret == PhoneConstants.APN_REQUEST_STARTED)) { 4688 log("isMobileOk: hipri started"); 4689 break; 4690 } 4691 if (VDBG) log("isMobileOk: hipri not started yet"); 4692 result = CMP_RESULT_CODE_NO_CONNECTION; 4693 sleep(POLLING_SLEEP_SEC); 4694 } 4695 4696 // Continue trying to connect until time has run out 4697 while(SystemClock.elapsedRealtime() < endTime) { 4698 try { 4699 // Wait for hipri to connect. 4700 // TODO: Don't poll and handle situation where hipri fails 4701 // because default is retrying. See b/9569540 4702 NetworkInfo.State state = mCs 4703 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); 4704 if (state != NetworkInfo.State.CONNECTED) { 4705 if (true/*VDBG*/) { 4706 log("isMobileOk: not connected ni=" + 4707 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI)); 4708 } 4709 sleep(POLLING_SLEEP_SEC); 4710 result = CMP_RESULT_CODE_NO_CONNECTION; 4711 continue; 4712 } 4713 4714 // Hipri has started check if this is a provisioning url 4715 MobileDataStateTracker mdst = (MobileDataStateTracker) 4716 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4717 if (mdst.isProvisioningNetwork()) { 4718 result = CMP_RESULT_CODE_PROVISIONING_NETWORK; 4719 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result); 4720 return result; 4721 } else { 4722 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue"); 4723 } 4724 4725 // Get of the addresses associated with the url host. We need to use the 4726 // address otherwise HttpURLConnection object will use the name to get 4727 // the addresses and will try every address but that will bypass the 4728 // route to host we setup and the connection could succeed as the default 4729 // interface might be connected to the internet via wifi or other interface. 4730 InetAddress[] addresses; 4731 try { 4732 addresses = InetAddress.getAllByName(orgUri.getHost()); 4733 } catch (UnknownHostException e) { 4734 result = CMP_RESULT_CODE_NO_DNS; 4735 log("isMobileOk: X UnknownHostException result=" + result); 4736 return result; 4737 } 4738 log("isMobileOk: addresses=" + inetAddressesToString(addresses)); 4739 4740 // Get the type of addresses supported by this link 4741 LinkProperties lp = mCs.getLinkPropertiesForTypeInternal( 4742 ConnectivityManager.TYPE_MOBILE_HIPRI); 4743 boolean linkHasIpv4 = lp.hasIPv4Address(); 4744 boolean linkHasIpv6 = lp.hasGlobalIPv6Address(); 4745 log("isMobileOk: linkHasIpv4=" + linkHasIpv4 4746 + " linkHasIpv6=" + linkHasIpv6); 4747 4748 final ArrayList<InetAddress> validAddresses = 4749 new ArrayList<InetAddress>(addresses.length); 4750 4751 for (InetAddress addr : addresses) { 4752 if (((addr instanceof Inet4Address) && linkHasIpv4) || 4753 ((addr instanceof Inet6Address) && linkHasIpv6)) { 4754 validAddresses.add(addr); 4755 } 4756 } 4757 4758 if (validAddresses.size() == 0) { 4759 return CMP_RESULT_CODE_NO_CONNECTION; 4760 } 4761 4762 int addrTried = 0; 4763 while (true) { 4764 // Loop through at most MAX_LOOPS valid addresses or until 4765 // we run out of time 4766 if (addrTried++ >= MAX_LOOPS) { 4767 log("isMobileOk: too many loops tried - giving up"); 4768 break; 4769 } 4770 if (SystemClock.elapsedRealtime() >= endTime) { 4771 log("isMobileOk: spend too much time - giving up"); 4772 break; 4773 } 4774 4775 InetAddress hostAddr = validAddresses.get(rand.nextInt( 4776 validAddresses.size())); 4777 4778 // Make a route to host so we check the specific interface. 4779 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI, 4780 hostAddr.getAddress(), null)) { 4781 // Wait a short time to be sure the route is established ?? 4782 log("isMobileOk:" 4783 + " wait to establish route to hostAddr=" + hostAddr); 4784 sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC); 4785 } else { 4786 log("isMobileOk:" 4787 + " could not establish route to hostAddr=" + hostAddr); 4788 // Wait a short time before the next attempt 4789 sleep(NET_ERROR_SLEEP_SEC); 4790 continue; 4791 } 4792 4793 // Rewrite the url to have numeric address to use the specific route 4794 // using http for half the attempts and https for the other half. 4795 // Doing https first and http second as on a redirected walled garden 4796 // such as t-mobile uses we get a SocketTimeoutException: "SSL 4797 // handshake timed out" which we declare as 4798 // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by 4799 // having http second we will be using logic used for some time. 4800 URL newUrl; 4801 String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http"; 4802 newUrl = new URL(scheme, hostAddr.getHostAddress(), 4803 orgUri.getPath()); 4804 log("isMobileOk: newUrl=" + newUrl); 4805 4806 HttpURLConnection urlConn = null; 4807 try { 4808 // Open the connection set the request headers and get the response 4809 urlConn = (HttpURLConnection)newUrl.openConnection( 4810 java.net.Proxy.NO_PROXY); 4811 if (scheme.equals("https")) { 4812 ((HttpsURLConnection)urlConn).setHostnameVerifier( 4813 new CheckMpHostnameVerifier(orgUri)); 4814 } 4815 urlConn.setInstanceFollowRedirects(false); 4816 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS); 4817 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS); 4818 urlConn.setUseCaches(false); 4819 urlConn.setAllowUserInteraction(false); 4820 // Set the "Connection" to "Close" as by default "Keep-Alive" 4821 // is used which is useless in this case. 4822 urlConn.setRequestProperty("Connection", "close"); 4823 int responseCode = urlConn.getResponseCode(); 4824 4825 // For debug display the headers 4826 Map<String, List<String>> headers = urlConn.getHeaderFields(); 4827 log("isMobileOk: headers=" + headers); 4828 4829 // Close the connection 4830 urlConn.disconnect(); 4831 urlConn = null; 4832 4833 if (mTestingFailures) { 4834 // Pretend no connection, this tests using http and https 4835 result = CMP_RESULT_CODE_NO_CONNECTION; 4836 log("isMobileOk: TESTING_FAILURES, pretend no connction"); 4837 continue; 4838 } 4839 4840 if (responseCode == 204) { 4841 // Return 4842 result = CMP_RESULT_CODE_CONNECTABLE; 4843 log("isMobileOk: X got expected responseCode=" + responseCode 4844 + " result=" + result); 4845 return result; 4846 } else { 4847 // Retry to be sure this was redirected, we've gotten 4848 // occasions where a server returned 200 even though 4849 // the device didn't have a "warm" sim. 4850 log("isMobileOk: not expected responseCode=" + responseCode); 4851 // TODO - it would be nice in the single-address case to do 4852 // another DNS resolve here, but flushing the cache is a bit 4853 // heavy-handed. 4854 result = CMP_RESULT_CODE_REDIRECTED; 4855 } 4856 } catch (Exception e) { 4857 log("isMobileOk: HttpURLConnection Exception" + e); 4858 result = CMP_RESULT_CODE_NO_TCP_CONNECTION; 4859 if (urlConn != null) { 4860 urlConn.disconnect(); 4861 urlConn = null; 4862 } 4863 sleep(NET_ERROR_SLEEP_SEC); 4864 continue; 4865 } 4866 } 4867 log("isMobileOk: X loops|timed out result=" + result); 4868 return result; 4869 } catch (Exception e) { 4870 log("isMobileOk: Exception e=" + e); 4871 continue; 4872 } 4873 } 4874 log("isMobileOk: timed out"); 4875 } finally { 4876 log("isMobileOk: F stop hipri"); 4877 mCs.setEnableFailFastMobileData(DctConstants.DISABLED); 4878 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, 4879 Phone.FEATURE_ENABLE_HIPRI); 4880 4881 // Wait for hipri to disconnect. 4882 long endTime = SystemClock.elapsedRealtime() + 5000; 4883 4884 while(SystemClock.elapsedRealtime() < endTime) { 4885 NetworkInfo.State state = mCs 4886 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); 4887 if (state != NetworkInfo.State.DISCONNECTED) { 4888 if (VDBG) { 4889 log("isMobileOk: connected ni=" + 4890 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI)); 4891 } 4892 sleep(POLLING_SLEEP_SEC); 4893 continue; 4894 } 4895 } 4896 4897 log("isMobileOk: X result=" + result); 4898 } 4899 return result; 4900 } 4901 4902 @Override 4903 protected Integer doInBackground(Params... params) { 4904 return isMobileOk(params[0]); 4905 } 4906 4907 @Override 4908 protected void onPostExecute(Integer result) { 4909 log("onPostExecute: result=" + result); 4910 if ((mParams != null) && (mParams.mCb != null)) { 4911 mParams.mCb.onComplete(result); 4912 } 4913 } 4914 4915 private String inetAddressesToString(InetAddress[] addresses) { 4916 StringBuffer sb = new StringBuffer(); 4917 boolean firstTime = true; 4918 for(InetAddress addr : addresses) { 4919 if (firstTime) { 4920 firstTime = false; 4921 } else { 4922 sb.append(","); 4923 } 4924 sb.append(addr); 4925 } 4926 return sb.toString(); 4927 } 4928 4929 private void printNetworkInfo() { 4930 boolean hasIccCard = mTm.hasIccCard(); 4931 int simState = mTm.getSimState(); 4932 log("hasIccCard=" + hasIccCard 4933 + " simState=" + simState); 4934 NetworkInfo[] ni = mCs.getAllNetworkInfo(); 4935 if (ni != null) { 4936 log("ni.length=" + ni.length); 4937 for (NetworkInfo netInfo: ni) { 4938 log("netInfo=" + netInfo.toString()); 4939 } 4940 } else { 4941 log("no network info ni=null"); 4942 } 4943 } 4944 4945 /** 4946 * Sleep for a few seconds then return. 4947 * @param seconds 4948 */ 4949 private static void sleep(int seconds) { 4950 long stopTime = System.nanoTime() + (seconds * 1000000000); 4951 long sleepTime; 4952 while ((sleepTime = stopTime - System.nanoTime()) > 0) { 4953 try { 4954 Thread.sleep(sleepTime / 1000000); 4955 } catch (InterruptedException ignored) { 4956 } 4957 } 4958 } 4959 4960 private static void log(String s) { 4961 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s); 4962 } 4963 } 4964 4965 // TODO: Move to ConnectivityManager and make public? 4966 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION = 4967 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION"; 4968 4969 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() { 4970 @Override 4971 public void onReceive(Context context, Intent intent) { 4972 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) { 4973 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL")); 4974 } 4975 } 4976 }; 4977 4978 private void handleMobileProvisioningAction(String url) { 4979 // Mark notification as not visible 4980 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null); 4981 4982 // Check airplane mode 4983 boolean isAirplaneModeOn = Settings.System.getInt(mContext.getContentResolver(), 4984 Settings.Global.AIRPLANE_MODE_ON, 0) == 1; 4985 // If provisioning network and not in airplane mode handle as a special case, 4986 // otherwise launch browser with the intent directly. 4987 if (mIsProvisioningNetwork.get() && !isAirplaneModeOn) { 4988 if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch"); 4989 mIsProvisioningNetwork.set(false); 4990// mIsStartingProvisioning.set(true); 4991// MobileDataStateTracker mdst = (MobileDataStateTracker) 4992// mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4993 // Radio was disabled on CMP_RESULT_CODE_PROVISIONING_NETWORK, enable it here 4994// mdst.setRadio(true); 4995// mdst.setEnableFailFastMobileData(DctConstants.ENABLED); 4996// mdst.enableMobileProvisioning(url); 4997 } else { 4998 if (DBG) log("handleMobileProvisioningAction: not prov network"); 4999 mIsProvisioningNetwork.set(false); 5000 // Check for apps that can handle provisioning first 5001 Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP); 5002 provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX 5003 + mTelephonyManager.getSimOperator()); 5004 if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */) 5005 != null) { 5006 provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 5007 Intent.FLAG_ACTIVITY_NEW_TASK); 5008 mContext.startActivity(provisioningIntent); 5009 } else { 5010 // If no apps exist, use standard URL ACTION_VIEW method 5011 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, 5012 Intent.CATEGORY_APP_BROWSER); 5013 newIntent.setData(Uri.parse(url)); 5014 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 5015 Intent.FLAG_ACTIVITY_NEW_TASK); 5016 try { 5017 mContext.startActivity(newIntent); 5018 } catch (ActivityNotFoundException e) { 5019 loge("handleMobileProvisioningAction: startActivity failed" + e); 5020 } 5021 } 5022 } 5023 } 5024 5025 private static final String NOTIFICATION_ID = "CaptivePortal.Notification"; 5026 private volatile boolean mIsNotificationVisible = false; 5027 5028 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo, 5029 String url) { 5030 if (DBG) { 5031 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType 5032 + " extraInfo=" + extraInfo + " url=" + url); 5033 } 5034 5035 Resources r = Resources.getSystem(); 5036 NotificationManager notificationManager = (NotificationManager) mContext 5037 .getSystemService(Context.NOTIFICATION_SERVICE); 5038 5039 if (visible) { 5040 CharSequence title; 5041 CharSequence details; 5042 int icon; 5043 Intent intent; 5044 Notification notification = new Notification(); 5045 switch (networkType) { 5046 case ConnectivityManager.TYPE_WIFI: 5047 title = r.getString(R.string.wifi_available_sign_in, 0); 5048 details = r.getString(R.string.network_available_sign_in_detailed, 5049 extraInfo); 5050 icon = R.drawable.stat_notify_wifi_in_range; 5051 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 5052 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 5053 Intent.FLAG_ACTIVITY_NEW_TASK); 5054 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0); 5055 break; 5056 case ConnectivityManager.TYPE_MOBILE: 5057 case ConnectivityManager.TYPE_MOBILE_HIPRI: 5058 title = r.getString(R.string.network_available_sign_in, 0); 5059 // TODO: Change this to pull from NetworkInfo once a printable 5060 // name has been added to it 5061 details = mTelephonyManager.getNetworkOperatorName(); 5062 icon = R.drawable.stat_notify_rssi_in_range; 5063 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION); 5064 intent.putExtra("EXTRA_URL", url); 5065 intent.setFlags(0); 5066 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); 5067 break; 5068 default: 5069 title = r.getString(R.string.network_available_sign_in, 0); 5070 details = r.getString(R.string.network_available_sign_in_detailed, 5071 extraInfo); 5072 icon = R.drawable.stat_notify_rssi_in_range; 5073 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 5074 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 5075 Intent.FLAG_ACTIVITY_NEW_TASK); 5076 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0); 5077 break; 5078 } 5079 5080 notification.when = 0; 5081 notification.icon = icon; 5082 notification.flags = Notification.FLAG_AUTO_CANCEL; 5083 notification.tickerText = title; 5084 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent); 5085 5086 try { 5087 notificationManager.notify(NOTIFICATION_ID, networkType, notification); 5088 } catch (NullPointerException npe) { 5089 loge("setNotificaitionVisible: visible notificationManager npe=" + npe); 5090 npe.printStackTrace(); 5091 } 5092 } else { 5093 try { 5094 notificationManager.cancel(NOTIFICATION_ID, networkType); 5095 } catch (NullPointerException npe) { 5096 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe); 5097 npe.printStackTrace(); 5098 } 5099 } 5100 mIsNotificationVisible = visible; 5101 } 5102 5103 /** Location to an updatable file listing carrier provisioning urls. 5104 * An example: 5105 * 5106 * <?xml version="1.0" encoding="utf-8"?> 5107 * <provisioningUrls> 5108 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl> 5109 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl> 5110 * </provisioningUrls> 5111 */ 5112 private static final String PROVISIONING_URL_PATH = 5113 "/data/misc/radio/provisioning_urls.xml"; 5114 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH); 5115 5116 /** XML tag for root element. */ 5117 private static final String TAG_PROVISIONING_URLS = "provisioningUrls"; 5118 /** XML tag for individual url */ 5119 private static final String TAG_PROVISIONING_URL = "provisioningUrl"; 5120 /** XML tag for redirected url */ 5121 private static final String TAG_REDIRECTED_URL = "redirectedUrl"; 5122 /** XML attribute for mcc */ 5123 private static final String ATTR_MCC = "mcc"; 5124 /** XML attribute for mnc */ 5125 private static final String ATTR_MNC = "mnc"; 5126 5127 private static final int REDIRECTED_PROVISIONING = 1; 5128 private static final int PROVISIONING = 2; 5129 5130 private String getProvisioningUrlBaseFromFile(int type) { 5131 FileReader fileReader = null; 5132 XmlPullParser parser = null; 5133 Configuration config = mContext.getResources().getConfiguration(); 5134 String tagType; 5135 5136 switch (type) { 5137 case PROVISIONING: 5138 tagType = TAG_PROVISIONING_URL; 5139 break; 5140 case REDIRECTED_PROVISIONING: 5141 tagType = TAG_REDIRECTED_URL; 5142 break; 5143 default: 5144 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " + 5145 type); 5146 } 5147 5148 try { 5149 fileReader = new FileReader(mProvisioningUrlFile); 5150 parser = Xml.newPullParser(); 5151 parser.setInput(fileReader); 5152 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS); 5153 5154 while (true) { 5155 XmlUtils.nextElement(parser); 5156 5157 String element = parser.getName(); 5158 if (element == null) break; 5159 5160 if (element.equals(tagType)) { 5161 String mcc = parser.getAttributeValue(null, ATTR_MCC); 5162 try { 5163 if (mcc != null && Integer.parseInt(mcc) == config.mcc) { 5164 String mnc = parser.getAttributeValue(null, ATTR_MNC); 5165 if (mnc != null && Integer.parseInt(mnc) == config.mnc) { 5166 parser.next(); 5167 if (parser.getEventType() == XmlPullParser.TEXT) { 5168 return parser.getText(); 5169 } 5170 } 5171 } 5172 } catch (NumberFormatException e) { 5173 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e); 5174 } 5175 } 5176 } 5177 return null; 5178 } catch (FileNotFoundException e) { 5179 loge("Carrier Provisioning Urls file not found"); 5180 } catch (XmlPullParserException e) { 5181 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e); 5182 } catch (IOException e) { 5183 loge("I/O exception reading Carrier Provisioning Urls file: " + e); 5184 } finally { 5185 if (fileReader != null) { 5186 try { 5187 fileReader.close(); 5188 } catch (IOException e) {} 5189 } 5190 } 5191 return null; 5192 } 5193 5194 @Override 5195 public String getMobileRedirectedProvisioningUrl() { 5196 enforceConnectivityInternalPermission(); 5197 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING); 5198 if (TextUtils.isEmpty(url)) { 5199 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url); 5200 } 5201 return url; 5202 } 5203 5204 @Override 5205 public String getMobileProvisioningUrl() { 5206 enforceConnectivityInternalPermission(); 5207 String url = getProvisioningUrlBaseFromFile(PROVISIONING); 5208 if (TextUtils.isEmpty(url)) { 5209 url = mContext.getResources().getString(R.string.mobile_provisioning_url); 5210 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url); 5211 } else { 5212 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url); 5213 } 5214 // populate the iccid, imei and phone number in the provisioning url. 5215 if (!TextUtils.isEmpty(url)) { 5216 String phoneNumber = mTelephonyManager.getLine1Number(); 5217 if (TextUtils.isEmpty(phoneNumber)) { 5218 phoneNumber = "0000000000"; 5219 } 5220 url = String.format(url, 5221 mTelephonyManager.getSimSerialNumber() /* ICCID */, 5222 mTelephonyManager.getDeviceId() /* IMEI */, 5223 phoneNumber /* Phone numer */); 5224 } 5225 5226 return url; 5227 } 5228 5229 @Override 5230 public void setProvisioningNotificationVisible(boolean visible, int networkType, 5231 String extraInfo, String url) { 5232 enforceConnectivityInternalPermission(); 5233 setProvNotificationVisible(visible, networkType, extraInfo, url); 5234 } 5235 5236 @Override 5237 public void setAirplaneMode(boolean enable) { 5238 enforceConnectivityInternalPermission(); 5239 final long ident = Binder.clearCallingIdentity(); 5240 try { 5241 final ContentResolver cr = mContext.getContentResolver(); 5242 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 5243 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 5244 intent.putExtra("state", enable); 5245 mContext.sendBroadcast(intent); 5246 } finally { 5247 Binder.restoreCallingIdentity(ident); 5248 } 5249 } 5250 5251 private void onUserStart(int userId) { 5252 synchronized(mVpns) { 5253 Vpn userVpn = mVpns.get(userId); 5254 if (userVpn != null) { 5255 loge("Starting user already has a VPN"); 5256 return; 5257 } 5258 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId); 5259 mVpns.put(userId, userVpn); 5260 userVpn.startMonitoring(mContext, mTrackerHandler); 5261 } 5262 } 5263 5264 private void onUserStop(int userId) { 5265 synchronized(mVpns) { 5266 Vpn userVpn = mVpns.get(userId); 5267 if (userVpn == null) { 5268 loge("Stopping user has no VPN"); 5269 return; 5270 } 5271 mVpns.delete(userId); 5272 } 5273 } 5274 5275 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() { 5276 @Override 5277 public void onReceive(Context context, Intent intent) { 5278 final String action = intent.getAction(); 5279 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 5280 if (userId == UserHandle.USER_NULL) return; 5281 5282 if (Intent.ACTION_USER_STARTING.equals(action)) { 5283 onUserStart(userId); 5284 } else if (Intent.ACTION_USER_STOPPING.equals(action)) { 5285 onUserStop(userId); 5286 } 5287 } 5288 }; 5289 5290 @Override 5291 public LinkQualityInfo getLinkQualityInfo(int networkType) { 5292 enforceAccessPermission(); 5293 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) { 5294 return mNetTrackers[networkType].getLinkQualityInfo(); 5295 } else { 5296 return null; 5297 } 5298 } 5299 5300 @Override 5301 public LinkQualityInfo getActiveLinkQualityInfo() { 5302 enforceAccessPermission(); 5303 if (isNetworkTypeValid(mActiveDefaultNetwork) && 5304 mNetTrackers[mActiveDefaultNetwork] != null) { 5305 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo(); 5306 } else { 5307 return null; 5308 } 5309 } 5310 5311 @Override 5312 public LinkQualityInfo[] getAllLinkQualityInfo() { 5313 enforceAccessPermission(); 5314 final ArrayList<LinkQualityInfo> result = Lists.newArrayList(); 5315 for (NetworkStateTracker tracker : mNetTrackers) { 5316 if (tracker != null) { 5317 LinkQualityInfo li = tracker.getLinkQualityInfo(); 5318 if (li != null) { 5319 result.add(li); 5320 } 5321 } 5322 } 5323 5324 return result.toArray(new LinkQualityInfo[result.size()]); 5325 } 5326 5327 /* Infrastructure for network sampling */ 5328 5329 private void handleNetworkSamplingTimeout() { 5330 5331 log("Sampling interval elapsed, updating statistics .."); 5332 5333 // initialize list of interfaces .. 5334 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample = 5335 new HashMap<String, SamplingDataTracker.SamplingSnapshot>(); 5336 for (NetworkStateTracker tracker : mNetTrackers) { 5337 if (tracker != null) { 5338 String ifaceName = tracker.getNetworkInterfaceName(); 5339 if (ifaceName != null) { 5340 mapIfaceToSample.put(ifaceName, null); 5341 } 5342 } 5343 } 5344 5345 // Read samples for all interfaces 5346 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample); 5347 5348 // process samples for all networks 5349 for (NetworkStateTracker tracker : mNetTrackers) { 5350 if (tracker != null) { 5351 String ifaceName = tracker.getNetworkInterfaceName(); 5352 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName); 5353 if (ss != null) { 5354 // end the previous sampling cycle 5355 tracker.stopSampling(ss); 5356 // start a new sampling cycle .. 5357 tracker.startSampling(ss); 5358 } 5359 } 5360 } 5361 5362 log("Done."); 5363 5364 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(), 5365 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS, 5366 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS); 5367 5368 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds"); 5369 5370 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent); 5371 } 5372 5373 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) { 5374 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds; 5375 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent); 5376 } 5377 5378 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = 5379 new HashMap<Messenger, NetworkFactoryInfo>(); 5380 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = 5381 new HashMap<NetworkRequest, NetworkRequestInfo>(); 5382 5383 private static class NetworkFactoryInfo { 5384 public final String name; 5385 public final Messenger messenger; 5386 public final AsyncChannel asyncChannel; 5387 5388 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) { 5389 this.name = name; 5390 this.messenger = messenger; 5391 this.asyncChannel = asyncChannel; 5392 } 5393 } 5394 5395 private class NetworkRequestInfo implements IBinder.DeathRecipient { 5396 static final boolean REQUEST = true; 5397 static final boolean LISTEN = false; 5398 5399 final NetworkRequest request; 5400 IBinder mBinder; 5401 final int mPid; 5402 final int mUid; 5403 final Messenger messenger; 5404 final boolean isRequest; 5405 5406 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) { 5407 super(); 5408 messenger = m; 5409 request = r; 5410 mBinder = binder; 5411 mPid = getCallingPid(); 5412 mUid = getCallingUid(); 5413 this.isRequest = isRequest; 5414 5415 try { 5416 mBinder.linkToDeath(this, 0); 5417 } catch (RemoteException e) { 5418 binderDied(); 5419 } 5420 } 5421 5422 void unlinkDeathRecipient() { 5423 mBinder.unlinkToDeath(this, 0); 5424 } 5425 5426 public void binderDied() { 5427 log("ConnectivityService NetworkRequestInfo binderDied(" + 5428 request + ", " + mBinder + ")"); 5429 releaseNetworkRequest(request); 5430 } 5431 5432 public String toString() { 5433 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" + 5434 mPid + " for " + request; 5435 } 5436 } 5437 5438 @Override 5439 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities, 5440 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) { 5441 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED) 5442 == false) { 5443 enforceConnectivityInternalPermission(); 5444 } else { 5445 enforceChangePermission(); 5446 } 5447 5448 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) { 5449 throw new IllegalArgumentException("Bad timeout specified"); 5450 } 5451 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities( 5452 networkCapabilities), legacyType, nextNetworkRequestId()); 5453 if (DBG) log("requestNetwork for " + networkRequest); 5454 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, 5455 NetworkRequestInfo.REQUEST); 5456 5457 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri)); 5458 if (timeoutMs > 0) { 5459 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST, 5460 nri), timeoutMs); 5461 } 5462 return networkRequest; 5463 } 5464 5465 @Override 5466 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities, 5467 PendingIntent operation) { 5468 // TODO 5469 return null; 5470 } 5471 5472 @Override 5473 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities, 5474 Messenger messenger, IBinder binder) { 5475 enforceAccessPermission(); 5476 5477 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities( 5478 networkCapabilities), TYPE_NONE, nextNetworkRequestId()); 5479 if (DBG) log("listenForNetwork for " + networkRequest); 5480 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, 5481 NetworkRequestInfo.LISTEN); 5482 5483 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 5484 return networkRequest; 5485 } 5486 5487 @Override 5488 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities, 5489 PendingIntent operation) { 5490 } 5491 5492 @Override 5493 public void releaseNetworkRequest(NetworkRequest networkRequest) { 5494 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 5495 0, networkRequest)); 5496 } 5497 5498 @Override 5499 public void registerNetworkFactory(Messenger messenger, String name) { 5500 enforceConnectivityInternalPermission(); 5501 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel()); 5502 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi)); 5503 } 5504 5505 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) { 5506 if (VDBG) log("Got NetworkFactory Messenger for " + nfi.name); 5507 mNetworkFactoryInfos.put(nfi.messenger, nfi); 5508 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger); 5509 } 5510 5511 @Override 5512 public void unregisterNetworkFactory(Messenger messenger) { 5513 enforceConnectivityInternalPermission(); 5514 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger)); 5515 } 5516 5517 private void handleUnregisterNetworkFactory(Messenger messenger) { 5518 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger); 5519 if (nfi == null) { 5520 if (VDBG) log("Failed to find Messenger in unregisterNetworkFactory"); 5521 return; 5522 } 5523 if (VDBG) log("unregisterNetworkFactory for " + nfi.name); 5524 } 5525 5526 /** 5527 * NetworkAgentInfo supporting a request by requestId. 5528 * These have already been vetted (their Capabilities satisfy the request) 5529 * and the are the highest scored network available. 5530 * the are keyed off the Requests requestId. 5531 */ 5532 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = 5533 new SparseArray<NetworkAgentInfo>(); 5534 5535 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = 5536 new SparseArray<NetworkAgentInfo>(); 5537 5538 // NetworkAgentInfo keyed off its connecting messenger 5539 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays 5540 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = 5541 new HashMap<Messenger, NetworkAgentInfo>(); 5542 5543 private final NetworkRequest mDefaultRequest; 5544 5545 public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo, 5546 LinkProperties linkProperties, NetworkCapabilities networkCapabilities, 5547 int currentScore) { 5548 enforceConnectivityInternalPermission(); 5549 5550 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), nextNetId(), 5551 new NetworkInfo(networkInfo), new LinkProperties(linkProperties), 5552 new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler); 5553 if (VDBG) log("registerNetworkAgent " + nai); 5554 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai)); 5555 } 5556 5557 private void handleRegisterNetworkAgent(NetworkAgentInfo na) { 5558 if (VDBG) log("Got NetworkAgent Messenger"); 5559 mNetworkAgentInfos.put(na.messenger, na); 5560 mNetworkForNetId.put(na.network.netId, na); 5561 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger); 5562 NetworkInfo networkInfo = na.networkInfo; 5563 na.networkInfo = null; 5564 updateNetworkInfo(na, networkInfo); 5565 } 5566 5567 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) { 5568 LinkProperties newLp = networkAgent.linkProperties; 5569 int netId = networkAgent.network.netId; 5570 5571 updateInterfaces(newLp, oldLp, netId); 5572 updateMtu(newLp, oldLp); 5573 // TODO - figure out what to do for clat 5574// for (LinkProperties lp : newLp.getStackedLinks()) { 5575// updateMtu(lp, null); 5576// } 5577 updateRoutes(newLp, oldLp, netId); 5578 updateDnses(newLp, oldLp, netId); 5579 updateClat(newLp, oldLp, networkAgent); 5580 } 5581 5582 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) { 5583 // Update 464xlat state. 5584 if (mClat.requiresClat(na)) { 5585 5586 // If the connection was previously using clat, but is not using it now, stop the clat 5587 // daemon. Normally, this happens automatically when the connection disconnects, but if 5588 // the disconnect is not reported, or if the connection's LinkProperties changed for 5589 // some other reason (e.g., handoff changes the IP addresses on the link), it would 5590 // still be running. If it's not running, then stopping it is a no-op. 5591 if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) { 5592 mClat.stopClat(); 5593 } 5594 // If the link requires clat to be running, then start the daemon now. 5595 if (na.networkInfo.isConnected()) { 5596 mClat.startClat(na); 5597 } else { 5598 mClat.stopClat(); 5599 } 5600 } 5601 } 5602 5603 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) { 5604 CompareResult<String> interfaceDiff = new CompareResult<String>(); 5605 if (oldLp != null) { 5606 interfaceDiff = oldLp.compareAllInterfaceNames(newLp); 5607 } else if (newLp != null) { 5608 interfaceDiff.added = newLp.getAllInterfaceNames(); 5609 } 5610 for (String iface : interfaceDiff.added) { 5611 try { 5612 mNetd.addInterfaceToNetwork(iface, netId); 5613 } catch (Exception e) { 5614 loge("Exception adding interface: " + e); 5615 } 5616 } 5617 for (String iface : interfaceDiff.removed) { 5618 try { 5619 mNetd.removeInterfaceFromNetwork(iface, netId); 5620 } catch (Exception e) { 5621 loge("Exception removing interface: " + e); 5622 } 5623 } 5624 } 5625 5626 private void updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) { 5627 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 5628 if (oldLp != null) { 5629 routeDiff = oldLp.compareAllRoutes(newLp); 5630 } else if (newLp != null) { 5631 routeDiff.added = newLp.getAllRoutes(); 5632 } 5633 5634 // add routes before removing old in case it helps with continuous connectivity 5635 5636 // do this twice, adding non-nexthop routes first, then routes they are dependent on 5637 for (RouteInfo route : routeDiff.added) { 5638 if (route.hasGateway()) continue; 5639 try { 5640 mNetd.addRoute(netId, route); 5641 } catch (Exception e) { 5642 loge("Exception in addRoute for non-gateway: " + e); 5643 } 5644 } 5645 for (RouteInfo route : routeDiff.added) { 5646 if (route.hasGateway() == false) continue; 5647 try { 5648 mNetd.addRoute(netId, route); 5649 } catch (Exception e) { 5650 loge("Exception in addRoute for gateway: " + e); 5651 } 5652 } 5653 5654 for (RouteInfo route : routeDiff.removed) { 5655 try { 5656 mNetd.removeRoute(netId, route); 5657 } catch (Exception e) { 5658 loge("Exception in removeRoute: " + e); 5659 } 5660 } 5661 } 5662 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) { 5663 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) { 5664 Collection<InetAddress> dnses = newLp.getDnsServers(); 5665 if (dnses.size() == 0 && mDefaultDns != null) { 5666 dnses = new ArrayList(); 5667 dnses.add(mDefaultDns); 5668 if (DBG) { 5669 loge("no dns provided for netId " + netId + ", so using defaults"); 5670 } 5671 } 5672 try { 5673 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), 5674 newLp.getDomains()); 5675 } catch (Exception e) { 5676 loge("Exception in setDnsServersForNetwork: " + e); 5677 } 5678 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId); 5679 if (defaultNai != null && defaultNai.network.netId == netId) { 5680 setDefaultDnsSystemProperties(dnses); 5681 } 5682 } 5683 } 5684 5685 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) { 5686 int last = 0; 5687 for (InetAddress dns : dnses) { 5688 ++last; 5689 String key = "net.dns" + last; 5690 String value = dns.getHostAddress(); 5691 SystemProperties.set(key, value); 5692 } 5693 for (int i = last + 1; i <= mNumDnsEntries; ++i) { 5694 String key = "net.dns" + i; 5695 SystemProperties.set(key, ""); 5696 } 5697 mNumDnsEntries = last; 5698 } 5699 5700 5701 private void updateCapabilities(NetworkAgentInfo networkAgent, 5702 NetworkCapabilities networkCapabilities) { 5703 // TODO - what else here? Verify still satisfies everybody? 5704 // Check if satisfies somebody new? call callbacks? 5705 networkAgent.networkCapabilities = networkCapabilities; 5706 } 5707 5708 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) { 5709 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString()); 5710 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 5711 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0, 5712 networkRequest); 5713 } 5714 } 5715 5716 private void callCallbackForRequest(NetworkRequestInfo nri, 5717 NetworkAgentInfo networkAgent, int notificationType) { 5718 if (nri.messenger == null) return; // Default request has no msgr 5719 Object o; 5720 int a1 = 0; 5721 int a2 = 0; 5722 switch (notificationType) { 5723 case ConnectivityManager.CALLBACK_LOSING: 5724 a1 = 30 * 1000; // TODO - read this from NetworkMonitor 5725 // fall through 5726 case ConnectivityManager.CALLBACK_PRECHECK: 5727 case ConnectivityManager.CALLBACK_AVAILABLE: 5728 case ConnectivityManager.CALLBACK_LOST: 5729 case ConnectivityManager.CALLBACK_CAP_CHANGED: 5730 case ConnectivityManager.CALLBACK_IP_CHANGED: { 5731 o = new NetworkRequest(nri.request); 5732 a2 = networkAgent.network.netId; 5733 break; 5734 } 5735 case ConnectivityManager.CALLBACK_UNAVAIL: 5736 case ConnectivityManager.CALLBACK_RELEASED: { 5737 o = new NetworkRequest(nri.request); 5738 break; 5739 } 5740 default: { 5741 loge("Unknown notificationType " + notificationType); 5742 return; 5743 } 5744 } 5745 Message msg = Message.obtain(); 5746 msg.arg1 = a1; 5747 msg.arg2 = a2; 5748 msg.obj = o; 5749 msg.what = notificationType; 5750 try { 5751 if (VDBG) log("sending notification " + notificationType + " for " + nri.request); 5752 nri.messenger.send(msg); 5753 } catch (RemoteException e) { 5754 // may occur naturally in the race of binder death. 5755 loge("RemoteException caught trying to send a callback msg for " + nri.request); 5756 } 5757 } 5758 5759 private void handleLingerComplete(NetworkAgentInfo oldNetwork) { 5760 if (oldNetwork == null) { 5761 loge("Unknown NetworkAgentInfo in handleLingerComplete"); 5762 return; 5763 } 5764 if (DBG) log("handleLingerComplete for " + oldNetwork.name()); 5765 if (DBG) { 5766 if (oldNetwork.networkRequests.size() != 0) { 5767 loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests"); 5768 } 5769 } 5770 oldNetwork.asyncChannel.disconnect(); 5771 } 5772 5773 private void handleConnectionValidated(NetworkAgentInfo newNetwork) { 5774 if (newNetwork == null) { 5775 loge("Unknown NetworkAgentInfo in handleConnectionValidated"); 5776 return; 5777 } 5778 boolean keep = false; 5779 boolean isNewDefault = false; 5780 if (DBG) log("handleConnectionValidated for "+newNetwork.name()); 5781 // check if any NetworkRequest wants this NetworkAgent 5782 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>(); 5783 if (VDBG) log(" new Network has: " + newNetwork.networkCapabilities); 5784 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 5785 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId); 5786 if (newNetwork == currentNetwork) { 5787 if (VDBG) log("Network " + newNetwork.name() + " was already satisfying" + 5788 " request " + nri.request.requestId + ". No change."); 5789 keep = true; 5790 continue; 5791 } 5792 5793 // check if it satisfies the NetworkCapabilities 5794 if (VDBG) log(" checking if request is satisfied: " + nri.request); 5795 if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities( 5796 newNetwork.networkCapabilities)) { 5797 // next check if it's better than any current network we're using for 5798 // this request 5799 if (VDBG) { 5800 log("currentScore = " + 5801 (currentNetwork != null ? currentNetwork.currentScore : 0) + 5802 ", newScore = " + newNetwork.currentScore); 5803 } 5804 if (currentNetwork == null || 5805 currentNetwork.currentScore < newNetwork.currentScore) { 5806 if (currentNetwork != null) { 5807 if (VDBG) log(" accepting network in place of " + currentNetwork.name()); 5808 currentNetwork.networkRequests.remove(nri.request.requestId); 5809 currentNetwork.networkLingered.add(nri.request); 5810 affectedNetworks.add(currentNetwork); 5811 } else { 5812 if (VDBG) log(" accepting network in place of null"); 5813 } 5814 mNetworkForRequestId.put(nri.request.requestId, newNetwork); 5815 newNetwork.addRequest(nri.request); 5816 int legacyType = nri.request.legacyType; 5817 if (legacyType != TYPE_NONE) { 5818 mLegacyTypeTracker.add(legacyType, newNetwork); 5819 } 5820 keep = true; 5821 // TODO - this could get expensive if we have alot of requests for this 5822 // network. Think about if there is a way to reduce this. Push 5823 // netid->request mapping to each factory? 5824 sendUpdatedScoreToFactories(nri.request, newNetwork.currentScore); 5825 if (mDefaultRequest.requestId == nri.request.requestId) { 5826 isNewDefault = true; 5827 updateActiveDefaultNetwork(newNetwork); 5828 if (newNetwork.linkProperties != null) { 5829 setDefaultDnsSystemProperties( 5830 newNetwork.linkProperties.getDnsServers()); 5831 } else { 5832 setDefaultDnsSystemProperties(new ArrayList<InetAddress>()); 5833 } 5834 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork); 5835 } 5836 } 5837 } 5838 } 5839 for (NetworkAgentInfo nai : affectedNetworks) { 5840 boolean teardown = true; 5841 for (int i = 0; i < nai.networkRequests.size(); i++) { 5842 NetworkRequest nr = nai.networkRequests.valueAt(i); 5843 try { 5844 if (mNetworkRequests.get(nr).isRequest) { 5845 teardown = false; 5846 } 5847 } catch (Exception e) { 5848 loge("Request " + nr + " not found in mNetworkRequests."); 5849 loge(" it came from request list of " + nai.name()); 5850 } 5851 } 5852 if (teardown) { 5853 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER); 5854 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING); 5855 } else { 5856 // not going to linger, so kill the list of linger networks.. only 5857 // notify them of linger if it happens as the result of gaining another, 5858 // but if they transition and old network stays up, don't tell them of linger 5859 // or very delayed loss 5860 nai.networkLingered.clear(); 5861 if (VDBG) log("Lingered for " + nai.name() + " cleared"); 5862 } 5863 } 5864 if (keep) { 5865 if (isNewDefault) { 5866 if (VDBG) log("Switching to new default network: " + newNetwork); 5867 setupDataActivityTracking(newNetwork); 5868 try { 5869 mNetd.setDefaultNetId(newNetwork.network.netId); 5870 } catch (Exception e) { 5871 loge("Exception setting default network :" + e); 5872 } 5873 if (newNetwork.equals(mNetworkForRequestId.get(mDefaultRequest.requestId))) { 5874 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy()); 5875 } 5876 synchronized (ConnectivityService.this) { 5877 // have a new default network, release the transition wakelock in 5878 // a second if it's held. The second pause is to allow apps 5879 // to reconnect over the new network 5880 if (mNetTransitionWakeLock.isHeld()) { 5881 mHandler.sendMessageDelayed(mHandler.obtainMessage( 5882 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 5883 mNetTransitionWakeLockSerialNumber, 0), 5884 1000); 5885 } 5886 } 5887 5888 // this will cause us to come up initially as unconnected and switching 5889 // to connected after our normal pause unless somebody reports us as 5890 // really disconnected 5891 mDefaultInetConditionPublished = 0; 5892 mDefaultConnectionSequence++; 5893 mInetConditionChangeInFlight = false; 5894 // TODO - read the tcp buffer size config string from somewhere 5895 // updateNetworkSettings(); 5896 } 5897 // notify battery stats service about this network 5898 try { 5899 BatteryStatsService.getService().noteNetworkInterfaceType( 5900 newNetwork.linkProperties.getInterfaceName(), 5901 newNetwork.networkInfo.getType()); 5902 } catch (RemoteException e) { } 5903 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE); 5904 } else { 5905 if (DBG && newNetwork.networkRequests.size() != 0) { 5906 loge("tearing down network with live requests:"); 5907 for (int i=0; i < newNetwork.networkRequests.size(); i++) { 5908 loge(" " + newNetwork.networkRequests.valueAt(i)); 5909 } 5910 } 5911 if (VDBG) log("Validated network turns out to be unwanted. Tear it down."); 5912 newNetwork.asyncChannel.disconnect(); 5913 } 5914 } 5915 5916 5917 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) { 5918 NetworkInfo.State state = newInfo.getState(); 5919 NetworkInfo oldInfo = networkAgent.networkInfo; 5920 networkAgent.networkInfo = newInfo; 5921 5922 if (oldInfo != null && oldInfo.getState() == state) { 5923 if (VDBG) log("ignoring duplicate network state non-change"); 5924 return; 5925 } 5926 if (DBG) { 5927 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " + 5928 (oldInfo == null ? "null" : oldInfo.getState()) + 5929 " to " + state); 5930 } 5931 5932 if (state == NetworkInfo.State.CONNECTED) { 5933 try { 5934 // This is likely caused by the fact that this network already 5935 // exists. An example is when a network goes from CONNECTED to 5936 // CONNECTING and back (like wifi on DHCP renew). 5937 // TODO: keep track of which networks we've created, or ask netd 5938 // to tell us whether we've already created this network or not. 5939 mNetd.createNetwork(networkAgent.network.netId); 5940 } catch (Exception e) { 5941 loge("Error creating network " + networkAgent.network.netId + ": " 5942 + e.getMessage()); 5943 return; 5944 } 5945 5946 updateLinkProperties(networkAgent, null); 5947 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK); 5948 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 5949 } else if (state == NetworkInfo.State.DISCONNECTED || 5950 state == NetworkInfo.State.SUSPENDED) { 5951 networkAgent.asyncChannel.disconnect(); 5952 } 5953 } 5954 5955 private void updateNetworkScore(NetworkAgentInfo nai, int score) { 5956 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score); 5957 5958 nai.currentScore = score; 5959 5960 // TODO - This will not do the right thing if this network is lowering 5961 // its score and has requests that can be served by other 5962 // currently-active networks, or if the network is increasing its 5963 // score and other networks have requests that can be better served 5964 // by this network. 5965 // 5966 // Really we want to see if any of our requests migrate to other 5967 // active/lingered networks and if any other requests migrate to us (depending 5968 // on increasing/decreasing currentScore. That's a bit of work and probably our 5969 // score checking/network allocation code needs to be modularized so we can understand 5970 // (see handleConnectionValided for an example). 5971 // 5972 // As a first order approx, lets just advertise the new score to factories. If 5973 // somebody can beat it they will nominate a network and our normal net replacement 5974 // code will fire. 5975 for (int i = 0; i < nai.networkRequests.size(); i++) { 5976 NetworkRequest nr = nai.networkRequests.valueAt(i); 5977 sendUpdatedScoreToFactories(nr, score); 5978 } 5979 } 5980 5981 // notify only this one new request of the current state 5982 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) { 5983 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE; 5984 // TODO - read state from monitor to decide what to send. 5985// if (nai.networkMonitor.isLingering()) { 5986// notifyType = NetworkCallbacks.LOSING; 5987// } else if (nai.networkMonitor.isEvaluating()) { 5988// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType); 5989// } 5990 callCallbackForRequest(nri, nai, notifyType); 5991 } 5992 5993 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) { 5994 if (connected) { 5995 NetworkInfo info = new NetworkInfo(nai.networkInfo); 5996 info.setType(type); 5997 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay()); 5998 } else { 5999 NetworkInfo info = new NetworkInfo(nai.networkInfo); 6000 info.setType(type); 6001 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 6002 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 6003 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 6004 if (info.isFailover()) { 6005 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 6006 nai.networkInfo.setFailover(false); 6007 } 6008 if (info.getReason() != null) { 6009 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 6010 } 6011 if (info.getExtraInfo() != null) { 6012 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo()); 6013 } 6014 NetworkAgentInfo newDefaultAgent = null; 6015 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 6016 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId); 6017 if (newDefaultAgent != null) { 6018 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, 6019 newDefaultAgent.networkInfo); 6020 } else { 6021 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 6022 } 6023 } 6024 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, 6025 mDefaultInetConditionPublished); 6026 final Intent immediateIntent = new Intent(intent); 6027 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE); 6028 sendStickyBroadcast(immediateIntent); 6029 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay()); 6030 if (newDefaultAgent != null) { 6031 sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo, 6032 getConnectivityChangeDelay()); 6033 } 6034 } 6035 } 6036 6037 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) { 6038 if (VDBG) log("notifyType " + notifyType + " for " + networkAgent.name()); 6039 for (int i = 0; i < networkAgent.networkRequests.size(); i++) { 6040 NetworkRequest nr = networkAgent.networkRequests.valueAt(i); 6041 NetworkRequestInfo nri = mNetworkRequests.get(nr); 6042 if (VDBG) log(" sending notification for " + nr); 6043 callCallbackForRequest(nri, networkAgent, notifyType); 6044 } 6045 } 6046 6047 private LinkProperties getLinkPropertiesForTypeInternal(int networkType) { 6048 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 6049 return (nai != null) ? 6050 new LinkProperties(nai.linkProperties) : 6051 new LinkProperties(); 6052 } 6053 6054 private NetworkInfo getNetworkInfoForType(int networkType) { 6055 if (!mLegacyTypeTracker.isTypeSupported(networkType)) 6056 return null; 6057 6058 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 6059 if (nai != null) { 6060 NetworkInfo result = new NetworkInfo(nai.networkInfo); 6061 result.setType(networkType); 6062 return result; 6063 } else { 6064 return new NetworkInfo(networkType, 0, "Unknown", ""); 6065 } 6066 } 6067 6068 private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) { 6069 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 6070 return (nai != null) ? 6071 new NetworkCapabilities(nai.networkCapabilities) : 6072 new NetworkCapabilities(); 6073 } 6074} 6075