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