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