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