ConnectivityService.java revision 44e27b5c74b5f441973561a4f945cb58e0cc45a4
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.net.ConnectivityManager.isNetworkTypeValid; 21import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL; 22import static android.net.NetworkPolicyManager.RULE_REJECT_METERED; 23 24import android.bluetooth.BluetoothTetheringDataTracker; 25import android.content.ContentResolver; 26import android.content.Context; 27import android.content.Intent; 28import android.content.pm.PackageManager; 29import android.database.ContentObserver; 30import android.net.ConnectivityManager; 31import android.net.DummyDataStateTracker; 32import android.net.EthernetDataTracker; 33import android.net.IConnectivityManager; 34import android.net.INetworkPolicyListener; 35import android.net.INetworkPolicyManager; 36import android.net.LinkProperties; 37import android.net.MobileDataStateTracker; 38import android.net.NetworkConfig; 39import android.net.NetworkInfo; 40import android.net.NetworkInfo.DetailedState; 41import android.net.NetworkState; 42import android.net.NetworkStateTracker; 43import android.net.NetworkUtils; 44import android.net.Proxy; 45import android.net.ProxyProperties; 46import android.net.RouteInfo; 47import android.net.wifi.WifiStateTracker; 48import android.os.Binder; 49import android.os.FileUtils; 50import android.os.Handler; 51import android.os.HandlerThread; 52import android.os.IBinder; 53import android.os.INetworkManagementService; 54import android.os.Looper; 55import android.os.Message; 56import android.os.ParcelFileDescriptor; 57import android.os.PowerManager; 58import android.os.RemoteException; 59import android.os.ServiceManager; 60import android.os.SystemProperties; 61import android.provider.Settings; 62import android.text.TextUtils; 63import android.util.EventLog; 64import android.util.Slog; 65import android.util.SparseIntArray; 66 67import com.android.internal.net.VpnConfig; 68import com.android.internal.telephony.Phone; 69import com.android.server.connectivity.Tethering; 70import com.android.server.connectivity.Vpn; 71 72import com.google.android.collect.Lists; 73import com.google.android.collect.Sets; 74 75import java.io.FileDescriptor; 76import java.io.IOException; 77import java.io.PrintWriter; 78import java.net.InetAddress; 79import java.net.UnknownHostException; 80import java.util.ArrayList; 81import java.util.Arrays; 82import java.util.Collection; 83import java.util.GregorianCalendar; 84import java.util.HashSet; 85import java.util.List; 86import java.util.concurrent.atomic.AtomicBoolean; 87 88/** 89 * @hide 90 */ 91public class ConnectivityService extends IConnectivityManager.Stub { 92 93 private static final boolean DBG = true; 94 private static final String TAG = "ConnectivityService"; 95 96 private static final boolean LOGD_RULES = false; 97 98 // how long to wait before switching back to a radio's default network 99 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000; 100 // system property that can override the above value 101 private static final String NETWORK_RESTORE_DELAY_PROP_NAME = 102 "android.telephony.apn-restore"; 103 104 // used in recursive route setting to add gateways for the host for which 105 // a host route was requested. 106 private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10; 107 108 private Tethering mTethering; 109 private boolean mTetheringConfigValid = false; 110 111 private Vpn mVpn; 112 113 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */ 114 private Object mRulesLock = new Object(); 115 /** Currently active network rules by UID. */ 116 private SparseIntArray mUidRules = new SparseIntArray(); 117 /** Set of ifaces that are costly. */ 118 private HashSet<String> mMeteredIfaces = Sets.newHashSet(); 119 120 /** 121 * Sometimes we want to refer to the individual network state 122 * trackers separately, and sometimes we just want to treat them 123 * abstractly. 124 */ 125 private NetworkStateTracker mNetTrackers[]; 126 127 /** 128 * A per Net list of the PID's that requested access to the net 129 * used both as a refcount and for per-PID DNS selection 130 */ 131 private List mNetRequestersPids[]; 132 133 // priority order of the nettrackers 134 // (excluding dynamically set mNetworkPreference) 135 // TODO - move mNetworkTypePreference into this 136 private int[] mPriorityList; 137 138 private Context mContext; 139 private int mNetworkPreference; 140 private int mActiveDefaultNetwork = -1; 141 // 0 is full bad, 100 is full good 142 private int mDefaultInetCondition = 0; 143 private int mDefaultInetConditionPublished = 0; 144 private boolean mInetConditionChangeInFlight = false; 145 private int mDefaultConnectionSequence = 0; 146 147 private int mNumDnsEntries; 148 149 private boolean mTestMode; 150 private static ConnectivityService sServiceInstance; 151 152 private AtomicBoolean mBackgroundDataEnabled = new AtomicBoolean(true); 153 154 private INetworkManagementService mNetd; 155 private INetworkPolicyManager mPolicyManager; 156 157 private static final int ENABLED = 1; 158 private static final int DISABLED = 0; 159 160 // Share the event space with NetworkStateTracker (which can't see this 161 // internal class but sends us events). If you change these, change 162 // NetworkStateTracker.java too. 163 private static final int MIN_NETWORK_STATE_TRACKER_EVENT = 1; 164 private static final int MAX_NETWORK_STATE_TRACKER_EVENT = 100; 165 166 /** 167 * used internally as a delayed event to make us switch back to the 168 * default network 169 */ 170 private static final int EVENT_RESTORE_DEFAULT_NETWORK = 171 MAX_NETWORK_STATE_TRACKER_EVENT + 1; 172 173 /** 174 * used internally to change our mobile data enabled flag 175 */ 176 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 177 MAX_NETWORK_STATE_TRACKER_EVENT + 2; 178 179 /** 180 * used internally to change our network preference setting 181 * arg1 = networkType to prefer 182 */ 183 private static final int EVENT_SET_NETWORK_PREFERENCE = 184 MAX_NETWORK_STATE_TRACKER_EVENT + 3; 185 186 /** 187 * used internally to synchronize inet condition reports 188 * arg1 = networkType 189 * arg2 = condition (0 bad, 100 good) 190 */ 191 private static final int EVENT_INET_CONDITION_CHANGE = 192 MAX_NETWORK_STATE_TRACKER_EVENT + 4; 193 194 /** 195 * used internally to mark the end of inet condition hold periods 196 * arg1 = networkType 197 */ 198 private static final int EVENT_INET_CONDITION_HOLD_END = 199 MAX_NETWORK_STATE_TRACKER_EVENT + 5; 200 201 /** 202 * used internally to set the background data preference 203 * arg1 = TRUE for enabled, FALSE for disabled 204 */ 205 private static final int EVENT_SET_BACKGROUND_DATA = 206 MAX_NETWORK_STATE_TRACKER_EVENT + 6; 207 208 /** 209 * used internally to set enable/disable cellular data 210 * arg1 = ENBALED or DISABLED 211 */ 212 private static final int EVENT_SET_MOBILE_DATA = 213 MAX_NETWORK_STATE_TRACKER_EVENT + 7; 214 215 /** 216 * used internally to clear a wakelock when transitioning 217 * from one net to another 218 */ 219 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 220 MAX_NETWORK_STATE_TRACKER_EVENT + 8; 221 222 /** 223 * used internally to reload global proxy settings 224 */ 225 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 226 MAX_NETWORK_STATE_TRACKER_EVENT + 9; 227 228 /** 229 * used internally to set external dependency met/unmet 230 * arg1 = ENABLED (met) or DISABLED (unmet) 231 * arg2 = NetworkType 232 */ 233 private static final int EVENT_SET_DEPENDENCY_MET = 234 MAX_NETWORK_STATE_TRACKER_EVENT + 10; 235 236 private Handler mHandler; 237 238 // list of DeathRecipients used to make sure features are turned off when 239 // a process dies 240 private List mFeatureUsers; 241 242 private boolean mSystemReady; 243 private Intent mInitialBroadcast; 244 245 private PowerManager.WakeLock mNetTransitionWakeLock; 246 private String mNetTransitionWakeLockCausedBy = ""; 247 private int mNetTransitionWakeLockSerialNumber; 248 private int mNetTransitionWakeLockTimeout; 249 250 private InetAddress mDefaultDns; 251 252 // used in DBG mode to track inet condition reports 253 private static final int INET_CONDITION_LOG_MAX_SIZE = 15; 254 private ArrayList mInetLog; 255 256 // track the current default http proxy - tell the world if we get a new one (real change) 257 private ProxyProperties mDefaultProxy = null; 258 // track the global proxy. 259 private ProxyProperties mGlobalProxy = null; 260 private final Object mGlobalProxyLock = new Object(); 261 262 private SettingsObserver mSettingsObserver; 263 264 NetworkConfig[] mNetConfigs; 265 int mNetworksDefined; 266 267 private static class RadioAttributes { 268 public int mSimultaneity; 269 public int mType; 270 public RadioAttributes(String init) { 271 String fragments[] = init.split(","); 272 mType = Integer.parseInt(fragments[0]); 273 mSimultaneity = Integer.parseInt(fragments[1]); 274 } 275 } 276 RadioAttributes[] mRadioAttributes; 277 278 // the set of network types that can only be enabled by system/sig apps 279 List mProtectedNetworks; 280 281 public ConnectivityService( 282 Context context, INetworkManagementService netd, INetworkPolicyManager policyManager) { 283 if (DBG) log("ConnectivityService starting up"); 284 285 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread"); 286 handlerThread.start(); 287 mHandler = new MyHandler(handlerThread.getLooper()); 288 289 mBackgroundDataEnabled.set(Settings.Secure.getInt(context.getContentResolver(), 290 Settings.Secure.BACKGROUND_DATA, 1) == 1); 291 292 // setup our unique device name 293 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) { 294 String id = Settings.Secure.getString(context.getContentResolver(), 295 Settings.Secure.ANDROID_ID); 296 if (id != null && id.length() > 0) { 297 String name = new String("android_").concat(id); 298 SystemProperties.set("net.hostname", name); 299 } 300 } 301 302 // read our default dns server ip 303 String dns = Settings.Secure.getString(context.getContentResolver(), 304 Settings.Secure.DEFAULT_DNS_SERVER); 305 if (dns == null || dns.length() == 0) { 306 dns = context.getResources().getString( 307 com.android.internal.R.string.config_default_dns_server); 308 } 309 try { 310 mDefaultDns = NetworkUtils.numericToInetAddress(dns); 311 } catch (IllegalArgumentException e) { 312 loge("Error setting defaultDns using " + dns); 313 } 314 315 mContext = checkNotNull(context, "missing Context"); 316 mNetd = checkNotNull(netd, "missing INetworkManagementService"); 317 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager"); 318 319 try { 320 mPolicyManager.registerListener(mPolicyListener); 321 } catch (RemoteException e) { 322 // ouch, no rules updates means some processes may never get network 323 Slog.e(TAG, "unable to register INetworkPolicyListener", e); 324 } 325 326 final PowerManager powerManager = (PowerManager) context.getSystemService( 327 Context.POWER_SERVICE); 328 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); 329 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger( 330 com.android.internal.R.integer.config_networkTransitionTimeout); 331 332 mNetTrackers = new NetworkStateTracker[ 333 ConnectivityManager.MAX_NETWORK_TYPE+1]; 334 335 mNetworkPreference = getPersistedNetworkPreference(); 336 337 mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1]; 338 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1]; 339 340 // Load device network attributes from resources 341 String[] raStrings = context.getResources().getStringArray( 342 com.android.internal.R.array.radioAttributes); 343 for (String raString : raStrings) { 344 RadioAttributes r = new RadioAttributes(raString); 345 if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) { 346 loge("Error in radioAttributes - ignoring attempt to define type " + r.mType); 347 continue; 348 } 349 if (mRadioAttributes[r.mType] != null) { 350 loge("Error in radioAttributes - ignoring attempt to redefine type " + 351 r.mType); 352 continue; 353 } 354 mRadioAttributes[r.mType] = r; 355 } 356 357 String[] naStrings = context.getResources().getStringArray( 358 com.android.internal.R.array.networkAttributes); 359 for (String naString : naStrings) { 360 try { 361 NetworkConfig n = new NetworkConfig(naString); 362 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) { 363 loge("Error in networkAttributes - ignoring attempt to define type " + 364 n.type); 365 continue; 366 } 367 if (mNetConfigs[n.type] != null) { 368 loge("Error in networkAttributes - ignoring attempt to redefine type " + 369 n.type); 370 continue; 371 } 372 if (mRadioAttributes[n.radio] == null) { 373 loge("Error in networkAttributes - ignoring attempt to use undefined " + 374 "radio " + n.radio + " in network type " + n.type); 375 continue; 376 } 377 mNetConfigs[n.type] = n; 378 mNetworksDefined++; 379 } catch(Exception e) { 380 // ignore it - leave the entry null 381 } 382 } 383 384 mProtectedNetworks = new ArrayList<Integer>(); 385 int[] protectedNetworks = context.getResources().getIntArray( 386 com.android.internal.R.array.config_protectedNetworks); 387 for (int p : protectedNetworks) { 388 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) { 389 mProtectedNetworks.add(p); 390 } else { 391 if (DBG) loge("Ignoring protectedNetwork " + p); 392 } 393 } 394 395 // high priority first 396 mPriorityList = new int[mNetworksDefined]; 397 { 398 int insertionPoint = mNetworksDefined-1; 399 int currentLowest = 0; 400 int nextLowest = 0; 401 while (insertionPoint > -1) { 402 for (NetworkConfig na : mNetConfigs) { 403 if (na == null) continue; 404 if (na.priority < currentLowest) continue; 405 if (na.priority > currentLowest) { 406 if (na.priority < nextLowest || nextLowest == 0) { 407 nextLowest = na.priority; 408 } 409 continue; 410 } 411 mPriorityList[insertionPoint--] = na.type; 412 } 413 currentLowest = nextLowest; 414 nextLowest = 0; 415 } 416 } 417 418 mNetRequestersPids = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1]; 419 for (int i : mPriorityList) { 420 mNetRequestersPids[i] = new ArrayList(); 421 } 422 423 mFeatureUsers = new ArrayList(); 424 425 mNumDnsEntries = 0; 426 427 mTestMode = SystemProperties.get("cm.test.mode").equals("true") 428 && SystemProperties.get("ro.build.type").equals("eng"); 429 /* 430 * Create the network state trackers for Wi-Fi and mobile 431 * data. Maybe this could be done with a factory class, 432 * but it's not clear that it's worth it, given that 433 * the number of different network types is not going 434 * to change very often. 435 */ 436 for (int netType : mPriorityList) { 437 switch (mNetConfigs[netType].radio) { 438 case ConnectivityManager.TYPE_WIFI: 439 if (DBG) log("Starting Wifi Service."); 440 WifiStateTracker wst = new WifiStateTracker(); 441 WifiService wifiService = new WifiService(context); 442 ServiceManager.addService(Context.WIFI_SERVICE, wifiService); 443 wifiService.checkAndStartWifi(); 444 mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst; 445 wst.startMonitoring(context, mHandler); 446 break; 447 case ConnectivityManager.TYPE_MOBILE: 448 mNetTrackers[netType] = new MobileDataStateTracker(netType, 449 mNetConfigs[netType].name); 450 mNetTrackers[netType].startMonitoring(context, mHandler); 451 break; 452 case ConnectivityManager.TYPE_DUMMY: 453 mNetTrackers[netType] = new DummyDataStateTracker(netType, 454 mNetConfigs[netType].name); 455 mNetTrackers[netType].startMonitoring(context, mHandler); 456 break; 457 case ConnectivityManager.TYPE_BLUETOOTH: 458 mNetTrackers[netType] = BluetoothTetheringDataTracker.getInstance(); 459 mNetTrackers[netType].startMonitoring(context, mHandler); 460 break; 461 case ConnectivityManager.TYPE_ETHERNET: 462 mNetTrackers[netType] = EthernetDataTracker.getInstance(); 463 mNetTrackers[netType].startMonitoring(context, mHandler); 464 break; 465 default: 466 loge("Trying to create a DataStateTracker for an unknown radio type " + 467 mNetConfigs[netType].radio); 468 continue; 469 } 470 } 471 472 IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE); 473 INetworkManagementService nmService = INetworkManagementService.Stub.asInterface(b); 474 475 mTethering = new Tethering(mContext, nmService, mHandler.getLooper()); 476 mTetheringConfigValid = ((mTethering.getTetherableUsbRegexs().length != 0 || 477 mTethering.getTetherableWifiRegexs().length != 0 || 478 mTethering.getTetherableBluetoothRegexs().length != 0) && 479 mTethering.getUpstreamIfaceTypes().length != 0); 480 481 mVpn = new Vpn(mContext, new VpnCallback()); 482 483 try { 484 nmService.registerObserver(mTethering); 485 nmService.registerObserver(mVpn); 486 } catch (RemoteException e) { 487 loge("Error registering observer :" + e); 488 } 489 490 if (DBG) { 491 mInetLog = new ArrayList(); 492 } 493 494 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY); 495 mSettingsObserver.observe(mContext); 496 497 loadGlobalProxy(); 498 } 499 500 /** 501 * Sets the preferred network. 502 * @param preference the new preference 503 */ 504 public void setNetworkPreference(int preference) { 505 enforceChangePermission(); 506 507 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0)); 508 } 509 510 public int getNetworkPreference() { 511 enforceAccessPermission(); 512 int preference; 513 synchronized(this) { 514 preference = mNetworkPreference; 515 } 516 return preference; 517 } 518 519 private void handleSetNetworkPreference(int preference) { 520 if (ConnectivityManager.isNetworkTypeValid(preference) && 521 mNetConfigs[preference] != null && 522 mNetConfigs[preference].isDefault()) { 523 if (mNetworkPreference != preference) { 524 final ContentResolver cr = mContext.getContentResolver(); 525 Settings.Secure.putInt(cr, Settings.Secure.NETWORK_PREFERENCE, preference); 526 synchronized(this) { 527 mNetworkPreference = preference; 528 } 529 enforcePreference(); 530 } 531 } 532 } 533 534 private int getPersistedNetworkPreference() { 535 final ContentResolver cr = mContext.getContentResolver(); 536 537 final int networkPrefSetting = Settings.Secure 538 .getInt(cr, Settings.Secure.NETWORK_PREFERENCE, -1); 539 if (networkPrefSetting != -1) { 540 return networkPrefSetting; 541 } 542 543 return ConnectivityManager.DEFAULT_NETWORK_PREFERENCE; 544 } 545 546 /** 547 * Make the state of network connectivity conform to the preference settings 548 * In this method, we only tear down a non-preferred network. Establishing 549 * a connection to the preferred network is taken care of when we handle 550 * the disconnect event from the non-preferred network 551 * (see {@link #handleDisconnect(NetworkInfo)}). 552 */ 553 private void enforcePreference() { 554 if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected()) 555 return; 556 557 if (!mNetTrackers[mNetworkPreference].isAvailable()) 558 return; 559 560 for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) { 561 if (t != mNetworkPreference && mNetTrackers[t] != null && 562 mNetTrackers[t].getNetworkInfo().isConnected()) { 563 if (DBG) { 564 log("tearing down " + mNetTrackers[t].getNetworkInfo() + 565 " in enforcePreference"); 566 } 567 teardown(mNetTrackers[t]); 568 } 569 } 570 } 571 572 private boolean teardown(NetworkStateTracker netTracker) { 573 if (netTracker.teardown()) { 574 netTracker.setTeardownRequested(true); 575 return true; 576 } else { 577 return false; 578 } 579 } 580 581 /** 582 * Check if UID should be blocked from using the network represented by the 583 * given {@link NetworkStateTracker}. 584 */ 585 private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) { 586 final String iface = tracker.getLinkProperties().getInterfaceName(); 587 588 final boolean networkCostly; 589 final int uidRules; 590 synchronized (mRulesLock) { 591 networkCostly = mMeteredIfaces.contains(iface); 592 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL); 593 } 594 595 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) { 596 return true; 597 } 598 599 // no restrictive rules; network is visible 600 return false; 601 } 602 603 /** 604 * Return a filtered {@link NetworkInfo}, potentially marked 605 * {@link DetailedState#BLOCKED} based on 606 * {@link #isNetworkBlocked(NetworkStateTracker, int)}. 607 */ 608 private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) { 609 NetworkInfo info = tracker.getNetworkInfo(); 610 if (isNetworkBlocked(tracker, uid)) { 611 // network is blocked; clone and override state 612 info = new NetworkInfo(info); 613 info.setDetailedState(DetailedState.BLOCKED, null, null); 614 } 615 return info; 616 } 617 618 /** 619 * Return NetworkInfo for the active (i.e., connected) network interface. 620 * It is assumed that at most one network is active at a time. If more 621 * than one is active, it is indeterminate which will be returned. 622 * @return the info for the active network, or {@code null} if none is 623 * active 624 */ 625 @Override 626 public NetworkInfo getActiveNetworkInfo() { 627 enforceAccessPermission(); 628 final int uid = Binder.getCallingUid(); 629 return getNetworkInfo(mActiveDefaultNetwork, uid); 630 } 631 632 @Override 633 public NetworkInfo getActiveNetworkInfoForUid(int uid) { 634 enforceConnectivityInternalPermission(); 635 return getNetworkInfo(mActiveDefaultNetwork, uid); 636 } 637 638 @Override 639 public NetworkInfo getNetworkInfo(int networkType) { 640 enforceAccessPermission(); 641 final int uid = Binder.getCallingUid(); 642 return getNetworkInfo(networkType, uid); 643 } 644 645 private NetworkInfo getNetworkInfo(int networkType, int uid) { 646 NetworkInfo info = null; 647 if (isNetworkTypeValid(networkType)) { 648 final NetworkStateTracker tracker = mNetTrackers[networkType]; 649 if (tracker != null) { 650 info = getFilteredNetworkInfo(tracker, uid); 651 } 652 } 653 return info; 654 } 655 656 @Override 657 public NetworkInfo[] getAllNetworkInfo() { 658 enforceAccessPermission(); 659 final int uid = Binder.getCallingUid(); 660 final ArrayList<NetworkInfo> result = Lists.newArrayList(); 661 synchronized (mRulesLock) { 662 for (NetworkStateTracker tracker : mNetTrackers) { 663 if (tracker != null) { 664 result.add(getFilteredNetworkInfo(tracker, uid)); 665 } 666 } 667 } 668 return result.toArray(new NetworkInfo[result.size()]); 669 } 670 671 /** 672 * Return LinkProperties for the active (i.e., connected) default 673 * network interface. It is assumed that at most one default network 674 * is active at a time. If more than one is active, it is indeterminate 675 * which will be returned. 676 * @return the ip properties for the active network, or {@code null} if 677 * none is active 678 */ 679 @Override 680 public LinkProperties getActiveLinkProperties() { 681 return getLinkProperties(mActiveDefaultNetwork); 682 } 683 684 @Override 685 public LinkProperties getLinkProperties(int networkType) { 686 enforceAccessPermission(); 687 if (isNetworkTypeValid(networkType)) { 688 final NetworkStateTracker tracker = mNetTrackers[networkType]; 689 if (tracker != null) { 690 return tracker.getLinkProperties(); 691 } 692 } 693 return null; 694 } 695 696 @Override 697 public NetworkState[] getAllNetworkState() { 698 enforceAccessPermission(); 699 final int uid = Binder.getCallingUid(); 700 final ArrayList<NetworkState> result = Lists.newArrayList(); 701 synchronized (mRulesLock) { 702 for (NetworkStateTracker tracker : mNetTrackers) { 703 if (tracker != null) { 704 final NetworkInfo info = getFilteredNetworkInfo(tracker, uid); 705 result.add(new NetworkState( 706 info, tracker.getLinkProperties(), tracker.getLinkCapabilities())); 707 } 708 } 709 } 710 return result.toArray(new NetworkState[result.size()]); 711 } 712 713 public boolean setRadios(boolean turnOn) { 714 boolean result = true; 715 enforceChangePermission(); 716 for (NetworkStateTracker t : mNetTrackers) { 717 if (t != null) result = t.setRadio(turnOn) && result; 718 } 719 return result; 720 } 721 722 public boolean setRadio(int netType, boolean turnOn) { 723 enforceChangePermission(); 724 if (!ConnectivityManager.isNetworkTypeValid(netType)) { 725 return false; 726 } 727 NetworkStateTracker tracker = mNetTrackers[netType]; 728 return tracker != null && tracker.setRadio(turnOn); 729 } 730 731 /** 732 * Used to notice when the calling process dies so we can self-expire 733 * 734 * Also used to know if the process has cleaned up after itself when 735 * our auto-expire timer goes off. The timer has a link to an object. 736 * 737 */ 738 private class FeatureUser implements IBinder.DeathRecipient { 739 int mNetworkType; 740 String mFeature; 741 IBinder mBinder; 742 int mPid; 743 int mUid; 744 long mCreateTime; 745 746 FeatureUser(int type, String feature, IBinder binder) { 747 super(); 748 mNetworkType = type; 749 mFeature = feature; 750 mBinder = binder; 751 mPid = getCallingPid(); 752 mUid = getCallingUid(); 753 mCreateTime = System.currentTimeMillis(); 754 755 try { 756 mBinder.linkToDeath(this, 0); 757 } catch (RemoteException e) { 758 binderDied(); 759 } 760 } 761 762 void unlinkDeathRecipient() { 763 mBinder.unlinkToDeath(this, 0); 764 } 765 766 public void binderDied() { 767 log("ConnectivityService FeatureUser binderDied(" + 768 mNetworkType + ", " + mFeature + ", " + mBinder + "), created " + 769 (System.currentTimeMillis() - mCreateTime) + " mSec ago"); 770 stopUsingNetworkFeature(this, false); 771 } 772 773 public void expire() { 774 log("ConnectivityService FeatureUser expire(" + 775 mNetworkType + ", " + mFeature + ", " + mBinder +"), created " + 776 (System.currentTimeMillis() - mCreateTime) + " mSec ago"); 777 stopUsingNetworkFeature(this, false); 778 } 779 780 public String toString() { 781 return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " + 782 (System.currentTimeMillis() - mCreateTime) + " mSec ago"; 783 } 784 } 785 786 // javadoc from interface 787 public int startUsingNetworkFeature(int networkType, String feature, 788 IBinder binder) { 789 if (DBG) { 790 log("startUsingNetworkFeature for net " + networkType + ": " + feature); 791 } 792 enforceChangePermission(); 793 if (!ConnectivityManager.isNetworkTypeValid(networkType) || 794 mNetConfigs[networkType] == null) { 795 return Phone.APN_REQUEST_FAILED; 796 } 797 798 FeatureUser f = new FeatureUser(networkType, feature, binder); 799 800 // TODO - move this into the MobileDataStateTracker 801 int usedNetworkType = networkType; 802 if(networkType == ConnectivityManager.TYPE_MOBILE) { 803 usedNetworkType = convertFeatureToNetworkType(feature); 804 if (usedNetworkType < 0) { 805 Slog.e(TAG, "Can't match any netTracker!"); 806 usedNetworkType = networkType; 807 } 808 } 809 810 if (mProtectedNetworks.contains(usedNetworkType)) { 811 enforceConnectivityInternalPermission(); 812 } 813 814 NetworkStateTracker network = mNetTrackers[usedNetworkType]; 815 if (network != null) { 816 Integer currentPid = new Integer(getCallingPid()); 817 if (usedNetworkType != networkType) { 818 NetworkStateTracker radio = mNetTrackers[networkType]; 819 NetworkInfo ni = network.getNetworkInfo(); 820 821 if (ni.isAvailable() == false) { 822 if (DBG) log("special network not available"); 823 if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) { 824 return Phone.APN_TYPE_NOT_AVAILABLE; 825 } else { 826 // else make the attempt anyway - probably giving REQUEST_STARTED below 827 } 828 } 829 830 synchronized(this) { 831 mFeatureUsers.add(f); 832 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) { 833 // this gets used for per-pid dns when connected 834 mNetRequestersPids[usedNetworkType].add(currentPid); 835 } 836 } 837 838 int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType); 839 840 if (restoreTimer >= 0) { 841 mHandler.sendMessageDelayed( 842 mHandler.obtainMessage(EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer); 843 } 844 845 if ((ni.isConnectedOrConnecting() == true) && 846 !network.isTeardownRequested()) { 847 if (ni.isConnected() == true) { 848 // add the pid-specific dns 849 handleDnsConfigurationChange(networkType); 850 if (DBG) log("special network already active"); 851 return Phone.APN_ALREADY_ACTIVE; 852 } 853 if (DBG) log("special network already connecting"); 854 return Phone.APN_REQUEST_STARTED; 855 } 856 857 // check if the radio in play can make another contact 858 // assume if cannot for now 859 860 if (DBG) log("reconnecting to special network"); 861 network.reconnect(); 862 return Phone.APN_REQUEST_STARTED; 863 } else { 864 // need to remember this unsupported request so we respond appropriately on stop 865 synchronized(this) { 866 mFeatureUsers.add(f); 867 if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) { 868 // this gets used for per-pid dns when connected 869 mNetRequestersPids[usedNetworkType].add(currentPid); 870 } 871 } 872 return -1; 873 } 874 } 875 return Phone.APN_TYPE_NOT_AVAILABLE; 876 } 877 878 // javadoc from interface 879 public int stopUsingNetworkFeature(int networkType, String feature) { 880 enforceChangePermission(); 881 882 int pid = getCallingPid(); 883 int uid = getCallingUid(); 884 885 FeatureUser u = null; 886 boolean found = false; 887 888 synchronized(this) { 889 for (int i = 0; i < mFeatureUsers.size() ; i++) { 890 u = (FeatureUser)mFeatureUsers.get(i); 891 if (uid == u.mUid && pid == u.mPid && 892 networkType == u.mNetworkType && 893 TextUtils.equals(feature, u.mFeature)) { 894 found = true; 895 break; 896 } 897 } 898 } 899 if (found && u != null) { 900 // stop regardless of how many other time this proc had called start 901 return stopUsingNetworkFeature(u, true); 902 } else { 903 // none found! 904 if (DBG) log("ignoring stopUsingNetworkFeature - not a live request"); 905 return 1; 906 } 907 } 908 909 private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) { 910 int networkType = u.mNetworkType; 911 String feature = u.mFeature; 912 int pid = u.mPid; 913 int uid = u.mUid; 914 915 NetworkStateTracker tracker = null; 916 boolean callTeardown = false; // used to carry our decision outside of sync block 917 918 if (DBG) { 919 log("stopUsingNetworkFeature for net " + networkType + 920 ": " + feature); 921 } 922 923 if (!ConnectivityManager.isNetworkTypeValid(networkType)) { 924 return -1; 925 } 926 927 // need to link the mFeatureUsers list with the mNetRequestersPids state in this 928 // sync block 929 synchronized(this) { 930 // check if this process still has an outstanding start request 931 if (!mFeatureUsers.contains(u)) { 932 if (DBG) log("ignoring - this process has no outstanding requests"); 933 return 1; 934 } 935 u.unlinkDeathRecipient(); 936 mFeatureUsers.remove(mFeatureUsers.indexOf(u)); 937 // If we care about duplicate requests, check for that here. 938 // 939 // This is done to support the extension of a request - the app 940 // can request we start the network feature again and renew the 941 // auto-shutoff delay. Normal "stop" calls from the app though 942 // do not pay attention to duplicate requests - in effect the 943 // API does not refcount and a single stop will counter multiple starts. 944 if (ignoreDups == false) { 945 for (int i = 0; i < mFeatureUsers.size() ; i++) { 946 FeatureUser x = (FeatureUser)mFeatureUsers.get(i); 947 if (x.mUid == u.mUid && x.mPid == u.mPid && 948 x.mNetworkType == u.mNetworkType && 949 TextUtils.equals(x.mFeature, u.mFeature)) { 950 if (DBG) log("ignoring stopUsingNetworkFeature as dup is found"); 951 return 1; 952 } 953 } 954 } 955 956 // TODO - move to MobileDataStateTracker 957 int usedNetworkType = networkType; 958 if (networkType == ConnectivityManager.TYPE_MOBILE) { 959 usedNetworkType = convertFeatureToNetworkType(feature); 960 if (usedNetworkType < 0) { 961 usedNetworkType = networkType; 962 } 963 } 964 tracker = mNetTrackers[usedNetworkType]; 965 if (tracker == null) { 966 if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType); 967 return -1; 968 } 969 if (usedNetworkType != networkType) { 970 Integer currentPid = new Integer(pid); 971 mNetRequestersPids[usedNetworkType].remove(currentPid); 972 reassessPidDns(pid, true); 973 if (mNetRequestersPids[usedNetworkType].size() != 0) { 974 if (DBG) log("not tearing down special network - " + 975 "others still using it"); 976 return 1; 977 } 978 callTeardown = true; 979 } else { 980 if (DBG) log("not a known feature - dropping"); 981 } 982 } 983 if (DBG) log("Doing network teardown"); 984 if (callTeardown) { 985 tracker.teardown(); 986 return 1; 987 } else { 988 return -1; 989 } 990 } 991 992 /** 993 * @deprecated use requestRouteToHostAddress instead 994 * 995 * Ensure that a network route exists to deliver traffic to the specified 996 * host via the specified network interface. 997 * @param networkType the type of the network over which traffic to the 998 * specified host is to be routed 999 * @param hostAddress the IP address of the host to which the route is 1000 * desired 1001 * @return {@code true} on success, {@code false} on failure 1002 */ 1003 public boolean requestRouteToHost(int networkType, int hostAddress) { 1004 InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress); 1005 1006 if (inetAddress == null) { 1007 return false; 1008 } 1009 1010 return requestRouteToHostAddress(networkType, inetAddress.getAddress()); 1011 } 1012 1013 /** 1014 * Ensure that a network route exists to deliver traffic to the specified 1015 * host via the specified network interface. 1016 * @param networkType the type of the network over which traffic to the 1017 * specified host is to be routed 1018 * @param hostAddress the IP address of the host to which the route is 1019 * desired 1020 * @return {@code true} on success, {@code false} on failure 1021 */ 1022 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) { 1023 enforceChangePermission(); 1024 if (mProtectedNetworks.contains(networkType)) { 1025 enforceConnectivityInternalPermission(); 1026 } 1027 1028 if (!ConnectivityManager.isNetworkTypeValid(networkType)) { 1029 return false; 1030 } 1031 NetworkStateTracker tracker = mNetTrackers[networkType]; 1032 1033 if (tracker == null || !tracker.getNetworkInfo().isConnected() || 1034 tracker.isTeardownRequested()) { 1035 if (DBG) { 1036 log("requestRouteToHostAddress on down network " + 1037 "(" + networkType + ") - dropped"); 1038 } 1039 return false; 1040 } 1041 try { 1042 InetAddress addr = InetAddress.getByAddress(hostAddress); 1043 return addHostRoute(tracker, addr, 0); 1044 } catch (UnknownHostException e) {} 1045 return false; 1046 } 1047 1048 /** 1049 * Ensure that a network route exists to deliver traffic to the specified 1050 * host via the mobile data network. 1051 * @param hostAddress the IP address of the host to which the route is desired, 1052 * in network byte order. 1053 * TODO - deprecate 1054 * @return {@code true} on success, {@code false} on failure 1055 */ 1056 private boolean addHostRoute(NetworkStateTracker nt, InetAddress hostAddress, int cycleCount) { 1057 LinkProperties lp = nt.getLinkProperties(); 1058 if ((lp == null) || (hostAddress == null)) return false; 1059 1060 String interfaceName = lp.getInterfaceName(); 1061 if (DBG) { 1062 log("Requested host route to " + hostAddress + "(" + interfaceName + "), cycleCount=" + 1063 cycleCount); 1064 } 1065 if (interfaceName == null) { 1066 if (DBG) loge("addHostRoute failed due to null interface name"); 1067 return false; 1068 } 1069 1070 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getRoutes(), hostAddress); 1071 InetAddress gatewayAddress = null; 1072 if (bestRoute != null) { 1073 gatewayAddress = bestRoute.getGateway(); 1074 // if the best route is ourself, don't relf-reference, just add the host route 1075 if (hostAddress.equals(gatewayAddress)) gatewayAddress = null; 1076 } 1077 if (gatewayAddress != null) { 1078 if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) { 1079 loge("Error adding hostroute - too much recursion"); 1080 return false; 1081 } 1082 if (!addHostRoute(nt, gatewayAddress, cycleCount+1)) return false; 1083 } 1084 1085 RouteInfo route = RouteInfo.makeHostRoute(hostAddress, gatewayAddress); 1086 1087 try { 1088 mNetd.addRoute(interfaceName, route); 1089 return true; 1090 } catch (Exception ex) { 1091 return false; 1092 } 1093 } 1094 1095 // TODO support the removal of single host routes. Keep a ref count of them so we 1096 // aren't over-zealous 1097 private boolean removeHostRoute(NetworkStateTracker nt, InetAddress hostAddress) { 1098 return false; 1099 } 1100 1101 /** 1102 * @see ConnectivityManager#getBackgroundDataSetting() 1103 */ 1104 public boolean getBackgroundDataSetting() { 1105 return mBackgroundDataEnabled.get(); 1106 } 1107 1108 /** 1109 * @see ConnectivityManager#setBackgroundDataSetting(boolean) 1110 */ 1111 public void setBackgroundDataSetting(boolean allowBackgroundDataUsage) { 1112 mContext.enforceCallingOrSelfPermission( 1113 android.Manifest.permission.CHANGE_BACKGROUND_DATA_SETTING, 1114 "ConnectivityService"); 1115 1116 mBackgroundDataEnabled.set(allowBackgroundDataUsage); 1117 1118 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_BACKGROUND_DATA, 1119 (allowBackgroundDataUsage ? ENABLED : DISABLED), 0)); 1120 } 1121 1122 private void handleSetBackgroundData(boolean enabled) { 1123 Settings.Secure.putInt(mContext.getContentResolver(), 1124 Settings.Secure.BACKGROUND_DATA, enabled ? 1 : 0); 1125 Intent broadcast = new Intent( 1126 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED); 1127 mContext.sendBroadcast(broadcast); 1128 } 1129 1130 /** 1131 * @see ConnectivityManager#getMobileDataEnabled() 1132 */ 1133 public boolean getMobileDataEnabled() { 1134 // TODO: This detail should probably be in DataConnectionTracker's 1135 // which is where we store the value and maybe make this 1136 // asynchronous. 1137 enforceAccessPermission(); 1138 boolean retVal = Settings.Secure.getInt(mContext.getContentResolver(), 1139 Settings.Secure.MOBILE_DATA, 1) == 1; 1140 if (DBG) log("getMobileDataEnabled returning " + retVal); 1141 return retVal; 1142 } 1143 1144 public void setDataDependency(int networkType, boolean met) { 1145 enforceConnectivityInternalPermission(); 1146 1147 if (DBG) { 1148 log("setDataDependency(" + networkType + ", " + met + ")"); 1149 } 1150 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET, 1151 (met ? ENABLED : DISABLED), networkType)); 1152 } 1153 1154 private void handleSetDependencyMet(int networkType, boolean met) { 1155 if (mNetTrackers[networkType] != null) { 1156 if (DBG) { 1157 log("handleSetDependencyMet(" + networkType + ", " + met + ")"); 1158 } 1159 mNetTrackers[networkType].setDependencyMet(met); 1160 } 1161 } 1162 1163 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() { 1164 @Override 1165 public void onUidRulesChanged(int uid, int uidRules) { 1166 // only someone like NPMS should only be calling us 1167 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG); 1168 1169 if (LOGD_RULES) { 1170 Slog.d(TAG, "onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")"); 1171 } 1172 1173 synchronized (mRulesLock) { 1174 // skip update when we've already applied rules 1175 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL); 1176 if (oldRules == uidRules) return; 1177 1178 mUidRules.put(uid, uidRules); 1179 } 1180 1181 // TODO: dispatch into NMS to push rules towards kernel module 1182 // TODO: notify UID when it has requested targeted updates 1183 } 1184 1185 @Override 1186 public void onMeteredIfacesChanged(String[] meteredIfaces) { 1187 // only someone like NPMS should only be calling us 1188 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG); 1189 1190 if (LOGD_RULES) { 1191 Slog.d(TAG, 1192 "onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")"); 1193 } 1194 1195 synchronized (mRulesLock) { 1196 mMeteredIfaces.clear(); 1197 for (String iface : meteredIfaces) { 1198 mMeteredIfaces.add(iface); 1199 } 1200 } 1201 } 1202 }; 1203 1204 /** 1205 * @see ConnectivityManager#setMobileDataEnabled(boolean) 1206 */ 1207 public void setMobileDataEnabled(boolean enabled) { 1208 enforceChangePermission(); 1209 if (DBG) log("setMobileDataEnabled(" + enabled + ")"); 1210 1211 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA, 1212 (enabled ? ENABLED : DISABLED), 0)); 1213 } 1214 1215 private void handleSetMobileData(boolean enabled) { 1216 if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) { 1217 if (DBG) { 1218 Slog.d(TAG, mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled); 1219 } 1220 mNetTrackers[ConnectivityManager.TYPE_MOBILE].setDataEnable(enabled); 1221 } 1222 } 1223 1224 private void enforceAccessPermission() { 1225 mContext.enforceCallingOrSelfPermission( 1226 android.Manifest.permission.ACCESS_NETWORK_STATE, 1227 "ConnectivityService"); 1228 } 1229 1230 private void enforceChangePermission() { 1231 mContext.enforceCallingOrSelfPermission( 1232 android.Manifest.permission.CHANGE_NETWORK_STATE, 1233 "ConnectivityService"); 1234 } 1235 1236 // TODO Make this a special check when it goes public 1237 private void enforceTetherChangePermission() { 1238 mContext.enforceCallingOrSelfPermission( 1239 android.Manifest.permission.CHANGE_NETWORK_STATE, 1240 "ConnectivityService"); 1241 } 1242 1243 private void enforceTetherAccessPermission() { 1244 mContext.enforceCallingOrSelfPermission( 1245 android.Manifest.permission.ACCESS_NETWORK_STATE, 1246 "ConnectivityService"); 1247 } 1248 1249 private void enforceConnectivityInternalPermission() { 1250 mContext.enforceCallingOrSelfPermission( 1251 android.Manifest.permission.CONNECTIVITY_INTERNAL, 1252 "ConnectivityService"); 1253 } 1254 1255 /** 1256 * Handle a {@code DISCONNECTED} event. If this pertains to the non-active 1257 * network, we ignore it. If it is for the active network, we send out a 1258 * broadcast. But first, we check whether it might be possible to connect 1259 * to a different network. 1260 * @param info the {@code NetworkInfo} for the network 1261 */ 1262 private void handleDisconnect(NetworkInfo info) { 1263 1264 int prevNetType = info.getType(); 1265 1266 mNetTrackers[prevNetType].setTeardownRequested(false); 1267 /* 1268 * If the disconnected network is not the active one, then don't report 1269 * this as a loss of connectivity. What probably happened is that we're 1270 * getting the disconnect for a network that we explicitly disabled 1271 * in accordance with network preference policies. 1272 */ 1273 if (!mNetConfigs[prevNetType].isDefault()) { 1274 List pids = mNetRequestersPids[prevNetType]; 1275 for (int i = 0; i<pids.size(); i++) { 1276 Integer pid = (Integer)pids.get(i); 1277 // will remove them because the net's no longer connected 1278 // need to do this now as only now do we know the pids and 1279 // can properly null things that are no longer referenced. 1280 reassessPidDns(pid.intValue(), false); 1281 } 1282 } 1283 1284 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 1285 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 1286 if (info.isFailover()) { 1287 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 1288 info.setFailover(false); 1289 } 1290 if (info.getReason() != null) { 1291 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 1292 } 1293 if (info.getExtraInfo() != null) { 1294 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, 1295 info.getExtraInfo()); 1296 } 1297 1298 if (mNetConfigs[prevNetType].isDefault()) { 1299 tryFailover(prevNetType); 1300 if (mActiveDefaultNetwork != -1) { 1301 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(); 1302 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo); 1303 } else { 1304 mDefaultInetConditionPublished = 0; // we're not connected anymore 1305 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 1306 } 1307 } 1308 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished); 1309 1310 // Reset interface if no other connections are using the same interface 1311 boolean doReset = true; 1312 LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties(); 1313 if (linkProperties != null) { 1314 String oldIface = linkProperties.getInterfaceName(); 1315 if (TextUtils.isEmpty(oldIface) == false) { 1316 for (NetworkStateTracker networkStateTracker : mNetTrackers) { 1317 if (networkStateTracker == null) continue; 1318 NetworkInfo networkInfo = networkStateTracker.getNetworkInfo(); 1319 if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) { 1320 LinkProperties l = networkStateTracker.getLinkProperties(); 1321 if (l == null) continue; 1322 if (oldIface.equals(l.getInterfaceName())) { 1323 doReset = false; 1324 break; 1325 } 1326 } 1327 } 1328 } 1329 } 1330 1331 // do this before we broadcast the change 1332 handleConnectivityChange(prevNetType, doReset); 1333 1334 sendStickyBroadcast(intent); 1335 /* 1336 * If the failover network is already connected, then immediately send 1337 * out a followup broadcast indicating successful failover 1338 */ 1339 if (mActiveDefaultNetwork != -1) { 1340 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo()); 1341 } 1342 } 1343 1344 private void tryFailover(int prevNetType) { 1345 /* 1346 * If this is a default network, check if other defaults are available. 1347 * Try to reconnect on all available and let them hash it out when 1348 * more than one connects. 1349 */ 1350 if (mNetConfigs[prevNetType].isDefault()) { 1351 if (mActiveDefaultNetwork == prevNetType) { 1352 mActiveDefaultNetwork = -1; 1353 } 1354 1355 // don't signal a reconnect for anything lower or equal priority than our 1356 // current connected default 1357 // TODO - don't filter by priority now - nice optimization but risky 1358// int currentPriority = -1; 1359// if (mActiveDefaultNetwork != -1) { 1360// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority; 1361// } 1362 for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) { 1363 if (checkType == prevNetType) continue; 1364 if (mNetConfigs[checkType] == null) continue; 1365 if (!mNetConfigs[checkType].isDefault()) continue; 1366 1367// Enabling the isAvailable() optimization caused mobile to not get 1368// selected if it was in the middle of error handling. Specifically 1369// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL 1370// would not be available and we wouldn't get connected to anything. 1371// So removing the isAvailable() optimization below for now. TODO: This 1372// optimization should work and we need to investigate why it doesn't work. 1373// This could be related to how DEACTIVATE_DATA_CALL is reporting its 1374// complete before it is really complete. 1375// if (!mNetTrackers[checkType].isAvailable()) continue; 1376 1377// if (currentPriority >= mNetConfigs[checkType].mPriority) continue; 1378 1379 NetworkStateTracker checkTracker = mNetTrackers[checkType]; 1380 NetworkInfo checkInfo = checkTracker.getNetworkInfo(); 1381 if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) { 1382 checkInfo.setFailover(true); 1383 checkTracker.reconnect(); 1384 } 1385 if (DBG) log("Attempting to switch to " + checkInfo.getTypeName()); 1386 } 1387 } 1388 } 1389 1390 private void sendConnectedBroadcast(NetworkInfo info) { 1391 sendGeneralBroadcast(info, ConnectivityManager.CONNECTIVITY_ACTION); 1392 } 1393 1394 private void sendInetConditionBroadcast(NetworkInfo info) { 1395 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION); 1396 } 1397 1398 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) { 1399 Intent intent = new Intent(bcastType); 1400 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 1401 if (info.isFailover()) { 1402 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 1403 info.setFailover(false); 1404 } 1405 if (info.getReason() != null) { 1406 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 1407 } 1408 if (info.getExtraInfo() != null) { 1409 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, 1410 info.getExtraInfo()); 1411 } 1412 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished); 1413 sendStickyBroadcast(intent); 1414 } 1415 1416 /** 1417 * Called when an attempt to fail over to another network has failed. 1418 * @param info the {@link NetworkInfo} for the failed network 1419 */ 1420 private void handleConnectionFailure(NetworkInfo info) { 1421 mNetTrackers[info.getType()].setTeardownRequested(false); 1422 1423 String reason = info.getReason(); 1424 String extraInfo = info.getExtraInfo(); 1425 1426 String reasonText; 1427 if (reason == null) { 1428 reasonText = "."; 1429 } else { 1430 reasonText = " (" + reason + ")."; 1431 } 1432 loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText); 1433 1434 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 1435 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 1436 if (getActiveNetworkInfo() == null) { 1437 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 1438 } 1439 if (reason != null) { 1440 intent.putExtra(ConnectivityManager.EXTRA_REASON, reason); 1441 } 1442 if (extraInfo != null) { 1443 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo); 1444 } 1445 if (info.isFailover()) { 1446 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 1447 info.setFailover(false); 1448 } 1449 1450 if (mNetConfigs[info.getType()].isDefault()) { 1451 tryFailover(info.getType()); 1452 if (mActiveDefaultNetwork != -1) { 1453 NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(); 1454 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo); 1455 } else { 1456 mDefaultInetConditionPublished = 0; 1457 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 1458 } 1459 } 1460 1461 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished); 1462 sendStickyBroadcast(intent); 1463 /* 1464 * If the failover network is already connected, then immediately send 1465 * out a followup broadcast indicating successful failover 1466 */ 1467 if (mActiveDefaultNetwork != -1) { 1468 sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo()); 1469 } 1470 } 1471 1472 private void sendStickyBroadcast(Intent intent) { 1473 synchronized(this) { 1474 if (!mSystemReady) { 1475 mInitialBroadcast = new Intent(intent); 1476 } 1477 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1478 mContext.sendStickyBroadcast(intent); 1479 } 1480 } 1481 1482 void systemReady() { 1483 synchronized(this) { 1484 mSystemReady = true; 1485 if (mInitialBroadcast != null) { 1486 mContext.sendStickyBroadcast(mInitialBroadcast); 1487 mInitialBroadcast = null; 1488 } 1489 } 1490 // load the global proxy at startup 1491 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY)); 1492 } 1493 1494 private void handleConnect(NetworkInfo info) { 1495 int type = info.getType(); 1496 1497 // snapshot isFailover, because sendConnectedBroadcast() resets it 1498 boolean isFailover = info.isFailover(); 1499 NetworkStateTracker thisNet = mNetTrackers[type]; 1500 1501 // if this is a default net and other default is running 1502 // kill the one not preferred 1503 if (mNetConfigs[type].isDefault()) { 1504 if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) { 1505 if ((type != mNetworkPreference && 1506 mNetConfigs[mActiveDefaultNetwork].priority > 1507 mNetConfigs[type].priority) || 1508 mNetworkPreference == mActiveDefaultNetwork) { 1509 // don't accept this one 1510 if (DBG) { 1511 log("Not broadcasting CONNECT_ACTION " + 1512 "to torn down network " + info.getTypeName()); 1513 } 1514 teardown(thisNet); 1515 return; 1516 } else { 1517 // tear down the other 1518 NetworkStateTracker otherNet = 1519 mNetTrackers[mActiveDefaultNetwork]; 1520 if (DBG) { 1521 log("Policy requires " + otherNet.getNetworkInfo().getTypeName() + 1522 " teardown"); 1523 } 1524 if (!teardown(otherNet)) { 1525 loge("Network declined teardown request"); 1526 teardown(thisNet); 1527 return; 1528 } 1529 } 1530 } 1531 synchronized (ConnectivityService.this) { 1532 // have a new default network, release the transition wakelock in a second 1533 // if it's held. The second pause is to allow apps to reconnect over the 1534 // new network 1535 if (mNetTransitionWakeLock.isHeld()) { 1536 mHandler.sendMessageDelayed(mHandler.obtainMessage( 1537 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 1538 mNetTransitionWakeLockSerialNumber, 0), 1539 1000); 1540 } 1541 } 1542 mActiveDefaultNetwork = type; 1543 // this will cause us to come up initially as unconnected and switching 1544 // to connected after our normal pause unless somebody reports us as reall 1545 // disconnected 1546 mDefaultInetConditionPublished = 0; 1547 mDefaultConnectionSequence++; 1548 mInetConditionChangeInFlight = false; 1549 // Don't do this - if we never sign in stay, grey 1550 //reportNetworkCondition(mActiveDefaultNetwork, 100); 1551 } 1552 thisNet.setTeardownRequested(false); 1553 updateNetworkSettings(thisNet); 1554 handleConnectivityChange(type, false); 1555 sendConnectedBroadcast(info); 1556 } 1557 1558 /** 1559 * After a change in the connectivity state of a network. We're mainly 1560 * concerned with making sure that the list of DNS servers is set up 1561 * according to which networks are connected, and ensuring that the 1562 * right routing table entries exist. 1563 */ 1564 private void handleConnectivityChange(int netType, boolean doReset) { 1565 /* 1566 * If a non-default network is enabled, add the host routes that 1567 * will allow it's DNS servers to be accessed. 1568 */ 1569 handleDnsConfigurationChange(netType); 1570 1571 if (mNetTrackers[netType].getNetworkInfo().isConnected()) { 1572 if (mNetConfigs[netType].isDefault()) { 1573 handleApplyDefaultProxy(netType); 1574 addDefaultRoute(mNetTrackers[netType]); 1575 } else { 1576 // many radios add a default route even when we don't want one. 1577 // remove the default route unless we need it for our active network 1578 if (mActiveDefaultNetwork != -1) { 1579 LinkProperties defaultLinkProperties = 1580 mNetTrackers[mActiveDefaultNetwork].getLinkProperties(); 1581 LinkProperties newLinkProperties = 1582 mNetTrackers[netType].getLinkProperties(); 1583 String defaultIface = defaultLinkProperties.getInterfaceName(); 1584 if (defaultIface != null && 1585 !defaultIface.equals(newLinkProperties.getInterfaceName())) { 1586 removeDefaultRoute(mNetTrackers[netType]); 1587 } 1588 } 1589 addPrivateDnsRoutes(mNetTrackers[netType]); 1590 } 1591 } else { 1592 if (mNetConfigs[netType].isDefault()) { 1593 removeDefaultRoute(mNetTrackers[netType]); 1594 } else { 1595 removePrivateDnsRoutes(mNetTrackers[netType]); 1596 } 1597 } 1598 1599 if (doReset) { 1600 LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties(); 1601 if (linkProperties != null) { 1602 String iface = linkProperties.getInterfaceName(); 1603 if (TextUtils.isEmpty(iface) == false) { 1604 if (DBG) log("resetConnections(" + iface + ")"); 1605 NetworkUtils.resetConnections(iface); 1606 } 1607 } 1608 } 1609 1610 // TODO: Temporary notifying upstread change to Tethering. 1611 // @see bug/4455071 1612 /** Notify TetheringService if interface name has been changed. */ 1613 if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(), 1614 Phone.REASON_LINK_PROPERTIES_CHANGED)) { 1615 if (isTetheringSupported()) { 1616 mTethering.handleTetherIfaceChange(); 1617 } 1618 } 1619 } 1620 1621 private void addPrivateDnsRoutes(NetworkStateTracker nt) { 1622 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet(); 1623 LinkProperties p = nt.getLinkProperties(); 1624 if (p == null) return; 1625 String interfaceName = p.getInterfaceName(); 1626 1627 if (DBG) { 1628 log("addPrivateDnsRoutes for " + nt + 1629 "(" + interfaceName + ") - mPrivateDnsRouteSet = " + privateDnsRouteSet); 1630 } 1631 if (interfaceName != null && !privateDnsRouteSet) { 1632 Collection<InetAddress> dnsList = p.getDnses(); 1633 for (InetAddress dns : dnsList) { 1634 addHostRoute(nt, dns, 0); 1635 } 1636 nt.privateDnsRouteSet(true); 1637 } 1638 } 1639 1640 private void removePrivateDnsRoutes(NetworkStateTracker nt) { 1641 LinkProperties p = nt.getLinkProperties(); 1642 if (p == null) return; 1643 String interfaceName = p.getInterfaceName(); 1644 boolean privateDnsRouteSet = nt.isPrivateDnsRouteSet(); 1645 if (interfaceName != null && privateDnsRouteSet) { 1646 if (DBG) { 1647 log("removePrivateDnsRoutes for " + nt.getNetworkInfo().getTypeName() + 1648 " (" + interfaceName + ")"); 1649 } 1650 1651 Collection<InetAddress> dnsList = p.getDnses(); 1652 for (InetAddress dns : dnsList) { 1653 if (DBG) log(" removing " + dns); 1654 RouteInfo route = RouteInfo.makeHostRoute(dns); 1655 try { 1656 mNetd.removeRoute(interfaceName, route); 1657 } catch (Exception ex) { 1658 loge("error (" + ex + ") removing dns route " + route); 1659 } 1660 } 1661 nt.privateDnsRouteSet(false); 1662 } 1663 } 1664 1665 1666 private void addDefaultRoute(NetworkStateTracker nt) { 1667 LinkProperties p = nt.getLinkProperties(); 1668 if (p == null) return; 1669 String interfaceName = p.getInterfaceName(); 1670 if (TextUtils.isEmpty(interfaceName)) return; 1671 1672 for (RouteInfo route : p.getRoutes()) { 1673 //TODO - handle non-default routes 1674 if (route.isDefaultRoute()) { 1675 if (DBG) log("adding default route " + route); 1676 InetAddress gateway = route.getGateway(); 1677 if (addHostRoute(nt, gateway, 0)) { 1678 try { 1679 mNetd.addRoute(interfaceName, route); 1680 } catch (Exception e) { 1681 loge("error adding default route " + route); 1682 continue; 1683 } 1684 if (DBG) { 1685 NetworkInfo networkInfo = nt.getNetworkInfo(); 1686 log("addDefaultRoute for " + networkInfo.getTypeName() + 1687 " (" + interfaceName + "), GatewayAddr=" + 1688 gateway.getHostAddress()); 1689 } 1690 } else { 1691 loge("error adding host route for default route " + route); 1692 } 1693 } 1694 } 1695 } 1696 1697 1698 public void removeDefaultRoute(NetworkStateTracker nt) { 1699 LinkProperties p = nt.getLinkProperties(); 1700 if (p == null) return; 1701 String interfaceName = p.getInterfaceName(); 1702 1703 if (interfaceName == null) return; 1704 1705 for (RouteInfo route : p.getRoutes()) { 1706 //TODO - handle non-default routes 1707 if (route.isDefaultRoute()) { 1708 try { 1709 mNetd.removeRoute(interfaceName, route); 1710 } catch (Exception ex) { 1711 loge("error (" + ex + ") removing default route " + route); 1712 continue; 1713 } 1714 if (DBG) { 1715 NetworkInfo networkInfo = nt.getNetworkInfo(); 1716 log("removeDefaultRoute for " + networkInfo.getTypeName() + " (" + 1717 interfaceName + ")"); 1718 } 1719 } 1720 } 1721 } 1722 1723 /** 1724 * Reads the network specific TCP buffer sizes from SystemProperties 1725 * net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system 1726 * wide use 1727 */ 1728 public void updateNetworkSettings(NetworkStateTracker nt) { 1729 String key = nt.getTcpBufferSizesPropName(); 1730 String bufferSizes = SystemProperties.get(key); 1731 1732 if (bufferSizes.length() == 0) { 1733 loge(key + " not found in system properties. Using defaults"); 1734 1735 // Setting to default values so we won't be stuck to previous values 1736 key = "net.tcp.buffersize.default"; 1737 bufferSizes = SystemProperties.get(key); 1738 } 1739 1740 // Set values in kernel 1741 if (bufferSizes.length() != 0) { 1742 if (DBG) { 1743 log("Setting TCP values: [" + bufferSizes 1744 + "] which comes from [" + key + "]"); 1745 } 1746 setBufferSize(bufferSizes); 1747 } 1748 } 1749 1750 /** 1751 * Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max] 1752 * which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem 1753 * 1754 * @param bufferSizes in the format of "readMin, readInitial, readMax, 1755 * writeMin, writeInitial, writeMax" 1756 */ 1757 private void setBufferSize(String bufferSizes) { 1758 try { 1759 String[] values = bufferSizes.split(","); 1760 1761 if (values.length == 6) { 1762 final String prefix = "/sys/kernel/ipv4/tcp_"; 1763 FileUtils.stringToFile(prefix + "rmem_min", values[0]); 1764 FileUtils.stringToFile(prefix + "rmem_def", values[1]); 1765 FileUtils.stringToFile(prefix + "rmem_max", values[2]); 1766 FileUtils.stringToFile(prefix + "wmem_min", values[3]); 1767 FileUtils.stringToFile(prefix + "wmem_def", values[4]); 1768 FileUtils.stringToFile(prefix + "wmem_max", values[5]); 1769 } else { 1770 loge("Invalid buffersize string: " + bufferSizes); 1771 } 1772 } catch (IOException e) { 1773 loge("Can't set tcp buffer sizes:" + e); 1774 } 1775 } 1776 1777 /** 1778 * Adjust the per-process dns entries (net.dns<x>.<pid>) based 1779 * on the highest priority active net which this process requested. 1780 * If there aren't any, clear it out 1781 */ 1782 private void reassessPidDns(int myPid, boolean doBump) 1783 { 1784 if (DBG) log("reassessPidDns for pid " + myPid); 1785 for(int i : mPriorityList) { 1786 if (mNetConfigs[i].isDefault()) { 1787 continue; 1788 } 1789 NetworkStateTracker nt = mNetTrackers[i]; 1790 if (nt.getNetworkInfo().isConnected() && 1791 !nt.isTeardownRequested()) { 1792 LinkProperties p = nt.getLinkProperties(); 1793 if (p == null) continue; 1794 List pids = mNetRequestersPids[i]; 1795 for (int j=0; j<pids.size(); j++) { 1796 Integer pid = (Integer)pids.get(j); 1797 if (pid.intValue() == myPid) { 1798 Collection<InetAddress> dnses = p.getDnses(); 1799 writePidDns(dnses, myPid); 1800 if (doBump) { 1801 bumpDns(); 1802 } 1803 return; 1804 } 1805 } 1806 } 1807 } 1808 // nothing found - delete 1809 for (int i = 1; ; i++) { 1810 String prop = "net.dns" + i + "." + myPid; 1811 if (SystemProperties.get(prop).length() == 0) { 1812 if (doBump) { 1813 bumpDns(); 1814 } 1815 return; 1816 } 1817 SystemProperties.set(prop, ""); 1818 } 1819 } 1820 1821 // return true if results in a change 1822 private boolean writePidDns(Collection <InetAddress> dnses, int pid) { 1823 int j = 1; 1824 boolean changed = false; 1825 for (InetAddress dns : dnses) { 1826 String dnsString = dns.getHostAddress(); 1827 if (changed || !dnsString.equals(SystemProperties.get("net.dns" + j + "." + pid))) { 1828 changed = true; 1829 SystemProperties.set("net.dns" + j++ + "." + pid, dns.getHostAddress()); 1830 } 1831 } 1832 return changed; 1833 } 1834 1835 private void bumpDns() { 1836 /* 1837 * Bump the property that tells the name resolver library to reread 1838 * the DNS server list from the properties. 1839 */ 1840 String propVal = SystemProperties.get("net.dnschange"); 1841 int n = 0; 1842 if (propVal.length() != 0) { 1843 try { 1844 n = Integer.parseInt(propVal); 1845 } catch (NumberFormatException e) {} 1846 } 1847 SystemProperties.set("net.dnschange", "" + (n+1)); 1848 /* 1849 * Tell the VMs to toss their DNS caches 1850 */ 1851 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE); 1852 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 1853 /* 1854 * Connectivity events can happen before boot has completed ... 1855 */ 1856 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1857 mContext.sendBroadcast(intent); 1858 } 1859 1860 private void handleDnsConfigurationChange(int netType) { 1861 // add default net's dns entries 1862 NetworkStateTracker nt = mNetTrackers[netType]; 1863 if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) { 1864 LinkProperties p = nt.getLinkProperties(); 1865 if (p == null) return; 1866 Collection<InetAddress> dnses = p.getDnses(); 1867 boolean changed = false; 1868 if (mNetConfigs[netType].isDefault()) { 1869 int j = 1; 1870 if (dnses.size() == 0 && mDefaultDns != null) { 1871 String dnsString = mDefaultDns.getHostAddress(); 1872 if (!dnsString.equals(SystemProperties.get("net.dns1"))) { 1873 if (DBG) { 1874 log("no dns provided - using " + dnsString); 1875 } 1876 changed = true; 1877 SystemProperties.set("net.dns1", dnsString); 1878 } 1879 j++; 1880 } else { 1881 for (InetAddress dns : dnses) { 1882 String dnsString = dns.getHostAddress(); 1883 if (!changed && dnsString.equals(SystemProperties.get("net.dns" + j))) { 1884 j++; 1885 continue; 1886 } 1887 if (DBG) { 1888 log("adding dns " + dns + " for " + 1889 nt.getNetworkInfo().getTypeName()); 1890 } 1891 changed = true; 1892 SystemProperties.set("net.dns" + j++, dnsString); 1893 } 1894 } 1895 for (int k=j ; k<mNumDnsEntries; k++) { 1896 if (changed || !TextUtils.isEmpty(SystemProperties.get("net.dns" + k))) { 1897 if (DBG) log("erasing net.dns" + k); 1898 changed = true; 1899 SystemProperties.set("net.dns" + k, ""); 1900 } 1901 } 1902 mNumDnsEntries = j; 1903 } else { 1904 // set per-pid dns for attached secondary nets 1905 List pids = mNetRequestersPids[netType]; 1906 for (int y=0; y< pids.size(); y++) { 1907 Integer pid = (Integer)pids.get(y); 1908 changed = writePidDns(dnses, pid.intValue()); 1909 } 1910 } 1911 if (changed) bumpDns(); 1912 } 1913 } 1914 1915 private int getRestoreDefaultNetworkDelay(int networkType) { 1916 String restoreDefaultNetworkDelayStr = SystemProperties.get( 1917 NETWORK_RESTORE_DELAY_PROP_NAME); 1918 if(restoreDefaultNetworkDelayStr != null && 1919 restoreDefaultNetworkDelayStr.length() != 0) { 1920 try { 1921 return Integer.valueOf(restoreDefaultNetworkDelayStr); 1922 } catch (NumberFormatException e) { 1923 } 1924 } 1925 // if the system property isn't set, use the value for the apn type 1926 int ret = RESTORE_DEFAULT_NETWORK_DELAY; 1927 1928 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) && 1929 (mNetConfigs[networkType] != null)) { 1930 ret = mNetConfigs[networkType].restoreTime; 1931 } 1932 return ret; 1933 } 1934 1935 @Override 1936 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1937 if (mContext.checkCallingOrSelfPermission( 1938 android.Manifest.permission.DUMP) 1939 != PackageManager.PERMISSION_GRANTED) { 1940 pw.println("Permission Denial: can't dump ConnectivityService " + 1941 "from from pid=" + Binder.getCallingPid() + ", uid=" + 1942 Binder.getCallingUid()); 1943 return; 1944 } 1945 pw.println(); 1946 for (NetworkStateTracker nst : mNetTrackers) { 1947 if (nst != null) { 1948 if (nst.getNetworkInfo().isConnected()) { 1949 pw.println("Active network: " + nst.getNetworkInfo(). 1950 getTypeName()); 1951 } 1952 pw.println(nst.getNetworkInfo()); 1953 pw.println(nst); 1954 pw.println(); 1955 } 1956 } 1957 1958 pw.println("Network Requester Pids:"); 1959 for (int net : mPriorityList) { 1960 String pidString = net + ": "; 1961 for (Object pid : mNetRequestersPids[net]) { 1962 pidString = pidString + pid.toString() + ", "; 1963 } 1964 pw.println(pidString); 1965 } 1966 pw.println(); 1967 1968 pw.println("FeatureUsers:"); 1969 for (Object requester : mFeatureUsers) { 1970 pw.println(requester.toString()); 1971 } 1972 pw.println(); 1973 1974 synchronized (this) { 1975 pw.println("NetworkTranstionWakeLock is currently " + 1976 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held."); 1977 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy); 1978 } 1979 pw.println(); 1980 1981 mTethering.dump(fd, pw, args); 1982 1983 if (mInetLog != null) { 1984 pw.println(); 1985 pw.println("Inet condition reports:"); 1986 for(int i = 0; i < mInetLog.size(); i++) { 1987 pw.println(mInetLog.get(i)); 1988 } 1989 } 1990 } 1991 1992 // must be stateless - things change under us. 1993 private class MyHandler extends Handler { 1994 public MyHandler(Looper looper) { 1995 super(looper); 1996 } 1997 1998 @Override 1999 public void handleMessage(Message msg) { 2000 NetworkInfo info; 2001 switch (msg.what) { 2002 case NetworkStateTracker.EVENT_STATE_CHANGED: 2003 info = (NetworkInfo) msg.obj; 2004 int type = info.getType(); 2005 NetworkInfo.State state = info.getState(); 2006 2007 if (DBG) log("ConnectivityChange for " + 2008 info.getTypeName() + ": " + 2009 state + "/" + info.getDetailedState()); 2010 2011 // Connectivity state changed: 2012 // [31-13] Reserved for future use 2013 // [12-9] Network subtype (for mobile network, as defined 2014 // by TelephonyManager) 2015 // [8-3] Detailed state ordinal (as defined by 2016 // NetworkInfo.DetailedState) 2017 // [2-0] Network type (as defined by ConnectivityManager) 2018 int eventLogParam = (info.getType() & 0x7) | 2019 ((info.getDetailedState().ordinal() & 0x3f) << 3) | 2020 (info.getSubtype() << 9); 2021 EventLog.writeEvent(EventLogTags.CONNECTIVITY_STATE_CHANGED, 2022 eventLogParam); 2023 2024 if (info.getDetailedState() == 2025 NetworkInfo.DetailedState.FAILED) { 2026 handleConnectionFailure(info); 2027 } else if (state == NetworkInfo.State.DISCONNECTED) { 2028 handleDisconnect(info); 2029 } else if (state == NetworkInfo.State.SUSPENDED) { 2030 // TODO: need to think this over. 2031 // the logic here is, handle SUSPENDED the same as 2032 // DISCONNECTED. The only difference being we are 2033 // broadcasting an intent with NetworkInfo that's 2034 // suspended. This allows the applications an 2035 // opportunity to handle DISCONNECTED and SUSPENDED 2036 // differently, or not. 2037 handleDisconnect(info); 2038 } else if (state == NetworkInfo.State.CONNECTED) { 2039 handleConnect(info); 2040 } 2041 break; 2042 case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: 2043 info = (NetworkInfo) msg.obj; 2044 // TODO: Temporary allowing network configuration 2045 // change not resetting sockets. 2046 // @see bug/4455071 2047 handleConnectivityChange(info.getType(), false); 2048 break; 2049 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: 2050 String causedBy = null; 2051 synchronized (ConnectivityService.this) { 2052 if (msg.arg1 == mNetTransitionWakeLockSerialNumber && 2053 mNetTransitionWakeLock.isHeld()) { 2054 mNetTransitionWakeLock.release(); 2055 causedBy = mNetTransitionWakeLockCausedBy; 2056 } 2057 } 2058 if (causedBy != null) { 2059 log("NetTransition Wakelock for " + causedBy + " released by timeout"); 2060 } 2061 break; 2062 case EVENT_RESTORE_DEFAULT_NETWORK: 2063 FeatureUser u = (FeatureUser)msg.obj; 2064 u.expire(); 2065 break; 2066 case EVENT_INET_CONDITION_CHANGE: 2067 { 2068 int netType = msg.arg1; 2069 int condition = msg.arg2; 2070 handleInetConditionChange(netType, condition); 2071 break; 2072 } 2073 case EVENT_INET_CONDITION_HOLD_END: 2074 { 2075 int netType = msg.arg1; 2076 int sequence = msg.arg2; 2077 handleInetConditionHoldEnd(netType, sequence); 2078 break; 2079 } 2080 case EVENT_SET_NETWORK_PREFERENCE: 2081 { 2082 int preference = msg.arg1; 2083 handleSetNetworkPreference(preference); 2084 break; 2085 } 2086 case EVENT_SET_BACKGROUND_DATA: 2087 { 2088 boolean enabled = (msg.arg1 == ENABLED); 2089 handleSetBackgroundData(enabled); 2090 break; 2091 } 2092 case EVENT_SET_MOBILE_DATA: 2093 { 2094 boolean enabled = (msg.arg1 == ENABLED); 2095 handleSetMobileData(enabled); 2096 break; 2097 } 2098 case EVENT_APPLY_GLOBAL_HTTP_PROXY: 2099 { 2100 handleDeprecatedGlobalHttpProxy(); 2101 break; 2102 } 2103 case EVENT_SET_DEPENDENCY_MET: 2104 { 2105 boolean met = (msg.arg1 == ENABLED); 2106 handleSetDependencyMet(msg.arg2, met); 2107 break; 2108 } 2109 } 2110 } 2111 } 2112 2113 // javadoc from interface 2114 public int tether(String iface) { 2115 enforceTetherChangePermission(); 2116 2117 if (isTetheringSupported()) { 2118 return mTethering.tether(iface); 2119 } else { 2120 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2121 } 2122 } 2123 2124 // javadoc from interface 2125 public int untether(String iface) { 2126 enforceTetherChangePermission(); 2127 2128 if (isTetheringSupported()) { 2129 return mTethering.untether(iface); 2130 } else { 2131 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2132 } 2133 } 2134 2135 // javadoc from interface 2136 public int getLastTetherError(String iface) { 2137 enforceTetherAccessPermission(); 2138 2139 if (isTetheringSupported()) { 2140 return mTethering.getLastTetherError(iface); 2141 } else { 2142 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2143 } 2144 } 2145 2146 // TODO - proper iface API for selection by property, inspection, etc 2147 public String[] getTetherableUsbRegexs() { 2148 enforceTetherAccessPermission(); 2149 if (isTetheringSupported()) { 2150 return mTethering.getTetherableUsbRegexs(); 2151 } else { 2152 return new String[0]; 2153 } 2154 } 2155 2156 public String[] getTetherableWifiRegexs() { 2157 enforceTetherAccessPermission(); 2158 if (isTetheringSupported()) { 2159 return mTethering.getTetherableWifiRegexs(); 2160 } else { 2161 return new String[0]; 2162 } 2163 } 2164 2165 public String[] getTetherableBluetoothRegexs() { 2166 enforceTetherAccessPermission(); 2167 if (isTetheringSupported()) { 2168 return mTethering.getTetherableBluetoothRegexs(); 2169 } else { 2170 return new String[0]; 2171 } 2172 } 2173 2174 // TODO - move iface listing, queries, etc to new module 2175 // javadoc from interface 2176 public String[] getTetherableIfaces() { 2177 enforceTetherAccessPermission(); 2178 return mTethering.getTetherableIfaces(); 2179 } 2180 2181 public String[] getTetheredIfaces() { 2182 enforceTetherAccessPermission(); 2183 return mTethering.getTetheredIfaces(); 2184 } 2185 2186 public String[] getTetheringErroredIfaces() { 2187 enforceTetherAccessPermission(); 2188 return mTethering.getErroredIfaces(); 2189 } 2190 2191 // if ro.tether.denied = true we default to no tethering 2192 // gservices could set the secure setting to 1 though to enable it on a build where it 2193 // had previously been turned off. 2194 public boolean isTetheringSupported() { 2195 enforceTetherAccessPermission(); 2196 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 2197 boolean tetherEnabledInSettings = (Settings.Secure.getInt(mContext.getContentResolver(), 2198 Settings.Secure.TETHER_SUPPORTED, defaultVal) != 0); 2199 return tetherEnabledInSettings && mTetheringConfigValid; 2200 } 2201 2202 // An API NetworkStateTrackers can call when they lose their network. 2203 // This will automatically be cleared after X seconds or a network becomes CONNECTED, 2204 // whichever happens first. The timer is started by the first caller and not 2205 // restarted by subsequent callers. 2206 public void requestNetworkTransitionWakelock(String forWhom) { 2207 enforceConnectivityInternalPermission(); 2208 synchronized (this) { 2209 if (mNetTransitionWakeLock.isHeld()) return; 2210 mNetTransitionWakeLockSerialNumber++; 2211 mNetTransitionWakeLock.acquire(); 2212 mNetTransitionWakeLockCausedBy = forWhom; 2213 } 2214 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2215 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 2216 mNetTransitionWakeLockSerialNumber, 0), 2217 mNetTransitionWakeLockTimeout); 2218 return; 2219 } 2220 2221 // 100 percent is full good, 0 is full bad. 2222 public void reportInetCondition(int networkType, int percentage) { 2223 if (DBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")"); 2224 mContext.enforceCallingOrSelfPermission( 2225 android.Manifest.permission.STATUS_BAR, 2226 "ConnectivityService"); 2227 2228 if (DBG) { 2229 int pid = getCallingPid(); 2230 int uid = getCallingUid(); 2231 String s = pid + "(" + uid + ") reports inet is " + 2232 (percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " + 2233 "network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime(); 2234 mInetLog.add(s); 2235 while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) { 2236 mInetLog.remove(0); 2237 } 2238 } 2239 mHandler.sendMessage(mHandler.obtainMessage( 2240 EVENT_INET_CONDITION_CHANGE, networkType, percentage)); 2241 } 2242 2243 private void handleInetConditionChange(int netType, int condition) { 2244 if (DBG) { 2245 log("Inet connectivity change, net=" + 2246 netType + ", condition=" + condition + 2247 ",mActiveDefaultNetwork=" + mActiveDefaultNetwork); 2248 } 2249 if (mActiveDefaultNetwork == -1) { 2250 if (DBG) log("no active default network - aborting"); 2251 return; 2252 } 2253 if (mActiveDefaultNetwork != netType) { 2254 if (DBG) log("given net not default - aborting"); 2255 return; 2256 } 2257 mDefaultInetCondition = condition; 2258 int delay; 2259 if (mInetConditionChangeInFlight == false) { 2260 if (DBG) log("starting a change hold"); 2261 // setup a new hold to debounce this 2262 if (mDefaultInetCondition > 50) { 2263 delay = Settings.Secure.getInt(mContext.getContentResolver(), 2264 Settings.Secure.INET_CONDITION_DEBOUNCE_UP_DELAY, 500); 2265 } else { 2266 delay = Settings.Secure.getInt(mContext.getContentResolver(), 2267 Settings.Secure.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000); 2268 } 2269 mInetConditionChangeInFlight = true; 2270 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END, 2271 mActiveDefaultNetwork, mDefaultConnectionSequence), delay); 2272 } else { 2273 // we've set the new condition, when this hold ends that will get 2274 // picked up 2275 if (DBG) log("currently in hold - not setting new end evt"); 2276 } 2277 } 2278 2279 private void handleInetConditionHoldEnd(int netType, int sequence) { 2280 if (DBG) { 2281 log("Inet hold end, net=" + netType + 2282 ", condition =" + mDefaultInetCondition + 2283 ", published condition =" + mDefaultInetConditionPublished); 2284 } 2285 mInetConditionChangeInFlight = false; 2286 2287 if (mActiveDefaultNetwork == -1) { 2288 if (DBG) log("no active default network - aborting"); 2289 return; 2290 } 2291 if (mDefaultConnectionSequence != sequence) { 2292 if (DBG) log("event hold for obsolete network - aborting"); 2293 return; 2294 } 2295 if (mDefaultInetConditionPublished == mDefaultInetCondition) { 2296 if (DBG) log("no change in condition - aborting"); 2297 return; 2298 } 2299 NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(); 2300 if (networkInfo.isConnected() == false) { 2301 if (DBG) log("default network not connected - aborting"); 2302 return; 2303 } 2304 mDefaultInetConditionPublished = mDefaultInetCondition; 2305 sendInetConditionBroadcast(networkInfo); 2306 return; 2307 } 2308 2309 public synchronized ProxyProperties getProxy() { 2310 if (mGlobalProxy != null) return mGlobalProxy; 2311 if (mDefaultProxy != null) return mDefaultProxy; 2312 return null; 2313 } 2314 2315 public void setGlobalProxy(ProxyProperties proxyProperties) { 2316 enforceChangePermission(); 2317 synchronized (mGlobalProxyLock) { 2318 if (proxyProperties == mGlobalProxy) return; 2319 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return; 2320 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return; 2321 2322 String host = ""; 2323 int port = 0; 2324 String exclList = ""; 2325 if (proxyProperties != null && !TextUtils.isEmpty(proxyProperties.getHost())) { 2326 mGlobalProxy = new ProxyProperties(proxyProperties); 2327 host = mGlobalProxy.getHost(); 2328 port = mGlobalProxy.getPort(); 2329 exclList = mGlobalProxy.getExclusionList(); 2330 } else { 2331 mGlobalProxy = null; 2332 } 2333 ContentResolver res = mContext.getContentResolver(); 2334 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST, host); 2335 Settings.Secure.putInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, port); 2336 Settings.Secure.putString(res, Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 2337 exclList); 2338 } 2339 2340 if (mGlobalProxy == null) { 2341 proxyProperties = mDefaultProxy; 2342 } 2343 sendProxyBroadcast(proxyProperties); 2344 } 2345 2346 private void loadGlobalProxy() { 2347 ContentResolver res = mContext.getContentResolver(); 2348 String host = Settings.Secure.getString(res, Settings.Secure.GLOBAL_HTTP_PROXY_HOST); 2349 int port = Settings.Secure.getInt(res, Settings.Secure.GLOBAL_HTTP_PROXY_PORT, 0); 2350 String exclList = Settings.Secure.getString(res, 2351 Settings.Secure.GLOBAL_HTTP_PROXY_EXCLUSION_LIST); 2352 if (!TextUtils.isEmpty(host)) { 2353 ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList); 2354 synchronized (mGlobalProxyLock) { 2355 mGlobalProxy = proxyProperties; 2356 } 2357 } 2358 } 2359 2360 public ProxyProperties getGlobalProxy() { 2361 synchronized (mGlobalProxyLock) { 2362 return mGlobalProxy; 2363 } 2364 } 2365 2366 private void handleApplyDefaultProxy(int type) { 2367 // check if new default - push it out to all VM if so 2368 ProxyProperties proxy = mNetTrackers[type].getLinkProperties().getHttpProxy(); 2369 synchronized (this) { 2370 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return; 2371 if (mDefaultProxy == proxy) return; 2372 if (!TextUtils.isEmpty(proxy.getHost())) { 2373 mDefaultProxy = proxy; 2374 } else { 2375 mDefaultProxy = null; 2376 } 2377 } 2378 if (DBG) log("changing default proxy to " + proxy); 2379 if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return; 2380 if (mGlobalProxy != null) return; 2381 sendProxyBroadcast(proxy); 2382 } 2383 2384 private void handleDeprecatedGlobalHttpProxy() { 2385 String proxy = Settings.Secure.getString(mContext.getContentResolver(), 2386 Settings.Secure.HTTP_PROXY); 2387 if (!TextUtils.isEmpty(proxy)) { 2388 String data[] = proxy.split(":"); 2389 String proxyHost = data[0]; 2390 int proxyPort = 8080; 2391 if (data.length > 1) { 2392 try { 2393 proxyPort = Integer.parseInt(data[1]); 2394 } catch (NumberFormatException e) { 2395 return; 2396 } 2397 } 2398 ProxyProperties p = new ProxyProperties(data[0], proxyPort, ""); 2399 setGlobalProxy(p); 2400 } 2401 } 2402 2403 private void sendProxyBroadcast(ProxyProperties proxy) { 2404 if (proxy == null) proxy = new ProxyProperties("", 0, ""); 2405 log("sending Proxy Broadcast for " + proxy); 2406 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); 2407 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 2408 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 2409 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy); 2410 mContext.sendStickyBroadcast(intent); 2411 } 2412 2413 private static class SettingsObserver extends ContentObserver { 2414 private int mWhat; 2415 private Handler mHandler; 2416 SettingsObserver(Handler handler, int what) { 2417 super(handler); 2418 mHandler = handler; 2419 mWhat = what; 2420 } 2421 2422 void observe(Context context) { 2423 ContentResolver resolver = context.getContentResolver(); 2424 resolver.registerContentObserver(Settings.Secure.getUriFor( 2425 Settings.Secure.HTTP_PROXY), false, this); 2426 } 2427 2428 @Override 2429 public void onChange(boolean selfChange) { 2430 mHandler.obtainMessage(mWhat).sendToTarget(); 2431 } 2432 } 2433 2434 private void log(String s) { 2435 Slog.d(TAG, s); 2436 } 2437 2438 private void loge(String s) { 2439 Slog.e(TAG, s); 2440 } 2441 2442 int convertFeatureToNetworkType(String feature){ 2443 int networkType = -1; 2444 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) { 2445 networkType = ConnectivityManager.TYPE_MOBILE_MMS; 2446 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) { 2447 networkType = ConnectivityManager.TYPE_MOBILE_SUPL; 2448 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) || 2449 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) { 2450 networkType = ConnectivityManager.TYPE_MOBILE_DUN; 2451 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) { 2452 networkType = ConnectivityManager.TYPE_MOBILE_HIPRI; 2453 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) { 2454 networkType = ConnectivityManager.TYPE_MOBILE_FOTA; 2455 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) { 2456 networkType = ConnectivityManager.TYPE_MOBILE_IMS; 2457 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) { 2458 networkType = ConnectivityManager.TYPE_MOBILE_CBS; 2459 } 2460 return networkType; 2461 } 2462 2463 private static <T> T checkNotNull(T value, String message) { 2464 if (value == null) { 2465 throw new NullPointerException(message); 2466 } 2467 return value; 2468 } 2469 2470 /** 2471 * Protect a socket from VPN routing rules. This method is used by 2472 * VpnBuilder and not available in ConnectivityManager. Permission 2473 * checks are done in Vpn class. 2474 * @hide 2475 */ 2476 @Override 2477 public void protectVpn(ParcelFileDescriptor socket) { 2478 mVpn.protect(socket, getDefaultInterface()); 2479 } 2480 2481 /** 2482 * Prepare for a VPN application. This method is used by VpnDialogs 2483 * and not available in ConnectivityManager. Permission checks are 2484 * done in Vpn class. 2485 * @hide 2486 */ 2487 @Override 2488 public String prepareVpn(String packageName) { 2489 return mVpn.prepare(packageName); 2490 } 2491 2492 /** 2493 * Configure a TUN interface and return its file descriptor. Parameters 2494 * are encoded and opaque to this class. This method is used by VpnBuilder 2495 * and not available in ConnectivityManager. Permission checks are done 2496 * in Vpn class. 2497 * @hide 2498 */ 2499 @Override 2500 public ParcelFileDescriptor establishVpn(VpnConfig config) { 2501 return mVpn.establish(config); 2502 } 2503 2504 /** 2505 * Handle a legacy VPN request. 2506 * @hide 2507 */ 2508 @Override 2509 public void doLegacyVpn(VpnConfig config, String[] racoon, String[] mtpd) { 2510 mVpn.doLegacyVpn(config, racoon, mtpd); 2511 } 2512 2513 private String getDefaultInterface() { 2514 if (ConnectivityManager.isNetworkTypeValid(mActiveDefaultNetwork)) { 2515 NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork]; 2516 if (tracker != null) { 2517 LinkProperties properties = tracker.getLinkProperties(); 2518 if (properties != null) { 2519 return properties.getInterfaceName(); 2520 } 2521 } 2522 } 2523 throw new IllegalStateException("No default interface"); 2524 } 2525 2526 /** 2527 * Callback for VPN subsystem. Currently VPN is not adapted to the service 2528 * through NetworkStateTracker since it works differently. For example, it 2529 * needs to override DNS servers but never takes the default routes. It 2530 * relies on another data network, and it could keep existing connections 2531 * alive after reconnecting, switching between networks, or even resuming 2532 * from deep sleep. Calls from applications should be done synchronously 2533 * to avoid race conditions. As these are all hidden APIs, refactoring can 2534 * be done whenever a better abstraction is developed. 2535 */ 2536 public class VpnCallback { 2537 2538 private VpnCallback() { 2539 } 2540 2541 public synchronized void override(List<String> dnsServers, List<String> searchDomains) { 2542 // TODO: override DNS servers and http proxy. 2543 } 2544 2545 public synchronized void restore() { 2546 // TODO: restore VPN changes. 2547 } 2548 } 2549} 2550