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