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