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