ConnectivityService.java revision 12e6735f77a6f8cbf71edde4f156f40668d2d25b
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 // TODO: add locking to get atomic snapshot 2838 pw.println(); 2839 for (int i = 0; i < mNetTrackers.length; i++) { 2840 final NetworkStateTracker nst = mNetTrackers[i]; 2841 if (nst != null) { 2842 pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":"); 2843 pw.increaseIndent(); 2844 if (nst.getNetworkInfo().isConnected()) { 2845 pw.println("Active network: " + nst.getNetworkInfo(). 2846 getTypeName()); 2847 } 2848 pw.println(nst.getNetworkInfo()); 2849 pw.println(nst.getLinkProperties()); 2850 pw.println(nst); 2851 pw.println(); 2852 pw.decreaseIndent(); 2853 } 2854 } 2855 2856 pw.print("Active default network: "); pw.println(getNetworkTypeName(mActiveDefaultNetwork)); 2857 pw.println(); 2858 2859 pw.println("Network Requester Pids:"); 2860 pw.increaseIndent(); 2861 for (int net : mPriorityList) { 2862 String pidString = net + ": "; 2863 for (Integer pid : mNetRequestersPids[net]) { 2864 pidString = pidString + pid.toString() + ", "; 2865 } 2866 pw.println(pidString); 2867 } 2868 pw.println(); 2869 pw.decreaseIndent(); 2870 2871 pw.println("FeatureUsers:"); 2872 pw.increaseIndent(); 2873 for (Object requester : mFeatureUsers) { 2874 pw.println(requester.toString()); 2875 } 2876 pw.println(); 2877 pw.decreaseIndent(); 2878 2879 synchronized (this) { 2880 pw.println("NetworkTranstionWakeLock is currently " + 2881 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held."); 2882 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy); 2883 } 2884 pw.println(); 2885 2886 mTethering.dump(fd, pw, args); 2887 2888 if (mInetLog != null) { 2889 pw.println(); 2890 pw.println("Inet condition reports:"); 2891 pw.increaseIndent(); 2892 for(int i = 0; i < mInetLog.size(); i++) { 2893 pw.println(mInetLog.get(i)); 2894 } 2895 pw.decreaseIndent(); 2896 } 2897 } 2898 2899 // must be stateless - things change under us. 2900 private class NetworkStateTrackerHandler extends Handler { 2901 public NetworkStateTrackerHandler(Looper looper) { 2902 super(looper); 2903 } 2904 2905 @Override 2906 public void handleMessage(Message msg) { 2907 NetworkInfo info; 2908 switch (msg.what) { 2909 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: { 2910 handleAsyncChannelHalfConnect(msg); 2911 break; 2912 } 2913 case AsyncChannel.CMD_CHANNEL_DISCONNECT: { 2914 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 2915 if (nai != null) nai.asyncChannel.disconnect(); 2916 break; 2917 } 2918 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: { 2919 handleAsyncChannelDisconnected(msg); 2920 break; 2921 } 2922 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: { 2923 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 2924 if (nai == null) { 2925 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent"); 2926 } else { 2927 updateCapabilities(nai, (NetworkCapabilities)msg.obj); 2928 } 2929 break; 2930 } 2931 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: { 2932 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 2933 if (nai == null) { 2934 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED"); 2935 } else { 2936 LinkProperties oldLp = nai.linkProperties; 2937 nai.linkProperties = (LinkProperties)msg.obj; 2938 updateLinkProperties(nai, oldLp); 2939 } 2940 break; 2941 } 2942 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: { 2943 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 2944 if (nai == null) { 2945 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent"); 2946 break; 2947 } 2948 info = (NetworkInfo) msg.obj; 2949 updateNetworkInfo(nai, info); 2950 break; 2951 } 2952 case NetworkMonitor.EVENT_NETWORK_VALIDATED: { 2953 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj; 2954 handleConnectionValidated(nai); 2955 break; 2956 } 2957 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: { 2958 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj; 2959 handleLingerComplete(nai); 2960 break; 2961 } 2962 case NetworkStateTracker.EVENT_STATE_CHANGED: { 2963 info = (NetworkInfo) msg.obj; 2964 NetworkInfo.State state = info.getState(); 2965 2966 if (VDBG || (state == NetworkInfo.State.CONNECTED) || 2967 (state == NetworkInfo.State.DISCONNECTED) || 2968 (state == NetworkInfo.State.SUSPENDED)) { 2969 log("ConnectivityChange for " + 2970 info.getTypeName() + ": " + 2971 state + "/" + info.getDetailedState()); 2972 } 2973 2974 // Since mobile has the notion of a network/apn that can be used for 2975 // provisioning we need to check every time we're connected as 2976 // CaptiveProtalTracker won't detected it because DCT doesn't report it 2977 // as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its 2978 // reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which 2979 // is received by MDST and sent here as EVENT_STATE_CHANGED. 2980 if (ConnectivityManager.isNetworkTypeMobile(info.getType()) 2981 && (0 != Settings.Global.getInt(mContext.getContentResolver(), 2982 Settings.Global.DEVICE_PROVISIONED, 0)) 2983 && (((state == NetworkInfo.State.CONNECTED) 2984 && (info.getType() == ConnectivityManager.TYPE_MOBILE)) 2985 || info.isConnectedToProvisioningNetwork())) { 2986 log("ConnectivityChange checkMobileProvisioning for" 2987 + " TYPE_MOBILE or ProvisioningNetwork"); 2988 checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS); 2989 } 2990 2991 EventLogTags.writeConnectivityStateChanged( 2992 info.getType(), info.getSubtype(), info.getDetailedState().ordinal()); 2993 2994 if (info.isConnectedToProvisioningNetwork()) { 2995 /** 2996 * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING 2997 * for now its an in between network, its a network that 2998 * is actually a default network but we don't want it to be 2999 * announced as such to keep background applications from 3000 * trying to use it. It turns out that some still try so we 3001 * take the additional step of clearing any default routes 3002 * to the link that may have incorrectly setup by the lower 3003 * levels. 3004 */ 3005 LinkProperties lp = getLinkProperties(info.getType()); 3006 if (DBG) { 3007 log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp); 3008 } 3009 3010 // Clear any default routes setup by the radio so 3011 // any activity by applications trying to use this 3012 // connection will fail until the provisioning network 3013 // is enabled. 3014 for (RouteInfo r : lp.getRoutes()) { 3015 removeRoute(lp, r, TO_DEFAULT_TABLE, 3016 mNetTrackers[info.getType()].getNetwork().netId); 3017 } 3018 } else if (state == NetworkInfo.State.DISCONNECTED) { 3019 } else if (state == NetworkInfo.State.SUSPENDED) { 3020 } else if (state == NetworkInfo.State.CONNECTED) { 3021 // handleConnect(info); 3022 } 3023 if (mLockdownTracker != null) { 3024 mLockdownTracker.onNetworkInfoChanged(info); 3025 } 3026 break; 3027 } 3028 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: { 3029 info = (NetworkInfo) msg.obj; 3030 // TODO: Temporary allowing network configuration 3031 // change not resetting sockets. 3032 // @see bug/4455071 3033 handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()], 3034 false); 3035 break; 3036 } 3037 case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: { 3038 info = (NetworkInfo) msg.obj; 3039 int type = info.getType(); 3040 if (mNetConfigs[type].isDefault()) updateNetworkSettings(mNetTrackers[type]); 3041 break; 3042 } 3043 } 3044 } 3045 } 3046 3047 private void handleAsyncChannelHalfConnect(Message msg) { 3048 AsyncChannel ac = (AsyncChannel) msg.obj; 3049 if (mNetworkFactories.contains(ac)) { 3050 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 3051 if (VDBG) log("NetworkFactory connected"); 3052 // A network factory has connected. Send it all current NetworkRequests. 3053 for (int i = 0; i < mNetworkRequests.size(); i++) { 3054 NetworkRequest request = mNetworkRequests.valueAt(i); 3055 NetworkAgentInfo nai = mNetworkForRequestId.get(request.requestId); 3056 ac.sendMessage(NetworkFactoryProtocol.CMD_REQUEST_NETWORK, 3057 (nai != null ? nai.currentScore : 0), 0, request); 3058 } 3059 } else { 3060 loge("Error connecting NetworkFactory"); 3061 mNetworkFactories.remove(ac); 3062 } 3063 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) { 3064 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 3065 if (VDBG) log("NetworkAgent connected"); 3066 // A network agent has requested a connection. Establish the connection. 3067 mNetworkAgentInfos.get(msg.replyTo).asyncChannel. 3068 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION); 3069 } else { 3070 loge("Error connecting NetworkAgent"); 3071 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo); 3072 try { 3073 mNetworkAgentInfoForType[nai.networkInfo.getType()].remove(nai); 3074 } catch (NullPointerException e) {} 3075 } 3076 } 3077 } 3078 private void handleAsyncChannelDisconnected(Message msg) { 3079 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 3080 if (nai != null) { 3081 if (DBG) log(nai.name() + " got DISCONNECTED"); 3082 // A network agent has disconnected. 3083 // Tell netd to clean up the configuration for this network 3084 // (routing rules, DNS, etc). 3085 try { 3086 mNetd.removeNetwork(nai.network.netId); 3087 } catch (Exception e) { 3088 loge("Exception removing network: " + e); 3089 } 3090 notifyNetworkCallbacks(nai, NetworkCallbacks.LOST); 3091 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED); 3092 mNetworkAgentInfos.remove(msg.replyTo); 3093 updateClat(null, nai.linkProperties, nai); 3094 try { 3095 mNetworkAgentInfoForType[nai.networkInfo.getType()].remove(nai); 3096 } catch (NullPointerException e) {} 3097 3098 // Since we've lost the network, go through all the requests that 3099 // it was satisfying and see if any other factory can satisfy them. 3100 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>(); 3101 for (int i = 0; i < nai.networkRequests.size(); i++) { 3102 NetworkRequest request = nai.networkRequests.valueAt(i); 3103 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId); 3104 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) { 3105 mNetworkForRequestId.remove(request.requestId); 3106 sendUpdatedScoreToFactories(request, 0); 3107 NetworkAgentInfo alternative = null; 3108 for (Map.Entry entry : mNetworkAgentInfos.entrySet()) { 3109 NetworkAgentInfo existing = (NetworkAgentInfo)entry.getValue(); 3110 if (existing.networkInfo.isConnected() && 3111 request.networkCapabilities.satisfiedByNetworkCapabilities( 3112 existing.networkCapabilities) && 3113 (alternative == null || 3114 alternative.currentScore < existing.currentScore)) { 3115 alternative = existing; 3116 } 3117 } 3118 if (alternative != null && !toActivate.contains(alternative)) { 3119 toActivate.add(alternative); 3120 } 3121 } 3122 } 3123 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 3124 removeDataActivityTracking(nai); 3125 mActiveDefaultNetwork = ConnectivityManager.TYPE_NONE; 3126 } 3127 for (NetworkAgentInfo networkToActivate : toActivate) { 3128 networkToActivate.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 3129 } 3130 } 3131 } 3132 3133 3134 private class InternalHandler extends Handler { 3135 public InternalHandler(Looper looper) { 3136 super(looper); 3137 } 3138 3139 @Override 3140 public void handleMessage(Message msg) { 3141 NetworkInfo info; 3142 switch (msg.what) { 3143 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: { 3144 String causedBy = null; 3145 synchronized (ConnectivityService.this) { 3146 if (msg.arg1 == mNetTransitionWakeLockSerialNumber && 3147 mNetTransitionWakeLock.isHeld()) { 3148 mNetTransitionWakeLock.release(); 3149 causedBy = mNetTransitionWakeLockCausedBy; 3150 } 3151 } 3152 if (causedBy != null) { 3153 log("NetTransition Wakelock for " + causedBy + " released by timeout"); 3154 } 3155 break; 3156 } 3157 case EVENT_RESTORE_DEFAULT_NETWORK: { 3158 FeatureUser u = (FeatureUser)msg.obj; 3159 u.expire(); 3160 break; 3161 } 3162 case EVENT_INET_CONDITION_CHANGE: { 3163 int netType = msg.arg1; 3164 int condition = msg.arg2; 3165 handleInetConditionChange(netType, condition); 3166 break; 3167 } 3168 case EVENT_INET_CONDITION_HOLD_END: { 3169 int netType = msg.arg1; 3170 int sequence = msg.arg2; 3171 handleInetConditionHoldEnd(netType, sequence); 3172 break; 3173 } 3174 case EVENT_SET_MOBILE_DATA: { 3175 boolean enabled = (msg.arg1 == ENABLED); 3176 handleSetMobileData(enabled); 3177 break; 3178 } 3179 case EVENT_APPLY_GLOBAL_HTTP_PROXY: { 3180 handleDeprecatedGlobalHttpProxy(); 3181 break; 3182 } 3183 case EVENT_SET_DEPENDENCY_MET: { 3184 boolean met = (msg.arg1 == ENABLED); 3185 handleSetDependencyMet(msg.arg2, met); 3186 break; 3187 } 3188 case EVENT_SEND_STICKY_BROADCAST_INTENT: { 3189 Intent intent = (Intent)msg.obj; 3190 sendStickyBroadcast(intent); 3191 break; 3192 } 3193 case EVENT_SET_POLICY_DATA_ENABLE: { 3194 final int networkType = msg.arg1; 3195 final boolean enabled = msg.arg2 == ENABLED; 3196 handleSetPolicyDataEnable(networkType, enabled); 3197 break; 3198 } 3199 case EVENT_VPN_STATE_CHANGED: { 3200 if (mLockdownTracker != null) { 3201 mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj); 3202 } 3203 break; 3204 } 3205 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: { 3206 int tag = mEnableFailFastMobileDataTag.get(); 3207 if (msg.arg1 == tag) { 3208 MobileDataStateTracker mobileDst = 3209 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 3210 if (mobileDst != null) { 3211 mobileDst.setEnableFailFastMobileData(msg.arg2); 3212 } 3213 } else { 3214 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1 3215 + " != tag:" + tag); 3216 } 3217 break; 3218 } 3219 case EVENT_SAMPLE_INTERVAL_ELAPSED: { 3220 handleNetworkSamplingTimeout(); 3221 break; 3222 } 3223 case EVENT_PROXY_HAS_CHANGED: { 3224 handleApplyDefaultProxy((ProxyInfo)msg.obj); 3225 break; 3226 } 3227 case EVENT_REGISTER_NETWORK_FACTORY: { 3228 handleRegisterNetworkFactory((Messenger)msg.obj); 3229 break; 3230 } 3231 case EVENT_REGISTER_NETWORK_AGENT: { 3232 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj); 3233 break; 3234 } 3235 } 3236 } 3237 } 3238 3239 // javadoc from interface 3240 public int tether(String iface) { 3241 enforceTetherChangePermission(); 3242 3243 if (isTetheringSupported()) { 3244 return mTethering.tether(iface); 3245 } else { 3246 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3247 } 3248 } 3249 3250 // javadoc from interface 3251 public int untether(String iface) { 3252 enforceTetherChangePermission(); 3253 3254 if (isTetheringSupported()) { 3255 return mTethering.untether(iface); 3256 } else { 3257 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3258 } 3259 } 3260 3261 // javadoc from interface 3262 public int getLastTetherError(String iface) { 3263 enforceTetherAccessPermission(); 3264 3265 if (isTetheringSupported()) { 3266 return mTethering.getLastTetherError(iface); 3267 } else { 3268 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3269 } 3270 } 3271 3272 // TODO - proper iface API for selection by property, inspection, etc 3273 public String[] getTetherableUsbRegexs() { 3274 enforceTetherAccessPermission(); 3275 if (isTetheringSupported()) { 3276 return mTethering.getTetherableUsbRegexs(); 3277 } else { 3278 return new String[0]; 3279 } 3280 } 3281 3282 public String[] getTetherableWifiRegexs() { 3283 enforceTetherAccessPermission(); 3284 if (isTetheringSupported()) { 3285 return mTethering.getTetherableWifiRegexs(); 3286 } else { 3287 return new String[0]; 3288 } 3289 } 3290 3291 public String[] getTetherableBluetoothRegexs() { 3292 enforceTetherAccessPermission(); 3293 if (isTetheringSupported()) { 3294 return mTethering.getTetherableBluetoothRegexs(); 3295 } else { 3296 return new String[0]; 3297 } 3298 } 3299 3300 public int setUsbTethering(boolean enable) { 3301 enforceTetherChangePermission(); 3302 if (isTetheringSupported()) { 3303 return mTethering.setUsbTethering(enable); 3304 } else { 3305 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 3306 } 3307 } 3308 3309 // TODO - move iface listing, queries, etc to new module 3310 // javadoc from interface 3311 public String[] getTetherableIfaces() { 3312 enforceTetherAccessPermission(); 3313 return mTethering.getTetherableIfaces(); 3314 } 3315 3316 public String[] getTetheredIfaces() { 3317 enforceTetherAccessPermission(); 3318 return mTethering.getTetheredIfaces(); 3319 } 3320 3321 public String[] getTetheringErroredIfaces() { 3322 enforceTetherAccessPermission(); 3323 return mTethering.getErroredIfaces(); 3324 } 3325 3326 // if ro.tether.denied = true we default to no tethering 3327 // gservices could set the secure setting to 1 though to enable it on a build where it 3328 // had previously been turned off. 3329 public boolean isTetheringSupported() { 3330 enforceTetherAccessPermission(); 3331 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 3332 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(), 3333 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0); 3334 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 || 3335 mTethering.getTetherableWifiRegexs().length != 0 || 3336 mTethering.getTetherableBluetoothRegexs().length != 0) && 3337 mTethering.getUpstreamIfaceTypes().length != 0); 3338 } 3339 3340 // An API NetworkStateTrackers can call when they lose their network. 3341 // This will automatically be cleared after X seconds or a network becomes CONNECTED, 3342 // whichever happens first. The timer is started by the first caller and not 3343 // restarted by subsequent callers. 3344 public void requestNetworkTransitionWakelock(String forWhom) { 3345 enforceConnectivityInternalPermission(); 3346 synchronized (this) { 3347 if (mNetTransitionWakeLock.isHeld()) return; 3348 mNetTransitionWakeLockSerialNumber++; 3349 mNetTransitionWakeLock.acquire(); 3350 mNetTransitionWakeLockCausedBy = forWhom; 3351 } 3352 mHandler.sendMessageDelayed(mHandler.obtainMessage( 3353 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 3354 mNetTransitionWakeLockSerialNumber, 0), 3355 mNetTransitionWakeLockTimeout); 3356 return; 3357 } 3358 3359 // 100 percent is full good, 0 is full bad. 3360 public void reportInetCondition(int networkType, int percentage) { 3361 if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")"); 3362 mContext.enforceCallingOrSelfPermission( 3363 android.Manifest.permission.STATUS_BAR, 3364 "ConnectivityService"); 3365 3366 if (DBG) { 3367 int pid = getCallingPid(); 3368 int uid = getCallingUid(); 3369 String s = pid + "(" + uid + ") reports inet is " + 3370 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " + 3371 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime(); 3372 mInetLog.add(s); 3373 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) { 3374 mInetLog.remove(0); 3375 } 3376 } 3377 mHandler.sendMessage(mHandler.obtainMessage( 3378 EVENT_INET_CONDITION_CHANGE, networkType, percentage)); 3379 } 3380 3381 private void handleInetConditionChange(int netType, int condition) { 3382 if (mActiveDefaultNetwork == -1) { 3383 if (DBG) log("handleInetConditionChange: no active default network - ignore"); 3384 return; 3385 } 3386 if (mActiveDefaultNetwork != netType) { 3387 if (DBG) log("handleInetConditionChange: net=" + netType + 3388 " != default=" + mActiveDefaultNetwork + " - ignore"); 3389 return; 3390 } 3391 if (VDBG) { 3392 log("handleInetConditionChange: net=" + 3393 netType + ", condition=" + condition + 3394 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork); 3395 } 3396 mDefaultInetCondition = condition; 3397 int delay; 3398 if (mInetConditionChangeInFlight == false) { 3399 if (VDBG) log("handleInetConditionChange: starting a change hold"); 3400 // setup a new hold to debounce this 3401 if (mDefaultInetCondition > 50) { 3402 delay = Settings.Global.getInt(mContext.getContentResolver(), 3403 Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500); 3404 } else { 3405 delay = Settings.Global.getInt(mContext.getContentResolver(), 3406 Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000); 3407 } 3408 mInetConditionChangeInFlight = true; 3409 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END, 3410 mActiveDefaultNetwork, mDefaultConnectionSequence), delay); 3411 } else { 3412 // we've set the new condition, when this hold ends that will get picked up 3413 if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt"); 3414 } 3415 } 3416 3417 private void handleInetConditionHoldEnd(int netType, int sequence) { 3418 if (DBG) { 3419 log("handleInetConditionHoldEnd: net=" + netType + 3420 ", condition=" + mDefaultInetCondition + 3421 ", published condition=" + mDefaultInetConditionPublished); 3422 } 3423 mInetConditionChangeInFlight = false; 3424 3425 if (mActiveDefaultNetwork == -1) { 3426 if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring"); 3427 return; 3428 } 3429 if (mDefaultConnectionSequence != sequence) { 3430 if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring"); 3431 return; 3432 } 3433 // TODO: Figure out why this optimization sometimes causes a 3434 // change in mDefaultInetCondition to be missed and the 3435 // UI to not be updated. 3436 //if (mDefaultInetConditionPublished == mDefaultInetCondition) { 3437 // if (DBG) log("no change in condition - aborting"); 3438 // return; 3439 //} 3440 NetworkInfo networkInfo = getNetworkInfoForType(mActiveDefaultNetwork); 3441 if (networkInfo.isConnected() == false) { 3442 if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring"); 3443 return; 3444 } 3445 mDefaultInetConditionPublished = mDefaultInetCondition; 3446 sendInetConditionBroadcast(networkInfo); 3447 return; 3448 } 3449 3450 public ProxyInfo getProxy() { 3451 // this information is already available as a world read/writable jvm property 3452 // so this API change wouldn't have a benifit. It also breaks the passing 3453 // of proxy info to all the JVMs. 3454 // enforceAccessPermission(); 3455 synchronized (mProxyLock) { 3456 ProxyInfo ret = mGlobalProxy; 3457 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy; 3458 return ret; 3459 } 3460 } 3461 3462 public void setGlobalProxy(ProxyInfo proxyProperties) { 3463 enforceConnectivityInternalPermission(); 3464 3465 synchronized (mProxyLock) { 3466 if (proxyProperties == mGlobalProxy) return; 3467 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return; 3468 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return; 3469 3470 String host = ""; 3471 int port = 0; 3472 String exclList = ""; 3473 String pacFileUrl = ""; 3474 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) || 3475 (proxyProperties.getPacFileUrl() != null))) { 3476 if (!proxyProperties.isValid()) { 3477 if (DBG) 3478 log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3479 return; 3480 } 3481 mGlobalProxy = new ProxyInfo(proxyProperties); 3482 host = mGlobalProxy.getHost(); 3483 port = mGlobalProxy.getPort(); 3484 exclList = mGlobalProxy.getExclusionListAsString(); 3485 if (proxyProperties.getPacFileUrl() != null) { 3486 pacFileUrl = proxyProperties.getPacFileUrl().toString(); 3487 } 3488 } else { 3489 mGlobalProxy = null; 3490 } 3491 ContentResolver res = mContext.getContentResolver(); 3492 final long token = Binder.clearCallingIdentity(); 3493 try { 3494 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host); 3495 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port); 3496 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 3497 exclList); 3498 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl); 3499 } finally { 3500 Binder.restoreCallingIdentity(token); 3501 } 3502 } 3503 3504 if (mGlobalProxy == null) { 3505 proxyProperties = mDefaultProxy; 3506 } 3507 sendProxyBroadcast(proxyProperties); 3508 } 3509 3510 private void loadGlobalProxy() { 3511 ContentResolver res = mContext.getContentResolver(); 3512 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST); 3513 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0); 3514 String exclList = Settings.Global.getString(res, 3515 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST); 3516 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC); 3517 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) { 3518 ProxyInfo proxyProperties; 3519 if (!TextUtils.isEmpty(pacFileUrl)) { 3520 proxyProperties = new ProxyInfo(pacFileUrl); 3521 } else { 3522 proxyProperties = new ProxyInfo(host, port, exclList); 3523 } 3524 if (!proxyProperties.isValid()) { 3525 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 3526 return; 3527 } 3528 3529 synchronized (mProxyLock) { 3530 mGlobalProxy = proxyProperties; 3531 } 3532 } 3533 } 3534 3535 public ProxyInfo getGlobalProxy() { 3536 // this information is already available as a world read/writable jvm property 3537 // so this API change wouldn't have a benifit. It also breaks the passing 3538 // of proxy info to all the JVMs. 3539 // enforceAccessPermission(); 3540 synchronized (mProxyLock) { 3541 return mGlobalProxy; 3542 } 3543 } 3544 3545 private void handleApplyDefaultProxy(ProxyInfo proxy) { 3546 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 3547 && (proxy.getPacFileUrl() == null)) { 3548 proxy = null; 3549 } 3550 synchronized (mProxyLock) { 3551 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return; 3552 if (mDefaultProxy == proxy) return; // catches repeated nulls 3553 if (proxy != null && !proxy.isValid()) { 3554 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString()); 3555 return; 3556 } 3557 3558 // This call could be coming from the PacManager, containing the port of the local 3559 // proxy. If this new proxy matches the global proxy then copy this proxy to the 3560 // global (to get the correct local port), and send a broadcast. 3561 // TODO: Switch PacManager to have its own message to send back rather than 3562 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy. 3563 if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null) 3564 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) { 3565 mGlobalProxy = proxy; 3566 sendProxyBroadcast(mGlobalProxy); 3567 return; 3568 } 3569 mDefaultProxy = proxy; 3570 3571 if (mGlobalProxy != null) return; 3572 if (!mDefaultProxyDisabled) { 3573 sendProxyBroadcast(proxy); 3574 } 3575 } 3576 } 3577 3578 private void handleDeprecatedGlobalHttpProxy() { 3579 String proxy = Settings.Global.getString(mContext.getContentResolver(), 3580 Settings.Global.HTTP_PROXY); 3581 if (!TextUtils.isEmpty(proxy)) { 3582 String data[] = proxy.split(":"); 3583 if (data.length == 0) { 3584 return; 3585 } 3586 3587 String proxyHost = data[0]; 3588 int proxyPort = 8080; 3589 if (data.length > 1) { 3590 try { 3591 proxyPort = Integer.parseInt(data[1]); 3592 } catch (NumberFormatException e) { 3593 return; 3594 } 3595 } 3596 ProxyInfo p = new ProxyInfo(data[0], proxyPort, ""); 3597 setGlobalProxy(p); 3598 } 3599 } 3600 3601 private void sendProxyBroadcast(ProxyInfo proxy) { 3602 if (proxy == null) proxy = new ProxyInfo("", 0, ""); 3603 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return; 3604 if (DBG) log("sending Proxy Broadcast for " + proxy); 3605 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); 3606 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 3607 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3608 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy); 3609 final long ident = Binder.clearCallingIdentity(); 3610 try { 3611 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 3612 } finally { 3613 Binder.restoreCallingIdentity(ident); 3614 } 3615 } 3616 3617 private static class SettingsObserver extends ContentObserver { 3618 private int mWhat; 3619 private Handler mHandler; 3620 SettingsObserver(Handler handler, int what) { 3621 super(handler); 3622 mHandler = handler; 3623 mWhat = what; 3624 } 3625 3626 void observe(Context context) { 3627 ContentResolver resolver = context.getContentResolver(); 3628 resolver.registerContentObserver(Settings.Global.getUriFor( 3629 Settings.Global.HTTP_PROXY), false, this); 3630 } 3631 3632 @Override 3633 public void onChange(boolean selfChange) { 3634 mHandler.obtainMessage(mWhat).sendToTarget(); 3635 } 3636 } 3637 3638 private static void log(String s) { 3639 Slog.d(TAG, s); 3640 } 3641 3642 private static void loge(String s) { 3643 Slog.e(TAG, s); 3644 } 3645 3646 int convertFeatureToNetworkType(int networkType, String feature) { 3647 int usedNetworkType = networkType; 3648 3649 if(networkType == ConnectivityManager.TYPE_MOBILE) { 3650 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) { 3651 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS; 3652 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) { 3653 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL; 3654 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) || 3655 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) { 3656 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN; 3657 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) { 3658 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI; 3659 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) { 3660 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA; 3661 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) { 3662 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS; 3663 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) { 3664 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS; 3665 } else { 3666 Slog.e(TAG, "Can't match any mobile netTracker!"); 3667 } 3668 } else if (networkType == ConnectivityManager.TYPE_WIFI) { 3669 if (TextUtils.equals(feature, "p2p")) { 3670 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P; 3671 } else { 3672 Slog.e(TAG, "Can't match any wifi netTracker!"); 3673 } 3674 } else { 3675 Slog.e(TAG, "Unexpected network type"); 3676 } 3677 return usedNetworkType; 3678 } 3679 3680 private static <T> T checkNotNull(T value, String message) { 3681 if (value == null) { 3682 throw new NullPointerException(message); 3683 } 3684 return value; 3685 } 3686 3687 /** 3688 * Protect a socket from VPN routing rules. This method is used by 3689 * VpnBuilder and not available in ConnectivityManager. Permissions 3690 * are checked in Vpn class. 3691 * @hide 3692 */ 3693 @Override 3694 public boolean protectVpn(ParcelFileDescriptor socket) { 3695 throwIfLockdownEnabled(); 3696 try { 3697 int type = mActiveDefaultNetwork; 3698 int user = UserHandle.getUserId(Binder.getCallingUid()); 3699 if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) { 3700 synchronized(mVpns) { 3701 mVpns.get(user).protect(socket); 3702 } 3703 return true; 3704 } 3705 } catch (Exception e) { 3706 // ignore 3707 } finally { 3708 try { 3709 socket.close(); 3710 } catch (Exception e) { 3711 // ignore 3712 } 3713 } 3714 return false; 3715 } 3716 3717 /** 3718 * Prepare for a VPN application. This method is used by VpnDialogs 3719 * and not available in ConnectivityManager. Permissions are checked 3720 * in Vpn class. 3721 * @hide 3722 */ 3723 @Override 3724 public boolean prepareVpn(String oldPackage, String newPackage) { 3725 throwIfLockdownEnabled(); 3726 int user = UserHandle.getUserId(Binder.getCallingUid()); 3727 synchronized(mVpns) { 3728 return mVpns.get(user).prepare(oldPackage, newPackage); 3729 } 3730 } 3731 3732 @Override 3733 public void markSocketAsUser(ParcelFileDescriptor socket, int uid) { 3734 enforceMarkNetworkSocketPermission(); 3735 final long token = Binder.clearCallingIdentity(); 3736 try { 3737 int mark = mNetd.getMarkForUid(uid); 3738 // Clear the mark on the socket if no mark is needed to prevent socket reuse issues 3739 if (mark == -1) { 3740 mark = 0; 3741 } 3742 NetworkUtils.markSocket(socket.getFd(), mark); 3743 } catch (RemoteException e) { 3744 } finally { 3745 Binder.restoreCallingIdentity(token); 3746 } 3747 } 3748 3749 /** 3750 * Configure a TUN interface and return its file descriptor. Parameters 3751 * are encoded and opaque to this class. This method is used by VpnBuilder 3752 * and not available in ConnectivityManager. Permissions are checked in 3753 * Vpn class. 3754 * @hide 3755 */ 3756 @Override 3757 public ParcelFileDescriptor establishVpn(VpnConfig config) { 3758 throwIfLockdownEnabled(); 3759 int user = UserHandle.getUserId(Binder.getCallingUid()); 3760 synchronized(mVpns) { 3761 return mVpns.get(user).establish(config); 3762 } 3763 } 3764 3765 /** 3766 * Start legacy VPN, controlling native daemons as needed. Creates a 3767 * secondary thread to perform connection work, returning quickly. 3768 */ 3769 @Override 3770 public void startLegacyVpn(VpnProfile profile) { 3771 throwIfLockdownEnabled(); 3772 final LinkProperties egress = getActiveLinkProperties(); 3773 if (egress == null) { 3774 throw new IllegalStateException("Missing active network connection"); 3775 } 3776 int user = UserHandle.getUserId(Binder.getCallingUid()); 3777 synchronized(mVpns) { 3778 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress); 3779 } 3780 } 3781 3782 /** 3783 * Return the information of the ongoing legacy VPN. This method is used 3784 * by VpnSettings and not available in ConnectivityManager. Permissions 3785 * are checked in Vpn class. 3786 * @hide 3787 */ 3788 @Override 3789 public LegacyVpnInfo getLegacyVpnInfo() { 3790 throwIfLockdownEnabled(); 3791 int user = UserHandle.getUserId(Binder.getCallingUid()); 3792 synchronized(mVpns) { 3793 return mVpns.get(user).getLegacyVpnInfo(); 3794 } 3795 } 3796 3797 /** 3798 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and 3799 * not available in ConnectivityManager. 3800 * Permissions are checked in Vpn class. 3801 * @hide 3802 */ 3803 @Override 3804 public VpnConfig getVpnConfig() { 3805 int user = UserHandle.getUserId(Binder.getCallingUid()); 3806 synchronized(mVpns) { 3807 return mVpns.get(user).getVpnConfig(); 3808 } 3809 } 3810 3811 /** 3812 * Callback for VPN subsystem. Currently VPN is not adapted to the service 3813 * through NetworkStateTracker since it works differently. For example, it 3814 * needs to override DNS servers but never takes the default routes. It 3815 * relies on another data network, and it could keep existing connections 3816 * alive after reconnecting, switching between networks, or even resuming 3817 * from deep sleep. Calls from applications should be done synchronously 3818 * to avoid race conditions. As these are all hidden APIs, refactoring can 3819 * be done whenever a better abstraction is developed. 3820 */ 3821 public class VpnCallback { 3822 private VpnCallback() { 3823 } 3824 3825 public void onStateChanged(NetworkInfo info) { 3826 mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget(); 3827 } 3828 3829 public void override(String iface, List<String> dnsServers, List<String> searchDomains) { 3830 if (dnsServers == null) { 3831 restore(); 3832 return; 3833 } 3834 3835 // Convert DNS servers into addresses. 3836 List<InetAddress> addresses = new ArrayList<InetAddress>(); 3837 for (String address : dnsServers) { 3838 // Double check the addresses and remove invalid ones. 3839 try { 3840 addresses.add(InetAddress.parseNumericAddress(address)); 3841 } catch (Exception e) { 3842 // ignore 3843 } 3844 } 3845 if (addresses.isEmpty()) { 3846 restore(); 3847 return; 3848 } 3849 3850 // Concatenate search domains into a string. 3851 StringBuilder buffer = new StringBuilder(); 3852 if (searchDomains != null) { 3853 for (String domain : searchDomains) { 3854 buffer.append(domain).append(' '); 3855 } 3856 } 3857 String domains = buffer.toString().trim(); 3858 3859 // Apply DNS changes. 3860 synchronized (mDnsLock) { 3861 // TODO: Re-enable this when the netId of the VPN is known. 3862 // updateDnsLocked("VPN", netId, addresses, domains); 3863 } 3864 3865 // Temporarily disable the default proxy (not global). 3866 synchronized (mProxyLock) { 3867 mDefaultProxyDisabled = true; 3868 if (mGlobalProxy == null && mDefaultProxy != null) { 3869 sendProxyBroadcast(null); 3870 } 3871 } 3872 3873 // TODO: support proxy per network. 3874 } 3875 3876 public void restore() { 3877 synchronized (mProxyLock) { 3878 mDefaultProxyDisabled = false; 3879 if (mGlobalProxy == null && mDefaultProxy != null) { 3880 sendProxyBroadcast(mDefaultProxy); 3881 } 3882 } 3883 } 3884 3885 public void protect(ParcelFileDescriptor socket) { 3886 try { 3887 final int mark = mNetd.getMarkForProtect(); 3888 NetworkUtils.markSocket(socket.getFd(), mark); 3889 } catch (RemoteException e) { 3890 } 3891 } 3892 3893 public void setRoutes(String interfaze, List<RouteInfo> routes) { 3894 for (RouteInfo route : routes) { 3895 try { 3896 mNetd.setMarkedForwardingRoute(interfaze, route); 3897 } catch (RemoteException e) { 3898 } 3899 } 3900 } 3901 3902 public void setMarkedForwarding(String interfaze) { 3903 try { 3904 mNetd.setMarkedForwarding(interfaze); 3905 } catch (RemoteException e) { 3906 } 3907 } 3908 3909 public void clearMarkedForwarding(String interfaze) { 3910 try { 3911 mNetd.clearMarkedForwarding(interfaze); 3912 } catch (RemoteException e) { 3913 } 3914 } 3915 3916 public void addUserForwarding(String interfaze, int uid, boolean forwardDns) { 3917 int uidStart = uid * UserHandle.PER_USER_RANGE; 3918 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1; 3919 addUidForwarding(interfaze, uidStart, uidEnd, forwardDns); 3920 } 3921 3922 public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) { 3923 int uidStart = uid * UserHandle.PER_USER_RANGE; 3924 int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1; 3925 clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns); 3926 } 3927 3928 public void addUidForwarding(String interfaze, int uidStart, int uidEnd, 3929 boolean forwardDns) { 3930 // TODO: Re-enable this when the netId of the VPN is known. 3931 // try { 3932 // mNetd.setUidRangeRoute(netId, uidStart, uidEnd, forwardDns); 3933 // } catch (RemoteException e) { 3934 // } 3935 3936 } 3937 3938 public void clearUidForwarding(String interfaze, int uidStart, int uidEnd, 3939 boolean forwardDns) { 3940 // TODO: Re-enable this when the netId of the VPN is known. 3941 // try { 3942 // mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd); 3943 // } catch (RemoteException e) { 3944 // } 3945 3946 } 3947 } 3948 3949 @Override 3950 public boolean updateLockdownVpn() { 3951 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 3952 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM"); 3953 return false; 3954 } 3955 3956 // Tear down existing lockdown if profile was removed 3957 mLockdownEnabled = LockdownVpnTracker.isEnabled(); 3958 if (mLockdownEnabled) { 3959 if (!mKeyStore.isUnlocked()) { 3960 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker"); 3961 return false; 3962 } 3963 3964 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN)); 3965 final VpnProfile profile = VpnProfile.decode( 3966 profileName, mKeyStore.get(Credentials.VPN + profileName)); 3967 int user = UserHandle.getUserId(Binder.getCallingUid()); 3968 synchronized(mVpns) { 3969 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user), 3970 profile)); 3971 } 3972 } else { 3973 setLockdownTracker(null); 3974 } 3975 3976 return true; 3977 } 3978 3979 /** 3980 * Internally set new {@link LockdownVpnTracker}, shutting down any existing 3981 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown. 3982 */ 3983 private void setLockdownTracker(LockdownVpnTracker tracker) { 3984 // Shutdown any existing tracker 3985 final LockdownVpnTracker existing = mLockdownTracker; 3986 mLockdownTracker = null; 3987 if (existing != null) { 3988 existing.shutdown(); 3989 } 3990 3991 try { 3992 if (tracker != null) { 3993 mNetd.setFirewallEnabled(true); 3994 mNetd.setFirewallInterfaceRule("lo", true); 3995 mLockdownTracker = tracker; 3996 mLockdownTracker.init(); 3997 } else { 3998 mNetd.setFirewallEnabled(false); 3999 } 4000 } catch (RemoteException e) { 4001 // ignored; NMS lives inside system_server 4002 } 4003 } 4004 4005 private void throwIfLockdownEnabled() { 4006 if (mLockdownEnabled) { 4007 throw new IllegalStateException("Unavailable in lockdown mode"); 4008 } 4009 } 4010 4011 public void supplyMessenger(int networkType, Messenger messenger) { 4012 enforceConnectivityInternalPermission(); 4013 4014 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) { 4015 mNetTrackers[networkType].supplyMessenger(messenger); 4016 } 4017 } 4018 4019 public int findConnectionTypeForIface(String iface) { 4020 enforceConnectivityInternalPermission(); 4021 4022 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE; 4023 for (NetworkStateTracker tracker : mNetTrackers) { 4024 if (tracker != null) { 4025 LinkProperties lp = tracker.getLinkProperties(); 4026 if (lp != null && iface.equals(lp.getInterfaceName())) { 4027 return tracker.getNetworkInfo().getType(); 4028 } 4029 } 4030 } 4031 return ConnectivityManager.TYPE_NONE; 4032 } 4033 4034 /** 4035 * Have mobile data fail fast if enabled. 4036 * 4037 * @param enabled DctConstants.ENABLED/DISABLED 4038 */ 4039 private void setEnableFailFastMobileData(int enabled) { 4040 int tag; 4041 4042 if (enabled == DctConstants.ENABLED) { 4043 tag = mEnableFailFastMobileDataTag.incrementAndGet(); 4044 } else { 4045 tag = mEnableFailFastMobileDataTag.get(); 4046 } 4047 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag, 4048 enabled)); 4049 } 4050 4051 private boolean isMobileDataStateTrackerReady() { 4052 MobileDataStateTracker mdst = 4053 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4054 return (mdst != null) && (mdst.isReady()); 4055 } 4056 4057 /** 4058 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE) 4059 */ 4060 4061 /** 4062 * No connection was possible to the network. 4063 * This is NOT a warm sim. 4064 */ 4065 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0; 4066 4067 /** 4068 * A connection was made to the internet, all is well. 4069 * This is NOT a warm sim. 4070 */ 4071 private static final int CMP_RESULT_CODE_CONNECTABLE = 1; 4072 4073 /** 4074 * A connection was made but no dns server was available to resolve a name to address. 4075 * This is NOT a warm sim since provisioning network is supported. 4076 */ 4077 private static final int CMP_RESULT_CODE_NO_DNS = 2; 4078 4079 /** 4080 * A connection was made but could not open a TCP connection. 4081 * This is NOT a warm sim since provisioning network is supported. 4082 */ 4083 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3; 4084 4085 /** 4086 * A connection was made but there was a redirection, we appear to be in walled garden. 4087 * This is an indication of a warm sim on a mobile network such as T-Mobile. 4088 */ 4089 private static final int CMP_RESULT_CODE_REDIRECTED = 4; 4090 4091 /** 4092 * The mobile network is a provisioning network. 4093 * This is an indication of a warm sim on a mobile network such as AT&T. 4094 */ 4095 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5; 4096 4097 /** 4098 * The mobile network is provisioning 4099 */ 4100 private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6; 4101 4102 private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false); 4103 private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false); 4104 4105 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false); 4106 4107 @Override 4108 public int checkMobileProvisioning(int suggestedTimeOutMs) { 4109 int timeOutMs = -1; 4110 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs); 4111 enforceConnectivityInternalPermission(); 4112 4113 final long token = Binder.clearCallingIdentity(); 4114 try { 4115 timeOutMs = suggestedTimeOutMs; 4116 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) { 4117 timeOutMs = CheckMp.MAX_TIMEOUT_MS; 4118 } 4119 4120 // Check that mobile networks are supported 4121 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE) 4122 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) { 4123 if (DBG) log("checkMobileProvisioning: X no mobile network"); 4124 return timeOutMs; 4125 } 4126 4127 // If we're already checking don't do it again 4128 // TODO: Add a queue of results... 4129 if (mIsCheckingMobileProvisioning.getAndSet(true)) { 4130 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment"); 4131 return timeOutMs; 4132 } 4133 4134 // Start off with mobile notification off 4135 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null); 4136 4137 CheckMp checkMp = new CheckMp(mContext, this); 4138 CheckMp.CallBack cb = new CheckMp.CallBack() { 4139 @Override 4140 void onComplete(Integer result) { 4141 if (DBG) log("CheckMp.onComplete: result=" + result); 4142 NetworkInfo ni = 4143 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo(); 4144 switch(result) { 4145 case CMP_RESULT_CODE_CONNECTABLE: 4146 case CMP_RESULT_CODE_NO_CONNECTION: 4147 case CMP_RESULT_CODE_NO_DNS: 4148 case CMP_RESULT_CODE_NO_TCP_CONNECTION: { 4149 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection"); 4150 break; 4151 } 4152 case CMP_RESULT_CODE_REDIRECTED: { 4153 if (DBG) log("CheckMp.onComplete: warm sim"); 4154 String url = getMobileProvisioningUrl(); 4155 if (TextUtils.isEmpty(url)) { 4156 url = getMobileRedirectedProvisioningUrl(); 4157 } 4158 if (TextUtils.isEmpty(url) == false) { 4159 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url); 4160 setProvNotificationVisible(true, 4161 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(), 4162 url); 4163 } else { 4164 if (DBG) log("CheckMp.onComplete: warm (redirected), no url"); 4165 } 4166 break; 4167 } 4168 case CMP_RESULT_CODE_PROVISIONING_NETWORK: { 4169 String url = getMobileProvisioningUrl(); 4170 if (TextUtils.isEmpty(url) == false) { 4171 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url); 4172 setProvNotificationVisible(true, 4173 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(), 4174 url); 4175 // Mark that we've got a provisioning network and 4176 // Disable Mobile Data until user actually starts provisioning. 4177 mIsProvisioningNetwork.set(true); 4178 MobileDataStateTracker mdst = (MobileDataStateTracker) 4179 mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4180 mdst.setInternalDataEnable(false); 4181 } else { 4182 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url"); 4183 } 4184 break; 4185 } 4186 case CMP_RESULT_CODE_IS_PROVISIONING: { 4187 // FIXME: Need to know when provisioning is done. Probably we can 4188 // check the completion status if successful we're done if we 4189 // "timedout" or still connected to provisioning APN turn off data? 4190 if (DBG) log("CheckMp.onComplete: provisioning started"); 4191 mIsStartingProvisioning.set(false); 4192 break; 4193 } 4194 default: { 4195 loge("CheckMp.onComplete: ignore unexpected result=" + result); 4196 break; 4197 } 4198 } 4199 mIsCheckingMobileProvisioning.set(false); 4200 } 4201 }; 4202 CheckMp.Params params = 4203 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb); 4204 if (DBG) log("checkMobileProvisioning: params=" + params); 4205 // TODO: Reenable when calls to the now defunct 4206 // MobileDataStateTracker.isProvisioningNetwork() are removed. 4207 // This code should be moved to the Telephony code. 4208 // checkMp.execute(params); 4209 } finally { 4210 Binder.restoreCallingIdentity(token); 4211 if (DBG) log("checkMobileProvisioning: X"); 4212 } 4213 return timeOutMs; 4214 } 4215 4216 static class CheckMp extends 4217 AsyncTask<CheckMp.Params, Void, Integer> { 4218 private static final String CHECKMP_TAG = "CheckMp"; 4219 4220 // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures 4221 private static boolean mTestingFailures; 4222 4223 // Choosing 4 loops as half of them will use HTTPS and the other half HTTP 4224 private static final int MAX_LOOPS = 4; 4225 4226 // Number of milli-seconds to complete all of the retires 4227 public static final int MAX_TIMEOUT_MS = 60000; 4228 4229 // The socket should retry only 5 seconds, the default is longer 4230 private static final int SOCKET_TIMEOUT_MS = 5000; 4231 4232 // Sleep time for network errors 4233 private static final int NET_ERROR_SLEEP_SEC = 3; 4234 4235 // Sleep time for network route establishment 4236 private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3; 4237 4238 // Short sleep time for polling :( 4239 private static final int POLLING_SLEEP_SEC = 1; 4240 4241 private Context mContext; 4242 private ConnectivityService mCs; 4243 private TelephonyManager mTm; 4244 private Params mParams; 4245 4246 /** 4247 * Parameters for AsyncTask.execute 4248 */ 4249 static class Params { 4250 private String mUrl; 4251 private long mTimeOutMs; 4252 private CallBack mCb; 4253 4254 Params(String url, long timeOutMs, CallBack cb) { 4255 mUrl = url; 4256 mTimeOutMs = timeOutMs; 4257 mCb = cb; 4258 } 4259 4260 @Override 4261 public String toString() { 4262 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}"; 4263 } 4264 } 4265 4266 // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be 4267 // issued by name or ip address, for Google its by name so when we construct 4268 // this HostnameVerifier we'll pass the original Uri and use it to verify 4269 // the host. If the host name in the original uril fails we'll test the 4270 // hostname parameter just incase things change. 4271 static class CheckMpHostnameVerifier implements HostnameVerifier { 4272 Uri mOrgUri; 4273 4274 CheckMpHostnameVerifier(Uri orgUri) { 4275 mOrgUri = orgUri; 4276 } 4277 4278 @Override 4279 public boolean verify(String hostname, SSLSession session) { 4280 HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); 4281 String orgUriHost = mOrgUri.getHost(); 4282 boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session); 4283 if (DBG) { 4284 log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname 4285 + " orgUriHost=" + orgUriHost); 4286 } 4287 return retVal; 4288 } 4289 } 4290 4291 /** 4292 * The call back object passed in Params. onComplete will be called 4293 * on the main thread. 4294 */ 4295 abstract static class CallBack { 4296 // Called on the main thread. 4297 abstract void onComplete(Integer result); 4298 } 4299 4300 public CheckMp(Context context, ConnectivityService cs) { 4301 if (Build.IS_DEBUGGABLE) { 4302 mTestingFailures = 4303 SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1; 4304 } else { 4305 mTestingFailures = false; 4306 } 4307 4308 mContext = context; 4309 mCs = cs; 4310 4311 // Setup access to TelephonyService we'll be using. 4312 mTm = (TelephonyManager) mContext.getSystemService( 4313 Context.TELEPHONY_SERVICE); 4314 } 4315 4316 /** 4317 * Get the default url to use for the test. 4318 */ 4319 public String getDefaultUrl() { 4320 // See http://go/clientsdns for usage approval 4321 String server = Settings.Global.getString(mContext.getContentResolver(), 4322 Settings.Global.CAPTIVE_PORTAL_SERVER); 4323 if (server == null) { 4324 server = "clients3.google.com"; 4325 } 4326 return "http://" + server + "/generate_204"; 4327 } 4328 4329 /** 4330 * Detect if its possible to connect to the http url. DNS based detection techniques 4331 * do not work at all hotspots. The best way to check is to perform a request to 4332 * a known address that fetches the data we expect. 4333 */ 4334 private synchronized Integer isMobileOk(Params params) { 4335 Integer result = CMP_RESULT_CODE_NO_CONNECTION; 4336 Uri orgUri = Uri.parse(params.mUrl); 4337 Random rand = new Random(); 4338 mParams = params; 4339 4340 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) { 4341 result = CMP_RESULT_CODE_NO_CONNECTION; 4342 log("isMobileOk: X not mobile capable result=" + result); 4343 return result; 4344 } 4345 4346 if (mCs.mIsStartingProvisioning.get()) { 4347 result = CMP_RESULT_CODE_IS_PROVISIONING; 4348 log("isMobileOk: X is provisioning result=" + result); 4349 return result; 4350 } 4351 4352 // See if we've already determined we've got a provisioning connection, 4353 // if so we don't need to do anything active. 4354 MobileDataStateTracker mdstDefault = (MobileDataStateTracker) 4355 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4356 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork(); 4357 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning); 4358 4359 MobileDataStateTracker mdstHipri = (MobileDataStateTracker) 4360 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4361 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork(); 4362 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning); 4363 4364 if (isDefaultProvisioning || isHipriProvisioning) { 4365 result = CMP_RESULT_CODE_PROVISIONING_NETWORK; 4366 log("isMobileOk: X default || hipri is provisioning result=" + result); 4367 return result; 4368 } 4369 4370 try { 4371 // Continue trying to connect until time has run out 4372 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs; 4373 4374 if (!mCs.isMobileDataStateTrackerReady()) { 4375 // Wait for MobileDataStateTracker to be ready. 4376 if (DBG) log("isMobileOk: mdst is not ready"); 4377 while(SystemClock.elapsedRealtime() < endTime) { 4378 if (mCs.isMobileDataStateTrackerReady()) { 4379 // Enable fail fast as we'll do retries here and use a 4380 // hipri connection so the default connection stays active. 4381 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data"); 4382 mCs.setEnableFailFastMobileData(DctConstants.ENABLED); 4383 break; 4384 } 4385 sleep(POLLING_SLEEP_SEC); 4386 } 4387 } 4388 4389 log("isMobileOk: start hipri url=" + params.mUrl); 4390 4391 // First wait until we can start using hipri 4392 Binder binder = new Binder(); 4393 while(SystemClock.elapsedRealtime() < endTime) { 4394 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, 4395 Phone.FEATURE_ENABLE_HIPRI, binder); 4396 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE) 4397 || (ret == PhoneConstants.APN_REQUEST_STARTED)) { 4398 log("isMobileOk: hipri started"); 4399 break; 4400 } 4401 if (VDBG) log("isMobileOk: hipri not started yet"); 4402 result = CMP_RESULT_CODE_NO_CONNECTION; 4403 sleep(POLLING_SLEEP_SEC); 4404 } 4405 4406 // Continue trying to connect until time has run out 4407 while(SystemClock.elapsedRealtime() < endTime) { 4408 try { 4409 // Wait for hipri to connect. 4410 // TODO: Don't poll and handle situation where hipri fails 4411 // because default is retrying. See b/9569540 4412 NetworkInfo.State state = mCs 4413 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); 4414 if (state != NetworkInfo.State.CONNECTED) { 4415 if (true/*VDBG*/) { 4416 log("isMobileOk: not connected ni=" + 4417 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI)); 4418 } 4419 sleep(POLLING_SLEEP_SEC); 4420 result = CMP_RESULT_CODE_NO_CONNECTION; 4421 continue; 4422 } 4423 4424 // Hipri has started check if this is a provisioning url 4425 MobileDataStateTracker mdst = (MobileDataStateTracker) 4426 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 4427 if (mdst.isProvisioningNetwork()) { 4428 result = CMP_RESULT_CODE_PROVISIONING_NETWORK; 4429 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result); 4430 return result; 4431 } else { 4432 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue"); 4433 } 4434 4435 // Get of the addresses associated with the url host. We need to use the 4436 // address otherwise HttpURLConnection object will use the name to get 4437 // the addresses and will try every address but that will bypass the 4438 // route to host we setup and the connection could succeed as the default 4439 // interface might be connected to the internet via wifi or other interface. 4440 InetAddress[] addresses; 4441 try { 4442 addresses = InetAddress.getAllByName(orgUri.getHost()); 4443 } catch (UnknownHostException e) { 4444 result = CMP_RESULT_CODE_NO_DNS; 4445 log("isMobileOk: X UnknownHostException result=" + result); 4446 return result; 4447 } 4448 log("isMobileOk: addresses=" + inetAddressesToString(addresses)); 4449 4450 // Get the type of addresses supported by this link 4451 LinkProperties lp = mCs.getLinkProperties( 4452 ConnectivityManager.TYPE_MOBILE_HIPRI); 4453 boolean linkHasIpv4 = lp.hasIPv4Address(); 4454 boolean linkHasIpv6 = lp.hasIPv6Address(); 4455 log("isMobileOk: linkHasIpv4=" + linkHasIpv4 4456 + " linkHasIpv6=" + linkHasIpv6); 4457 4458 final ArrayList<InetAddress> validAddresses = 4459 new ArrayList<InetAddress>(addresses.length); 4460 4461 for (InetAddress addr : addresses) { 4462 if (((addr instanceof Inet4Address) && linkHasIpv4) || 4463 ((addr instanceof Inet6Address) && linkHasIpv6)) { 4464 validAddresses.add(addr); 4465 } 4466 } 4467 4468 if (validAddresses.size() == 0) { 4469 return CMP_RESULT_CODE_NO_CONNECTION; 4470 } 4471 4472 int addrTried = 0; 4473 while (true) { 4474 // Loop through at most MAX_LOOPS valid addresses or until 4475 // we run out of time 4476 if (addrTried++ >= MAX_LOOPS) { 4477 log("isMobileOk: too many loops tried - giving up"); 4478 break; 4479 } 4480 if (SystemClock.elapsedRealtime() >= endTime) { 4481 log("isMobileOk: spend too much time - giving up"); 4482 break; 4483 } 4484 4485 InetAddress hostAddr = validAddresses.get(rand.nextInt( 4486 validAddresses.size())); 4487 4488 // Make a route to host so we check the specific interface. 4489 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI, 4490 hostAddr.getAddress(), null)) { 4491 // Wait a short time to be sure the route is established ?? 4492 log("isMobileOk:" 4493 + " wait to establish route to hostAddr=" + hostAddr); 4494 sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC); 4495 } else { 4496 log("isMobileOk:" 4497 + " could not establish route to hostAddr=" + hostAddr); 4498 // Wait a short time before the next attempt 4499 sleep(NET_ERROR_SLEEP_SEC); 4500 continue; 4501 } 4502 4503 // Rewrite the url to have numeric address to use the specific route 4504 // using http for half the attempts and https for the other half. 4505 // Doing https first and http second as on a redirected walled garden 4506 // such as t-mobile uses we get a SocketTimeoutException: "SSL 4507 // handshake timed out" which we declare as 4508 // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by 4509 // having http second we will be using logic used for some time. 4510 URL newUrl; 4511 String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http"; 4512 newUrl = new URL(scheme, hostAddr.getHostAddress(), 4513 orgUri.getPath()); 4514 log("isMobileOk: newUrl=" + newUrl); 4515 4516 HttpURLConnection urlConn = null; 4517 try { 4518 // Open the connection set the request headers and get the response 4519 urlConn = (HttpURLConnection)newUrl.openConnection( 4520 java.net.Proxy.NO_PROXY); 4521 if (scheme.equals("https")) { 4522 ((HttpsURLConnection)urlConn).setHostnameVerifier( 4523 new CheckMpHostnameVerifier(orgUri)); 4524 } 4525 urlConn.setInstanceFollowRedirects(false); 4526 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS); 4527 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS); 4528 urlConn.setUseCaches(false); 4529 urlConn.setAllowUserInteraction(false); 4530 // Set the "Connection" to "Close" as by default "Keep-Alive" 4531 // is used which is useless in this case. 4532 urlConn.setRequestProperty("Connection", "close"); 4533 int responseCode = urlConn.getResponseCode(); 4534 4535 // For debug display the headers 4536 Map<String, List<String>> headers = urlConn.getHeaderFields(); 4537 log("isMobileOk: headers=" + headers); 4538 4539 // Close the connection 4540 urlConn.disconnect(); 4541 urlConn = null; 4542 4543 if (mTestingFailures) { 4544 // Pretend no connection, this tests using http and https 4545 result = CMP_RESULT_CODE_NO_CONNECTION; 4546 log("isMobileOk: TESTING_FAILURES, pretend no connction"); 4547 continue; 4548 } 4549 4550 if (responseCode == 204) { 4551 // Return 4552 result = CMP_RESULT_CODE_CONNECTABLE; 4553 log("isMobileOk: X got expected responseCode=" + responseCode 4554 + " result=" + result); 4555 return result; 4556 } else { 4557 // Retry to be sure this was redirected, we've gotten 4558 // occasions where a server returned 200 even though 4559 // the device didn't have a "warm" sim. 4560 log("isMobileOk: not expected responseCode=" + responseCode); 4561 // TODO - it would be nice in the single-address case to do 4562 // another DNS resolve here, but flushing the cache is a bit 4563 // heavy-handed. 4564 result = CMP_RESULT_CODE_REDIRECTED; 4565 } 4566 } catch (Exception e) { 4567 log("isMobileOk: HttpURLConnection Exception" + e); 4568 result = CMP_RESULT_CODE_NO_TCP_CONNECTION; 4569 if (urlConn != null) { 4570 urlConn.disconnect(); 4571 urlConn = null; 4572 } 4573 sleep(NET_ERROR_SLEEP_SEC); 4574 continue; 4575 } 4576 } 4577 log("isMobileOk: X loops|timed out result=" + result); 4578 return result; 4579 } catch (Exception e) { 4580 log("isMobileOk: Exception e=" + e); 4581 continue; 4582 } 4583 } 4584 log("isMobileOk: timed out"); 4585 } finally { 4586 log("isMobileOk: F stop hipri"); 4587 mCs.setEnableFailFastMobileData(DctConstants.DISABLED); 4588 mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, 4589 Phone.FEATURE_ENABLE_HIPRI); 4590 4591 // Wait for hipri to disconnect. 4592 long endTime = SystemClock.elapsedRealtime() + 5000; 4593 4594 while(SystemClock.elapsedRealtime() < endTime) { 4595 NetworkInfo.State state = mCs 4596 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); 4597 if (state != NetworkInfo.State.DISCONNECTED) { 4598 if (VDBG) { 4599 log("isMobileOk: connected ni=" + 4600 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI)); 4601 } 4602 sleep(POLLING_SLEEP_SEC); 4603 continue; 4604 } 4605 } 4606 4607 log("isMobileOk: X result=" + result); 4608 } 4609 return result; 4610 } 4611 4612 @Override 4613 protected Integer doInBackground(Params... params) { 4614 return isMobileOk(params[0]); 4615 } 4616 4617 @Override 4618 protected void onPostExecute(Integer result) { 4619 log("onPostExecute: result=" + result); 4620 if ((mParams != null) && (mParams.mCb != null)) { 4621 mParams.mCb.onComplete(result); 4622 } 4623 } 4624 4625 private String inetAddressesToString(InetAddress[] addresses) { 4626 StringBuffer sb = new StringBuffer(); 4627 boolean firstTime = true; 4628 for(InetAddress addr : addresses) { 4629 if (firstTime) { 4630 firstTime = false; 4631 } else { 4632 sb.append(","); 4633 } 4634 sb.append(addr); 4635 } 4636 return sb.toString(); 4637 } 4638 4639 private void printNetworkInfo() { 4640 boolean hasIccCard = mTm.hasIccCard(); 4641 int simState = mTm.getSimState(); 4642 log("hasIccCard=" + hasIccCard 4643 + " simState=" + simState); 4644 NetworkInfo[] ni = mCs.getAllNetworkInfo(); 4645 if (ni != null) { 4646 log("ni.length=" + ni.length); 4647 for (NetworkInfo netInfo: ni) { 4648 log("netInfo=" + netInfo.toString()); 4649 } 4650 } else { 4651 log("no network info ni=null"); 4652 } 4653 } 4654 4655 /** 4656 * Sleep for a few seconds then return. 4657 * @param seconds 4658 */ 4659 private static void sleep(int seconds) { 4660 long stopTime = System.nanoTime() + (seconds * 1000000000); 4661 long sleepTime; 4662 while ((sleepTime = stopTime - System.nanoTime()) > 0) { 4663 try { 4664 Thread.sleep(sleepTime / 1000000); 4665 } catch (InterruptedException ignored) { 4666 } 4667 } 4668 } 4669 4670 private static void log(String s) { 4671 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s); 4672 } 4673 } 4674 4675 // TODO: Move to ConnectivityManager and make public? 4676 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION = 4677 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION"; 4678 4679 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() { 4680 @Override 4681 public void onReceive(Context context, Intent intent) { 4682 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) { 4683 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL")); 4684 } 4685 } 4686 }; 4687 4688 private void handleMobileProvisioningAction(String url) { 4689 // Mark notification as not visible 4690 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null); 4691 4692 // If provisioning network handle as a special case, 4693 // otherwise launch browser with the intent directly. 4694 if (mIsProvisioningNetwork.get()) { 4695 if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch"); 4696// mIsStartingProvisioning.set(true); 4697// MobileDataStateTracker mdst = (MobileDataStateTracker) 4698// mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 4699// mdst.setEnableFailFastMobileData(DctConstants.ENABLED); 4700// mdst.enableMobileProvisioning(url); 4701 } else { 4702 if (DBG) log("handleMobileProvisioningAction: not prov network"); 4703 // Check for apps that can handle provisioning first 4704 Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP); 4705 provisioningIntent.addCategory(TelephonyIntents.CATEGORY_MCCMNC_PREFIX 4706 + mTelephonyManager.getSimOperator()); 4707 if (mContext.getPackageManager().resolveActivity(provisioningIntent, 0 /* flags */) 4708 != null) { 4709 provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 4710 Intent.FLAG_ACTIVITY_NEW_TASK); 4711 mContext.startActivity(provisioningIntent); 4712 } else { 4713 // If no apps exist, use standard URL ACTION_VIEW method 4714 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, 4715 Intent.CATEGORY_APP_BROWSER); 4716 newIntent.setData(Uri.parse(url)); 4717 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 4718 Intent.FLAG_ACTIVITY_NEW_TASK); 4719 try { 4720 mContext.startActivity(newIntent); 4721 } catch (ActivityNotFoundException e) { 4722 loge("handleMobileProvisioningAction: startActivity failed" + e); 4723 } 4724 } 4725 } 4726 } 4727 4728 private static final String NOTIFICATION_ID = "CaptivePortal.Notification"; 4729 private volatile boolean mIsNotificationVisible = false; 4730 4731 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo, 4732 String url) { 4733 if (DBG) { 4734 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType 4735 + " extraInfo=" + extraInfo + " url=" + url); 4736 } 4737 4738 Resources r = Resources.getSystem(); 4739 NotificationManager notificationManager = (NotificationManager) mContext 4740 .getSystemService(Context.NOTIFICATION_SERVICE); 4741 4742 if (visible) { 4743 CharSequence title; 4744 CharSequence details; 4745 int icon; 4746 Intent intent; 4747 Notification notification = new Notification(); 4748 switch (networkType) { 4749 case ConnectivityManager.TYPE_WIFI: 4750 title = r.getString(R.string.wifi_available_sign_in, 0); 4751 details = r.getString(R.string.network_available_sign_in_detailed, 4752 extraInfo); 4753 icon = R.drawable.stat_notify_wifi_in_range; 4754 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 4755 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 4756 Intent.FLAG_ACTIVITY_NEW_TASK); 4757 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0); 4758 break; 4759 case ConnectivityManager.TYPE_MOBILE: 4760 case ConnectivityManager.TYPE_MOBILE_HIPRI: 4761 title = r.getString(R.string.network_available_sign_in, 0); 4762 // TODO: Change this to pull from NetworkInfo once a printable 4763 // name has been added to it 4764 details = mTelephonyManager.getNetworkOperatorName(); 4765 icon = R.drawable.stat_notify_rssi_in_range; 4766 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION); 4767 intent.putExtra("EXTRA_URL", url); 4768 intent.setFlags(0); 4769 notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); 4770 break; 4771 default: 4772 title = r.getString(R.string.network_available_sign_in, 0); 4773 details = r.getString(R.string.network_available_sign_in_detailed, 4774 extraInfo); 4775 icon = R.drawable.stat_notify_rssi_in_range; 4776 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 4777 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 4778 Intent.FLAG_ACTIVITY_NEW_TASK); 4779 notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0); 4780 break; 4781 } 4782 4783 notification.when = 0; 4784 notification.icon = icon; 4785 notification.flags = Notification.FLAG_AUTO_CANCEL; 4786 notification.tickerText = title; 4787 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent); 4788 4789 try { 4790 notificationManager.notify(NOTIFICATION_ID, networkType, notification); 4791 } catch (NullPointerException npe) { 4792 loge("setNotificaitionVisible: visible notificationManager npe=" + npe); 4793 npe.printStackTrace(); 4794 } 4795 } else { 4796 try { 4797 notificationManager.cancel(NOTIFICATION_ID, networkType); 4798 } catch (NullPointerException npe) { 4799 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe); 4800 npe.printStackTrace(); 4801 } 4802 } 4803 mIsNotificationVisible = visible; 4804 } 4805 4806 /** Location to an updatable file listing carrier provisioning urls. 4807 * An example: 4808 * 4809 * <?xml version="1.0" encoding="utf-8"?> 4810 * <provisioningUrls> 4811 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl> 4812 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl> 4813 * </provisioningUrls> 4814 */ 4815 private static final String PROVISIONING_URL_PATH = 4816 "/data/misc/radio/provisioning_urls.xml"; 4817 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH); 4818 4819 /** XML tag for root element. */ 4820 private static final String TAG_PROVISIONING_URLS = "provisioningUrls"; 4821 /** XML tag for individual url */ 4822 private static final String TAG_PROVISIONING_URL = "provisioningUrl"; 4823 /** XML tag for redirected url */ 4824 private static final String TAG_REDIRECTED_URL = "redirectedUrl"; 4825 /** XML attribute for mcc */ 4826 private static final String ATTR_MCC = "mcc"; 4827 /** XML attribute for mnc */ 4828 private static final String ATTR_MNC = "mnc"; 4829 4830 private static final int REDIRECTED_PROVISIONING = 1; 4831 private static final int PROVISIONING = 2; 4832 4833 private String getProvisioningUrlBaseFromFile(int type) { 4834 FileReader fileReader = null; 4835 XmlPullParser parser = null; 4836 Configuration config = mContext.getResources().getConfiguration(); 4837 String tagType; 4838 4839 switch (type) { 4840 case PROVISIONING: 4841 tagType = TAG_PROVISIONING_URL; 4842 break; 4843 case REDIRECTED_PROVISIONING: 4844 tagType = TAG_REDIRECTED_URL; 4845 break; 4846 default: 4847 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " + 4848 type); 4849 } 4850 4851 try { 4852 fileReader = new FileReader(mProvisioningUrlFile); 4853 parser = Xml.newPullParser(); 4854 parser.setInput(fileReader); 4855 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS); 4856 4857 while (true) { 4858 XmlUtils.nextElement(parser); 4859 4860 String element = parser.getName(); 4861 if (element == null) break; 4862 4863 if (element.equals(tagType)) { 4864 String mcc = parser.getAttributeValue(null, ATTR_MCC); 4865 try { 4866 if (mcc != null && Integer.parseInt(mcc) == config.mcc) { 4867 String mnc = parser.getAttributeValue(null, ATTR_MNC); 4868 if (mnc != null && Integer.parseInt(mnc) == config.mnc) { 4869 parser.next(); 4870 if (parser.getEventType() == XmlPullParser.TEXT) { 4871 return parser.getText(); 4872 } 4873 } 4874 } 4875 } catch (NumberFormatException e) { 4876 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e); 4877 } 4878 } 4879 } 4880 return null; 4881 } catch (FileNotFoundException e) { 4882 loge("Carrier Provisioning Urls file not found"); 4883 } catch (XmlPullParserException e) { 4884 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e); 4885 } catch (IOException e) { 4886 loge("I/O exception reading Carrier Provisioning Urls file: " + e); 4887 } finally { 4888 if (fileReader != null) { 4889 try { 4890 fileReader.close(); 4891 } catch (IOException e) {} 4892 } 4893 } 4894 return null; 4895 } 4896 4897 @Override 4898 public String getMobileRedirectedProvisioningUrl() { 4899 enforceConnectivityInternalPermission(); 4900 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING); 4901 if (TextUtils.isEmpty(url)) { 4902 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url); 4903 } 4904 return url; 4905 } 4906 4907 @Override 4908 public String getMobileProvisioningUrl() { 4909 enforceConnectivityInternalPermission(); 4910 String url = getProvisioningUrlBaseFromFile(PROVISIONING); 4911 if (TextUtils.isEmpty(url)) { 4912 url = mContext.getResources().getString(R.string.mobile_provisioning_url); 4913 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url); 4914 } else { 4915 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url); 4916 } 4917 // populate the iccid, imei and phone number in the provisioning url. 4918 if (!TextUtils.isEmpty(url)) { 4919 String phoneNumber = mTelephonyManager.getLine1Number(); 4920 if (TextUtils.isEmpty(phoneNumber)) { 4921 phoneNumber = "0000000000"; 4922 } 4923 url = String.format(url, 4924 mTelephonyManager.getSimSerialNumber() /* ICCID */, 4925 mTelephonyManager.getDeviceId() /* IMEI */, 4926 phoneNumber /* Phone numer */); 4927 } 4928 4929 return url; 4930 } 4931 4932 @Override 4933 public void setProvisioningNotificationVisible(boolean visible, int networkType, 4934 String extraInfo, String url) { 4935 enforceConnectivityInternalPermission(); 4936 setProvNotificationVisible(visible, networkType, extraInfo, url); 4937 } 4938 4939 @Override 4940 public void setAirplaneMode(boolean enable) { 4941 enforceConnectivityInternalPermission(); 4942 final long ident = Binder.clearCallingIdentity(); 4943 try { 4944 final ContentResolver cr = mContext.getContentResolver(); 4945 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 4946 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 4947 intent.putExtra("state", enable); 4948 mContext.sendBroadcast(intent); 4949 } finally { 4950 Binder.restoreCallingIdentity(ident); 4951 } 4952 } 4953 4954 private void onUserStart(int userId) { 4955 synchronized(mVpns) { 4956 Vpn userVpn = mVpns.get(userId); 4957 if (userVpn != null) { 4958 loge("Starting user already has a VPN"); 4959 return; 4960 } 4961 userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId); 4962 mVpns.put(userId, userVpn); 4963 userVpn.startMonitoring(mContext, mTrackerHandler); 4964 } 4965 } 4966 4967 private void onUserStop(int userId) { 4968 synchronized(mVpns) { 4969 Vpn userVpn = mVpns.get(userId); 4970 if (userVpn == null) { 4971 loge("Stopping user has no VPN"); 4972 return; 4973 } 4974 mVpns.delete(userId); 4975 } 4976 } 4977 4978 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() { 4979 @Override 4980 public void onReceive(Context context, Intent intent) { 4981 final String action = intent.getAction(); 4982 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 4983 if (userId == UserHandle.USER_NULL) return; 4984 4985 if (Intent.ACTION_USER_STARTING.equals(action)) { 4986 onUserStart(userId); 4987 } else if (Intent.ACTION_USER_STOPPING.equals(action)) { 4988 onUserStop(userId); 4989 } 4990 } 4991 }; 4992 4993 @Override 4994 public LinkQualityInfo getLinkQualityInfo(int networkType) { 4995 enforceAccessPermission(); 4996 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) { 4997 return mNetTrackers[networkType].getLinkQualityInfo(); 4998 } else { 4999 return null; 5000 } 5001 } 5002 5003 @Override 5004 public LinkQualityInfo getActiveLinkQualityInfo() { 5005 enforceAccessPermission(); 5006 if (isNetworkTypeValid(mActiveDefaultNetwork) && 5007 mNetTrackers[mActiveDefaultNetwork] != null) { 5008 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo(); 5009 } else { 5010 return null; 5011 } 5012 } 5013 5014 @Override 5015 public LinkQualityInfo[] getAllLinkQualityInfo() { 5016 enforceAccessPermission(); 5017 final ArrayList<LinkQualityInfo> result = Lists.newArrayList(); 5018 for (NetworkStateTracker tracker : mNetTrackers) { 5019 if (tracker != null) { 5020 LinkQualityInfo li = tracker.getLinkQualityInfo(); 5021 if (li != null) { 5022 result.add(li); 5023 } 5024 } 5025 } 5026 5027 return result.toArray(new LinkQualityInfo[result.size()]); 5028 } 5029 5030 /* Infrastructure for network sampling */ 5031 5032 private void handleNetworkSamplingTimeout() { 5033 5034 log("Sampling interval elapsed, updating statistics .."); 5035 5036 // initialize list of interfaces .. 5037 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample = 5038 new HashMap<String, SamplingDataTracker.SamplingSnapshot>(); 5039 for (NetworkStateTracker tracker : mNetTrackers) { 5040 if (tracker != null) { 5041 String ifaceName = tracker.getNetworkInterfaceName(); 5042 if (ifaceName != null) { 5043 mapIfaceToSample.put(ifaceName, null); 5044 } 5045 } 5046 } 5047 5048 // Read samples for all interfaces 5049 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample); 5050 5051 // process samples for all networks 5052 for (NetworkStateTracker tracker : mNetTrackers) { 5053 if (tracker != null) { 5054 String ifaceName = tracker.getNetworkInterfaceName(); 5055 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName); 5056 if (ss != null) { 5057 // end the previous sampling cycle 5058 tracker.stopSampling(ss); 5059 // start a new sampling cycle .. 5060 tracker.startSampling(ss); 5061 } 5062 } 5063 } 5064 5065 log("Done."); 5066 5067 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(), 5068 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS, 5069 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS); 5070 5071 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds"); 5072 5073 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent); 5074 } 5075 5076 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) { 5077 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds; 5078 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent); 5079 } 5080 5081 private final ArrayList<AsyncChannel> mNetworkFactories = new ArrayList<AsyncChannel>(); 5082 5083 public void registerNetworkFactory(Messenger messenger) { 5084 enforceConnectivityInternalPermission(); 5085 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, messenger)); 5086 } 5087 5088 private void handleRegisterNetworkFactory(Messenger messenger) { 5089 if (VDBG) log("Got NetworkFactory Messenger"); 5090 AsyncChannel ac = new AsyncChannel(); 5091 mNetworkFactories.add(ac); 5092 ac.connect(mContext, mTrackerHandler, messenger); 5093 } 5094 5095 // NetworkRequest by requestId 5096 private final SparseArray<NetworkRequest> mNetworkRequests = new SparseArray<NetworkRequest>(); 5097 5098 /** 5099 * NetworkAgentInfo supporting a request by requestId. 5100 * These have already been vetted (their Capabilities satisfy the request) 5101 * and the are the highest scored network available. 5102 * the are keyed off the Requests requestId. 5103 */ 5104 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = 5105 new SparseArray<NetworkAgentInfo>(); 5106 5107 // NetworkAgentInfo keyed off its connecting messenger 5108 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays 5109 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = 5110 new HashMap<Messenger, NetworkAgentInfo>(); 5111 5112 private final NetworkRequest mDefaultRequest; 5113 5114 public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo, 5115 LinkProperties linkProperties, NetworkCapabilities networkCapabilities, 5116 int currentScore) { 5117 enforceConnectivityInternalPermission(); 5118 5119 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), nextNetId(), 5120 new NetworkInfo(networkInfo), new LinkProperties(linkProperties), 5121 new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler); 5122 5123 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai)); 5124 } 5125 5126 private void handleRegisterNetworkAgent(NetworkAgentInfo na) { 5127 if (VDBG) log("Got NetworkAgent Messenger"); 5128 mNetworkAgentInfos.put(na.messenger, na); 5129 try { 5130 mNetworkAgentInfoForType[na.networkInfo.getType()].add(na); 5131 } catch (NullPointerException e) { 5132 loge("registered NetworkAgent for unsupported type: " + na); 5133 } 5134 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger); 5135 NetworkInfo networkInfo = na.networkInfo; 5136 na.networkInfo = null; 5137 updateNetworkInfo(na, networkInfo); 5138 } 5139 5140 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) { 5141 LinkProperties newLp = networkAgent.linkProperties; 5142 int netId = networkAgent.network.netId; 5143 5144 updateInterfaces(newLp, oldLp, netId); 5145 updateMtu(newLp, oldLp); 5146 // TODO - figure out what to do for clat 5147// for (LinkProperties lp : newLp.getStackedLinks()) { 5148// updateMtu(lp, null); 5149// } 5150 updateRoutes(newLp, oldLp, netId); 5151 updateDnses(newLp, oldLp, netId); 5152 updateClat(newLp, oldLp, networkAgent); 5153 } 5154 5155 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) { 5156 // Update 464xlat state. 5157 if (mClat.requiresClat(na)) { 5158 5159 // If the connection was previously using clat, but is not using it now, stop the clat 5160 // daemon. Normally, this happens automatically when the connection disconnects, but if 5161 // the disconnect is not reported, or if the connection's LinkProperties changed for 5162 // some other reason (e.g., handoff changes the IP addresses on the link), it would 5163 // still be running. If it's not running, then stopping it is a no-op. 5164 if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) { 5165 mClat.stopClat(); 5166 } 5167 // If the link requires clat to be running, then start the daemon now. 5168 if (newLp != null && na.networkInfo.isConnected()) { 5169 mClat.startClat(na); 5170 } else { 5171 mClat.stopClat(); 5172 } 5173 } 5174 } 5175 5176 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) { 5177 CompareResult<String> interfaceDiff = new CompareResult<String>(); 5178 if (oldLp != null) { 5179 interfaceDiff = oldLp.compareAllInterfaceNames(newLp); 5180 } else if (newLp != null) { 5181 interfaceDiff.added = newLp.getAllInterfaceNames(); 5182 } 5183 for (String iface : interfaceDiff.added) { 5184 try { 5185 mNetd.addInterfaceToNetwork(iface, netId); 5186 } catch (Exception e) { 5187 loge("Exception adding interface: " + e); 5188 } 5189 } 5190 for (String iface : interfaceDiff.removed) { 5191 try { 5192 mNetd.removeInterfaceFromNetwork(iface, netId); 5193 } catch (Exception e) { 5194 loge("Exception removing interface: " + e); 5195 } 5196 } 5197 } 5198 5199 private void updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) { 5200 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 5201 if (oldLp != null) { 5202 routeDiff = oldLp.compareAllRoutes(newLp); 5203 } else if (newLp != null) { 5204 routeDiff.added = newLp.getAllRoutes(); 5205 } 5206 5207 // add routes before removing old in case it helps with continuous connectivity 5208 5209 // do this twice, adding non-nexthop routes first, then routes they are dependent on 5210 for (RouteInfo route : routeDiff.added) { 5211 if (route.hasGateway()) continue; 5212 try { 5213 mNetd.addRoute(netId, route); 5214 } catch (Exception e) { 5215 loge("Exception in addRoute for non-gateway: " + e); 5216 } 5217 } 5218 for (RouteInfo route : routeDiff.added) { 5219 if (route.hasGateway() == false) continue; 5220 try { 5221 mNetd.addRoute(netId, route); 5222 } catch (Exception e) { 5223 loge("Exception in addRoute for gateway: " + e); 5224 } 5225 } 5226 5227 for (RouteInfo route : routeDiff.removed) { 5228 try { 5229 mNetd.removeRoute(netId, route); 5230 } catch (Exception e) { 5231 loge("Exception in removeRoute: " + e); 5232 } 5233 } 5234 } 5235 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) { 5236 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) { 5237 Collection<InetAddress> dnses = newLp.getDnses(); 5238 if (dnses.size() == 0 && mDefaultDns != null) { 5239 dnses = new ArrayList(); 5240 dnses.add(mDefaultDns); 5241 if (DBG) { 5242 loge("no dns provided for netId " + netId + ", so using defaults"); 5243 } 5244 } 5245 try { 5246 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), 5247 newLp.getDomains()); 5248 } catch (Exception e) { 5249 loge("Exception in setDnsServersForNetwork: " + e); 5250 } 5251 // TODO - setprop "net.dnsX" 5252 } 5253 } 5254 5255 private void updateCapabilities(NetworkAgentInfo networkAgent, 5256 NetworkCapabilities networkCapabilities) { 5257 // TODO - what else here? Verify still satisfies everybody? 5258 // Check if satisfies somebody new? call callbacks? 5259 networkAgent.networkCapabilities = networkCapabilities; 5260 } 5261 5262 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) { 5263 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString()); 5264 for (AsyncChannel ac : mNetworkFactories) { 5265 ac.sendMessage(NetworkFactoryProtocol.CMD_REQUEST_NETWORK, score, 0, networkRequest); 5266 } 5267 } 5268 5269 private void callCallbackForRequest(NetworkRequest networkRequest, 5270 NetworkAgentInfo networkAgent, int notificationType) { 5271 // TODO 5272 } 5273 5274 private void handleLingerComplete(NetworkAgentInfo oldNetwork) { 5275 if (oldNetwork == null) { 5276 loge("Unknown NetworkAgentInfo in handleLingerComplete"); 5277 return; 5278 } 5279 if (DBG) log("handleLingerComplete for " + oldNetwork.name()); 5280 if (DBG) { 5281 if (oldNetwork.networkRequests.size() != 0) { 5282 loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests"); 5283 } 5284 } 5285 oldNetwork.asyncChannel.disconnect(); 5286 } 5287 5288 private void handleConnectionValidated(NetworkAgentInfo newNetwork) { 5289 if (newNetwork == null) { 5290 loge("Unknown NetworkAgentInfo in handleConnectionValidated"); 5291 return; 5292 } 5293 boolean keep = false; 5294 boolean isNewDefault = false; 5295 if (DBG) log("handleConnectionValidated for "+newNetwork.name()); 5296 // check if any NetworkRequest wants this NetworkAgent 5297 // first check if it satisfies the NetworkCapabilities 5298 for (int i = 0; i < mNetworkRequests.size(); i++) { 5299 NetworkRequest nr = mNetworkRequests.valueAt(i); 5300 if (nr.networkCapabilities.satisfiedByNetworkCapabilities( 5301 newNetwork.networkCapabilities)) { 5302 // next check if it's better than any current network we're using for 5303 // this request 5304 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nr.requestId); 5305 if (VDBG) { 5306 log("currentScore = " + 5307 (currentNetwork != null ? currentNetwork.currentScore : 0) + 5308 ", newScore = " + newNetwork.currentScore); 5309 } 5310 if (currentNetwork == null || 5311 currentNetwork.currentScore < newNetwork.currentScore) { 5312 if (currentNetwork != null) { 5313 currentNetwork.networkRequests.remove(nr.requestId); 5314 currentNetwork.networkListens.add(nr); 5315 if (currentNetwork.networkRequests.size() == 0) { 5316 currentNetwork.networkMonitor.sendMessage( 5317 NetworkMonitor.CMD_NETWORK_LINGER); 5318 notifyNetworkCallbacks(currentNetwork, NetworkCallbacks.LOSING); 5319 } 5320 } 5321 mNetworkForRequestId.put(nr.requestId, newNetwork); 5322 newNetwork.networkRequests.put(nr.requestId, nr); 5323 keep = true; 5324 // TODO - this could get expensive if we have alot of requests for this 5325 // network. Think about if there is a way to reduce this. Push 5326 // netid->request mapping to each factory? 5327 sendUpdatedScoreToFactories(nr, newNetwork.currentScore); 5328 if (mDefaultRequest.requestId == nr.requestId) { 5329 isNewDefault = true; 5330 updateActiveDefaultNetwork(newNetwork); 5331 } 5332 } 5333 } 5334 } 5335 if (keep) { 5336 if (isNewDefault) { 5337 if (VDBG) log("Switching to new default network: " + newNetwork); 5338 setupDataActivityTracking(newNetwork); 5339 try { 5340 mNetd.setDefaultNetId(newNetwork.network.netId); 5341 } catch (Exception e) { 5342 loge("Exception setting default network :" + e); 5343 } 5344 if (newNetwork.equals(mNetworkForRequestId.get(mDefaultRequest.requestId))) { 5345 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy()); 5346 } 5347 synchronized (ConnectivityService.this) { 5348 // have a new default network, release the transition wakelock in 5349 // a second if it's held. The second pause is to allow apps 5350 // to reconnect over the new network 5351 if (mNetTransitionWakeLock.isHeld()) { 5352 mHandler.sendMessageDelayed(mHandler.obtainMessage( 5353 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 5354 mNetTransitionWakeLockSerialNumber, 0), 5355 1000); 5356 } 5357 } 5358 5359 // this will cause us to come up initially as unconnected and switching 5360 // to connected after our normal pause unless somebody reports us as 5361 // really disconnected 5362 mDefaultInetConditionPublished = 0; 5363 mDefaultConnectionSequence++; 5364 mInetConditionChangeInFlight = false; 5365 // TODO - read the tcp buffer size config string from somewhere 5366 // updateNetworkSettings(); 5367 } 5368 // notify battery stats service about this network 5369// try { 5370 // TODO 5371 //BatteryStatsService.getService().noteNetworkInterfaceType(iface, netType); 5372// } catch (RemoteException e) { } 5373 notifyNetworkCallbacks(newNetwork, NetworkCallbacks.AVAILABLE); 5374 } else if (newNetwork.networkRequests.size() == 0) { 5375 if (VDBG) log("Validated network turns out to be unwanted. Tear it down."); 5376 newNetwork.asyncChannel.disconnect(); 5377 } 5378 } 5379 5380 5381 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) { 5382 NetworkInfo.State state = newInfo.getState(); 5383 NetworkInfo oldInfo = networkAgent.networkInfo; 5384 networkAgent.networkInfo = newInfo; 5385 5386 if (oldInfo != null && oldInfo.getState() == state) { 5387 if (VDBG) log("ignoring duplicate network state non-change"); 5388 return; 5389 } 5390 if (DBG) { 5391 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " + 5392 (oldInfo == null ? "null" : oldInfo.getState()) + 5393 " to " + state); 5394 } 5395 5396 if (state == NetworkInfo.State.CONNECTED) { 5397 // TODO - check if we want it (optimization) 5398 try { 5399 mNetd.createNetwork(networkAgent.network.netId); 5400 } catch (Exception e) { 5401 loge("Error creating Network " + networkAgent.network.netId); 5402 } 5403 updateLinkProperties(networkAgent, null); 5404 notifyNetworkCallbacks(networkAgent, NetworkCallbacks.PRECHECK); 5405 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 5406 } else if (state == NetworkInfo.State.DISCONNECTED || 5407 state == NetworkInfo.State.SUSPENDED) { 5408 networkAgent.asyncChannel.disconnect(); 5409 } 5410 } 5411 5412 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) { 5413 if (VDBG) log("notifyType " + notifyType + " for " + networkAgent.name()); 5414 boolean needsBroadcasts = false; 5415 for (int i = 0; i < networkAgent.networkRequests.size(); i++) { 5416 NetworkRequest request = networkAgent.networkRequests.valueAt(i); 5417 if (request == null) continue; 5418 if (request.needsBroadcasts) needsBroadcasts = true; 5419 callCallbackForRequest(request, networkAgent, notifyType); 5420 } 5421 for (NetworkRequest request : networkAgent.networkListens) { 5422 if (request.needsBroadcasts) needsBroadcasts = true; 5423 callCallbackForRequest(request, networkAgent, notifyType); 5424 } 5425 if (needsBroadcasts) { 5426 if (notifyType == NetworkCallbacks.AVAILABLE) { 5427 sendConnectedBroadcastDelayed(networkAgent.networkInfo, 5428 getConnectivityChangeDelay()); 5429 } else if (notifyType == NetworkCallbacks.LOST) { 5430 NetworkInfo info = new NetworkInfo(networkAgent.networkInfo); 5431 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 5432 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 5433 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 5434 if (info.isFailover()) { 5435 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 5436 networkAgent.networkInfo.setFailover(false); 5437 } 5438 if (info.getReason() != null) { 5439 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 5440 } 5441 if (info.getExtraInfo() != null) { 5442 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo()); 5443 } 5444 NetworkAgentInfo newDefaultAgent = null; 5445 if (networkAgent.networkRequests.get(mDefaultRequest.requestId) != null) { 5446 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId); 5447 if (newDefaultAgent != null) { 5448 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, 5449 newDefaultAgent.networkInfo); 5450 } else { 5451 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 5452 } 5453 } 5454 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, 5455 mDefaultInetConditionPublished); 5456 final Intent immediateIntent = new Intent(intent); 5457 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE); 5458 sendStickyBroadcast(immediateIntent); 5459 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay()); 5460 if (newDefaultAgent != null) { 5461 sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo, 5462 getConnectivityChangeDelay()); 5463 } 5464 } 5465 } 5466 } 5467 5468 private LinkProperties getLinkPropertiesForType(int networkType) { 5469 ArrayList<NetworkAgentInfo> list = mNetworkAgentInfoForType[networkType]; 5470 if (list == null) return null; 5471 try { 5472 return new LinkProperties(list.get(0).linkProperties); 5473 } catch (IndexOutOfBoundsException e) { 5474 return new LinkProperties(); 5475 } 5476 } 5477 5478 private NetworkInfo getNetworkInfoForType(int networkType) { 5479 ArrayList<NetworkAgentInfo> list = mNetworkAgentInfoForType[networkType]; 5480 if (list == null) return null; 5481 try { 5482 return new NetworkInfo(list.get(0).networkInfo); 5483 } catch (IndexOutOfBoundsException e) { 5484 return new NetworkInfo(networkType, 0, "Unknown", ""); 5485 } 5486 } 5487 5488 private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) { 5489 ArrayList<NetworkAgentInfo> list = mNetworkAgentInfoForType[networkType]; 5490 if (list == null) return null; 5491 try { 5492 return new NetworkCapabilities(list.get(0).networkCapabilities); 5493 } catch (IndexOutOfBoundsException e) { 5494 return new NetworkCapabilities(); 5495 } 5496 } 5497} 5498