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