ConnectivityService.java revision 80047faad914c9b9b4966d6b58fc22800c3fcebc
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.RECEIVE_DATA_ACTIVITY_CHANGE; 20import static android.net.ConnectivityManager.CONNECTIVITY_ACTION; 21import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE; 22import static android.net.ConnectivityManager.NETID_UNSET; 23import static android.net.ConnectivityManager.TYPE_NONE; 24import static android.net.ConnectivityManager.TYPE_VPN; 25import static android.net.ConnectivityManager.getNetworkTypeName; 26import static android.net.ConnectivityManager.isNetworkTypeValid; 27import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL; 28import static android.net.NetworkPolicyManager.RULE_REJECT_METERED; 29 30import android.annotation.Nullable; 31import android.app.AlarmManager; 32import android.app.Notification; 33import android.app.NotificationManager; 34import android.app.PendingIntent; 35import android.content.BroadcastReceiver; 36import android.content.ContentResolver; 37import android.content.Context; 38import android.content.Intent; 39import android.content.IntentFilter; 40import android.content.pm.PackageManager; 41import android.content.res.Configuration; 42import android.content.res.Resources; 43import android.database.ContentObserver; 44import android.net.ConnectivityManager; 45import android.net.IConnectivityManager; 46import android.net.INetworkManagementEventObserver; 47import android.net.INetworkPolicyListener; 48import android.net.INetworkPolicyManager; 49import android.net.INetworkStatsService; 50import android.net.LinkProperties; 51import android.net.LinkProperties.CompareResult; 52import android.net.Network; 53import android.net.NetworkAgent; 54import android.net.NetworkCapabilities; 55import android.net.NetworkConfig; 56import android.net.NetworkInfo; 57import android.net.NetworkInfo.DetailedState; 58import android.net.NetworkMisc; 59import android.net.NetworkQuotaInfo; 60import android.net.NetworkRequest; 61import android.net.NetworkState; 62import android.net.NetworkUtils; 63import android.net.Proxy; 64import android.net.ProxyInfo; 65import android.net.RouteInfo; 66import android.net.UidRange; 67import android.net.Uri; 68import android.os.Binder; 69import android.os.Bundle; 70import android.os.FileUtils; 71import android.os.Handler; 72import android.os.HandlerThread; 73import android.os.IBinder; 74import android.os.INetworkManagementService; 75import android.os.Looper; 76import android.os.Message; 77import android.os.Messenger; 78import android.os.ParcelFileDescriptor; 79import android.os.PowerManager; 80import android.os.Process; 81import android.os.RemoteException; 82import android.os.SystemClock; 83import android.os.SystemProperties; 84import android.os.UserHandle; 85import android.os.UserManager; 86import android.provider.Settings; 87import android.security.Credentials; 88import android.security.KeyStore; 89import android.telephony.TelephonyManager; 90import android.text.TextUtils; 91import android.util.Slog; 92import android.util.SparseArray; 93import android.util.SparseBooleanArray; 94import android.util.SparseIntArray; 95import android.util.Xml; 96 97import com.android.internal.R; 98import com.android.internal.annotations.GuardedBy; 99import com.android.internal.app.IBatteryStats; 100import com.android.internal.net.LegacyVpnInfo; 101import com.android.internal.net.NetworkStatsFactory; 102import com.android.internal.net.VpnConfig; 103import com.android.internal.net.VpnInfo; 104import com.android.internal.net.VpnProfile; 105import com.android.internal.telephony.DctConstants; 106import com.android.internal.util.AsyncChannel; 107import com.android.internal.util.IndentingPrintWriter; 108import com.android.internal.util.XmlUtils; 109import com.android.server.am.BatteryStatsService; 110import com.android.server.connectivity.DataConnectionStats; 111import com.android.server.connectivity.Nat464Xlat; 112import com.android.server.connectivity.NetworkAgentInfo; 113import com.android.server.connectivity.NetworkMonitor; 114import com.android.server.connectivity.PacManager; 115import com.android.server.connectivity.PermissionMonitor; 116import com.android.server.connectivity.Tethering; 117import com.android.server.connectivity.Vpn; 118import com.android.server.net.BaseNetworkObserver; 119import com.android.server.net.LockdownVpnTracker; 120import com.google.android.collect.Lists; 121import com.google.android.collect.Sets; 122 123import org.xmlpull.v1.XmlPullParser; 124import org.xmlpull.v1.XmlPullParserException; 125 126import java.io.File; 127import java.io.FileDescriptor; 128import java.io.FileNotFoundException; 129import java.io.FileReader; 130import java.io.IOException; 131import java.io.PrintWriter; 132import java.net.Inet4Address; 133import java.net.InetAddress; 134import java.net.UnknownHostException; 135import java.util.ArrayList; 136import java.util.Arrays; 137import java.util.Collection; 138import java.util.HashMap; 139import java.util.HashSet; 140import java.util.Iterator; 141import java.util.List; 142import java.util.Map; 143import java.util.Objects; 144import java.util.concurrent.atomic.AtomicInteger; 145 146/** 147 * @hide 148 */ 149public class ConnectivityService extends IConnectivityManager.Stub 150 implements PendingIntent.OnFinished { 151 private static final String TAG = "ConnectivityService"; 152 153 private static final boolean DBG = true; 154 private static final boolean VDBG = false; 155 156 private static final boolean LOGD_RULES = false; 157 158 // TODO: create better separation between radio types and network types 159 160 // how long to wait before switching back to a radio's default network 161 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000; 162 // system property that can override the above value 163 private static final String NETWORK_RESTORE_DELAY_PROP_NAME = 164 "android.telephony.apn-restore"; 165 166 // How long to delay to removal of a pending intent based request. 167 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS 168 private final int mReleasePendingIntentDelayMs; 169 170 private Tethering mTethering; 171 172 private final PermissionMonitor mPermissionMonitor; 173 174 private KeyStore mKeyStore; 175 176 @GuardedBy("mVpns") 177 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>(); 178 179 private boolean mLockdownEnabled; 180 private LockdownVpnTracker mLockdownTracker; 181 182 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */ 183 private Object mRulesLock = new Object(); 184 /** Currently active network rules by UID. */ 185 private SparseIntArray mUidRules = new SparseIntArray(); 186 /** Set of ifaces that are costly. */ 187 private HashSet<String> mMeteredIfaces = Sets.newHashSet(); 188 189 private Context mContext; 190 private int mNetworkPreference; 191 // 0 is full bad, 100 is full good 192 private int mDefaultInetConditionPublished = 0; 193 194 private Object mDnsLock = new Object(); 195 private int mNumDnsEntries; 196 197 private boolean mTestMode; 198 private static ConnectivityService sServiceInstance; 199 200 private INetworkManagementService mNetd; 201 private INetworkStatsService mStatsService; 202 private INetworkPolicyManager mPolicyManager; 203 204 private String mCurrentTcpBufferSizes; 205 206 private static final int ENABLED = 1; 207 private static final int DISABLED = 0; 208 209 // Arguments to rematchNetworkAndRequests() 210 private enum NascentState { 211 // Indicates a network was just validated for the first time. If the network is found to 212 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down. 213 JUST_VALIDATED, 214 // Indicates a network was not validated for the first time immediately prior to this call. 215 NOT_JUST_VALIDATED 216 }; 217 private enum ReapUnvalidatedNetworks { 218 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming 219 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's 220 // known that there may be unvalidated networks that could potentially be reaped, and when 221 // all networks have been rematched against all NetworkRequests. 222 REAP, 223 // Don't reap unvalidated networks. This should be passed when it's known that there are 224 // no unvalidated networks that could potentially be reaped, and when some networks have 225 // not yet been rematched against all NetworkRequests. 226 DONT_REAP 227 }; 228 229 /** 230 * used internally to change our mobile data enabled flag 231 */ 232 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2; 233 234 /** 235 * used internally to clear a wakelock when transitioning 236 * from one net to another. Clear happens when we get a new 237 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens 238 * after a timeout if no network is found (typically 1 min). 239 */ 240 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8; 241 242 /** 243 * used internally to reload global proxy settings 244 */ 245 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9; 246 247 /** 248 * used internally to send a sticky broadcast delayed. 249 */ 250 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11; 251 252 /** 253 * PAC manager has received new port. 254 */ 255 private static final int EVENT_PROXY_HAS_CHANGED = 16; 256 257 /** 258 * used internally when registering NetworkFactories 259 * obj = NetworkFactoryInfo 260 */ 261 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17; 262 263 /** 264 * used internally when registering NetworkAgents 265 * obj = Messenger 266 */ 267 private static final int EVENT_REGISTER_NETWORK_AGENT = 18; 268 269 /** 270 * used to add a network request 271 * includes a NetworkRequestInfo 272 */ 273 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19; 274 275 /** 276 * indicates a timeout period is over - check if we had a network yet or not 277 * and if not, call the timeout calback (but leave the request live until they 278 * cancel it. 279 * includes a NetworkRequestInfo 280 */ 281 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20; 282 283 /** 284 * used to add a network listener - no request 285 * includes a NetworkRequestInfo 286 */ 287 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21; 288 289 /** 290 * used to remove a network request, either a listener or a real request 291 * arg1 = UID of caller 292 * obj = NetworkRequest 293 */ 294 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22; 295 296 /** 297 * used internally when registering NetworkFactories 298 * obj = Messenger 299 */ 300 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23; 301 302 /** 303 * used internally to expire a wakelock when transitioning 304 * from one net to another. Expire happens when we fail to find 305 * a new network (typically after 1 minute) - 306 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found 307 * a replacement network. 308 */ 309 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24; 310 311 /** 312 * Used internally to indicate the system is ready. 313 */ 314 private static final int EVENT_SYSTEM_READY = 25; 315 316 /** 317 * used to add a network request with a pending intent 318 * includes a NetworkRequestInfo 319 */ 320 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26; 321 322 /** 323 * used to remove a pending intent and its associated network request. 324 * arg1 = UID of caller 325 * obj = PendingIntent 326 */ 327 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27; 328 329 330 /** Handler used for internal events. */ 331 final private InternalHandler mHandler; 332 /** Handler used for incoming {@link NetworkStateTracker} events. */ 333 final private NetworkStateTrackerHandler mTrackerHandler; 334 335 private boolean mSystemReady; 336 private Intent mInitialBroadcast; 337 338 private PowerManager.WakeLock mNetTransitionWakeLock; 339 private String mNetTransitionWakeLockCausedBy = ""; 340 private int mNetTransitionWakeLockSerialNumber; 341 private int mNetTransitionWakeLockTimeout; 342 private final PowerManager.WakeLock mPendingIntentWakeLock; 343 344 private InetAddress mDefaultDns; 345 346 // used in DBG mode to track inet condition reports 347 private static final int INET_CONDITION_LOG_MAX_SIZE = 15; 348 private ArrayList mInetLog; 349 350 // track the current default http proxy - tell the world if we get a new one (real change) 351 private volatile ProxyInfo mDefaultProxy = null; 352 private Object mProxyLock = new Object(); 353 private boolean mDefaultProxyDisabled = false; 354 355 // track the global proxy. 356 private ProxyInfo mGlobalProxy = null; 357 358 private PacManager mPacManager = null; 359 360 private SettingsObserver mSettingsObserver; 361 362 private UserManager mUserManager; 363 364 NetworkConfig[] mNetConfigs; 365 int mNetworksDefined; 366 367 // the set of network types that can only be enabled by system/sig apps 368 List mProtectedNetworks; 369 370 private DataConnectionStats mDataConnectionStats; 371 372 TelephonyManager mTelephonyManager; 373 374 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp 375 private final static int MIN_NET_ID = 100; // some reserved marks 376 private final static int MAX_NET_ID = 65535; 377 private int mNextNetId = MIN_NET_ID; 378 379 // sequence number of NetworkRequests 380 private int mNextNetworkRequestId = 1; 381 382 /** 383 * Implements support for the legacy "one network per network type" model. 384 * 385 * We used to have a static array of NetworkStateTrackers, one for each 386 * network type, but that doesn't work any more now that we can have, 387 * for example, more that one wifi network. This class stores all the 388 * NetworkAgentInfo objects that support a given type, but the legacy 389 * API will only see the first one. 390 * 391 * It serves two main purposes: 392 * 393 * 1. Provide information about "the network for a given type" (since this 394 * API only supports one). 395 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if 396 * the first network for a given type changes, or if the default network 397 * changes. 398 */ 399 private class LegacyTypeTracker { 400 401 private static final boolean DBG = true; 402 private static final boolean VDBG = false; 403 private static final String TAG = "CSLegacyTypeTracker"; 404 405 /** 406 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS). 407 * Each list holds references to all NetworkAgentInfos that are used to 408 * satisfy requests for that network type. 409 * 410 * This array is built out at startup such that an unsupported network 411 * doesn't get an ArrayList instance, making this a tristate: 412 * unsupported, supported but not active and active. 413 * 414 * The actual lists are populated when we scan the network types that 415 * are supported on this device. 416 */ 417 private ArrayList<NetworkAgentInfo> mTypeLists[]; 418 419 public LegacyTypeTracker() { 420 mTypeLists = (ArrayList<NetworkAgentInfo>[]) 421 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1]; 422 } 423 424 public void addSupportedType(int type) { 425 if (mTypeLists[type] != null) { 426 throw new IllegalStateException( 427 "legacy list for type " + type + "already initialized"); 428 } 429 mTypeLists[type] = new ArrayList<NetworkAgentInfo>(); 430 } 431 432 public boolean isTypeSupported(int type) { 433 return isNetworkTypeValid(type) && mTypeLists[type] != null; 434 } 435 436 public NetworkAgentInfo getNetworkForType(int type) { 437 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) { 438 return mTypeLists[type].get(0); 439 } else { 440 return null; 441 } 442 } 443 444 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type) { 445 if (DBG) { 446 log("Sending " + (connected ? "connected" : "disconnected") + 447 " broadcast for type " + type + " " + nai.name() + 448 " isDefaultNetwork=" + isDefaultNetwork(nai)); 449 } 450 } 451 452 /** Adds the given network to the specified legacy type list. */ 453 public void add(int type, NetworkAgentInfo nai) { 454 if (!isTypeSupported(type)) { 455 return; // Invalid network type. 456 } 457 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type); 458 459 ArrayList<NetworkAgentInfo> list = mTypeLists[type]; 460 if (list.contains(nai)) { 461 loge("Attempting to register duplicate agent for type " + type + ": " + nai); 462 return; 463 } 464 465 list.add(nai); 466 467 // Send a broadcast if this is the first network of its type or if it's the default. 468 if (list.size() == 1 || isDefaultNetwork(nai)) { 469 maybeLogBroadcast(nai, true, type); 470 sendLegacyNetworkBroadcast(nai, true, type); 471 } 472 } 473 474 /** Removes the given network from the specified legacy type list. */ 475 public void remove(int type, NetworkAgentInfo nai) { 476 ArrayList<NetworkAgentInfo> list = mTypeLists[type]; 477 if (list == null || list.isEmpty()) { 478 return; 479 } 480 481 boolean wasFirstNetwork = list.get(0).equals(nai); 482 483 if (!list.remove(nai)) { 484 return; 485 } 486 487 if (wasFirstNetwork || isDefaultNetwork(nai)) { 488 maybeLogBroadcast(nai, false, type); 489 sendLegacyNetworkBroadcast(nai, false, type); 490 } 491 492 if (!list.isEmpty() && wasFirstNetwork) { 493 if (DBG) log("Other network available for type " + type + 494 ", sending connected broadcast"); 495 maybeLogBroadcast(list.get(0), false, type); 496 sendLegacyNetworkBroadcast(list.get(0), false, type); 497 } 498 } 499 500 /** Removes the given network from all legacy type lists. */ 501 public void remove(NetworkAgentInfo nai) { 502 if (VDBG) log("Removing agent " + nai); 503 for (int type = 0; type < mTypeLists.length; type++) { 504 remove(type, nai); 505 } 506 } 507 508 private String naiToString(NetworkAgentInfo nai) { 509 String name = (nai != null) ? nai.name() : "null"; 510 String state = (nai.networkInfo != null) ? 511 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() : 512 "???/???"; 513 return name + " " + state; 514 } 515 516 public void dump(IndentingPrintWriter pw) { 517 for (int type = 0; type < mTypeLists.length; type++) { 518 if (mTypeLists[type] == null) continue; 519 pw.print(type + " "); 520 pw.increaseIndent(); 521 if (mTypeLists[type].size() == 0) pw.println("none"); 522 for (NetworkAgentInfo nai : mTypeLists[type]) { 523 pw.println(naiToString(nai)); 524 } 525 pw.decreaseIndent(); 526 } 527 } 528 529 // This class needs its own log method because it has a different TAG. 530 private void log(String s) { 531 Slog.d(TAG, s); 532 } 533 534 } 535 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(); 536 537 public ConnectivityService(Context context, INetworkManagementService netManager, 538 INetworkStatsService statsService, INetworkPolicyManager policyManager) { 539 if (DBG) log("ConnectivityService starting up"); 540 541 NetworkCapabilities netCap = new NetworkCapabilities(); 542 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); 543 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED); 544 mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId()); 545 NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(), 546 NetworkRequestInfo.REQUEST); 547 mNetworkRequests.put(mDefaultRequest, nri); 548 549 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread"); 550 handlerThread.start(); 551 mHandler = new InternalHandler(handlerThread.getLooper()); 552 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper()); 553 554 // setup our unique device name 555 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) { 556 String id = Settings.Secure.getString(context.getContentResolver(), 557 Settings.Secure.ANDROID_ID); 558 if (id != null && id.length() > 0) { 559 String name = new String("android-").concat(id); 560 SystemProperties.set("net.hostname", name); 561 } 562 } 563 564 // read our default dns server ip 565 String dns = Settings.Global.getString(context.getContentResolver(), 566 Settings.Global.DEFAULT_DNS_SERVER); 567 if (dns == null || dns.length() == 0) { 568 dns = context.getResources().getString( 569 com.android.internal.R.string.config_default_dns_server); 570 } 571 try { 572 mDefaultDns = NetworkUtils.numericToInetAddress(dns); 573 } catch (IllegalArgumentException e) { 574 loge("Error setting defaultDns using " + dns); 575 } 576 577 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(), 578 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000); 579 580 mContext = checkNotNull(context, "missing Context"); 581 mNetd = checkNotNull(netManager, "missing INetworkManagementService"); 582 mStatsService = checkNotNull(statsService, "missing INetworkStatsService"); 583 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager"); 584 mKeyStore = KeyStore.getInstance(); 585 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); 586 587 try { 588 mPolicyManager.registerListener(mPolicyListener); 589 } catch (RemoteException e) { 590 // ouch, no rules updates means some processes may never get network 591 loge("unable to register INetworkPolicyListener" + e.toString()); 592 } 593 594 final PowerManager powerManager = (PowerManager) context.getSystemService( 595 Context.POWER_SERVICE); 596 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); 597 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger( 598 com.android.internal.R.integer.config_networkTransitionTimeout); 599 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); 600 601 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1]; 602 603 // TODO: What is the "correct" way to do determine if this is a wifi only device? 604 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false); 605 log("wifiOnly=" + wifiOnly); 606 String[] naStrings = context.getResources().getStringArray( 607 com.android.internal.R.array.networkAttributes); 608 for (String naString : naStrings) { 609 try { 610 NetworkConfig n = new NetworkConfig(naString); 611 if (VDBG) log("naString=" + naString + " config=" + n); 612 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) { 613 loge("Error in networkAttributes - ignoring attempt to define type " + 614 n.type); 615 continue; 616 } 617 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) { 618 log("networkAttributes - ignoring mobile as this dev is wifiOnly " + 619 n.type); 620 continue; 621 } 622 if (mNetConfigs[n.type] != null) { 623 loge("Error in networkAttributes - ignoring attempt to redefine type " + 624 n.type); 625 continue; 626 } 627 mLegacyTypeTracker.addSupportedType(n.type); 628 629 mNetConfigs[n.type] = n; 630 mNetworksDefined++; 631 } catch(Exception e) { 632 // ignore it - leave the entry null 633 } 634 } 635 636 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config. 637 if (mNetConfigs[TYPE_VPN] == null) { 638 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we 639 // don't need to add TYPE_VPN to mNetConfigs. 640 mLegacyTypeTracker.addSupportedType(TYPE_VPN); 641 mNetworksDefined++; // used only in the log() statement below. 642 } 643 644 if (VDBG) log("mNetworksDefined=" + mNetworksDefined); 645 646 mProtectedNetworks = new ArrayList<Integer>(); 647 int[] protectedNetworks = context.getResources().getIntArray( 648 com.android.internal.R.array.config_protectedNetworks); 649 for (int p : protectedNetworks) { 650 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) { 651 mProtectedNetworks.add(p); 652 } else { 653 if (DBG) loge("Ignoring protectedNetwork " + p); 654 } 655 } 656 657 mTestMode = SystemProperties.get("cm.test.mode").equals("true") 658 && SystemProperties.get("ro.build.type").equals("eng"); 659 660 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper()); 661 662 mPermissionMonitor = new PermissionMonitor(mContext, mNetd); 663 664 //set up the listener for user state for creating user VPNs 665 IntentFilter intentFilter = new IntentFilter(); 666 intentFilter.addAction(Intent.ACTION_USER_STARTING); 667 intentFilter.addAction(Intent.ACTION_USER_STOPPING); 668 mContext.registerReceiverAsUser( 669 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null); 670 671 try { 672 mNetd.registerObserver(mTethering); 673 mNetd.registerObserver(mDataActivityObserver); 674 } catch (RemoteException e) { 675 loge("Error registering observer :" + e); 676 } 677 678 if (DBG) { 679 mInetLog = new ArrayList(); 680 } 681 682 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY); 683 mSettingsObserver.observe(mContext); 684 685 mDataConnectionStats = new DataConnectionStats(mContext); 686 mDataConnectionStats.startMonitoring(); 687 688 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED); 689 690 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE); 691 } 692 693 private synchronized int nextNetworkRequestId() { 694 return mNextNetworkRequestId++; 695 } 696 697 private int reserveNetId() { 698 synchronized (mNetworkForNetId) { 699 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) { 700 int netId = mNextNetId; 701 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID; 702 // Make sure NetID unused. http://b/16815182 703 if (!mNetIdInUse.get(netId)) { 704 mNetIdInUse.put(netId, true); 705 return netId; 706 } 707 } 708 } 709 throw new IllegalStateException("No free netIds"); 710 } 711 712 private NetworkState getFilteredNetworkState(int networkType, int uid) { 713 NetworkInfo info = null; 714 LinkProperties lp = null; 715 NetworkCapabilities nc = null; 716 Network network = null; 717 String subscriberId = null; 718 719 if (mLegacyTypeTracker.isTypeSupported(networkType)) { 720 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 721 if (nai != null) { 722 synchronized (nai) { 723 info = new NetworkInfo(nai.networkInfo); 724 lp = new LinkProperties(nai.linkProperties); 725 nc = new NetworkCapabilities(nai.networkCapabilities); 726 // Network objects are outwardly immutable so there is no point to duplicating. 727 // Duplicating also precludes sharing socket factories and connection pools. 728 network = nai.network; 729 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null; 730 } 731 info.setType(networkType); 732 } else { 733 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), ""); 734 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null); 735 info.setIsAvailable(true); 736 lp = new LinkProperties(); 737 nc = new NetworkCapabilities(); 738 network = null; 739 } 740 info = getFilteredNetworkInfo(info, lp, uid); 741 } 742 743 return new NetworkState(info, lp, nc, network, subscriberId, null); 744 } 745 746 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) { 747 if (network == null) { 748 return null; 749 } 750 synchronized (mNetworkForNetId) { 751 return mNetworkForNetId.get(network.netId); 752 } 753 }; 754 755 private Network[] getVpnUnderlyingNetworks(int uid) { 756 if (!mLockdownEnabled) { 757 int user = UserHandle.getUserId(uid); 758 synchronized (mVpns) { 759 Vpn vpn = mVpns.get(user); 760 if (vpn != null && vpn.appliesToUid(uid)) { 761 return vpn.getUnderlyingNetworks(); 762 } 763 } 764 } 765 return null; 766 } 767 768 private NetworkState getUnfilteredActiveNetworkState(int uid) { 769 NetworkInfo info = null; 770 LinkProperties lp = null; 771 NetworkCapabilities nc = null; 772 Network network = null; 773 String subscriberId = null; 774 775 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId); 776 777 final Network[] networks = getVpnUnderlyingNetworks(uid); 778 if (networks != null) { 779 // getUnderlyingNetworks() returns: 780 // null => there was no VPN, or the VPN didn't specify anything, so we use the default. 781 // empty array => the VPN explicitly said "no default network". 782 // non-empty array => the VPN specified one or more default networks; we use the 783 // first one. 784 if (networks.length > 0) { 785 nai = getNetworkAgentInfoForNetwork(networks[0]); 786 } else { 787 nai = null; 788 } 789 } 790 791 if (nai != null) { 792 synchronized (nai) { 793 info = new NetworkInfo(nai.networkInfo); 794 lp = new LinkProperties(nai.linkProperties); 795 nc = new NetworkCapabilities(nai.networkCapabilities); 796 // Network objects are outwardly immutable so there is no point to duplicating. 797 // Duplicating also precludes sharing socket factories and connection pools. 798 network = nai.network; 799 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null; 800 } 801 } 802 803 return new NetworkState(info, lp, nc, network, subscriberId, null); 804 } 805 806 /** 807 * Check if UID should be blocked from using the network with the given LinkProperties. 808 */ 809 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) { 810 final boolean networkCostly; 811 final int uidRules; 812 813 final String iface = (lp == null ? "" : lp.getInterfaceName()); 814 synchronized (mRulesLock) { 815 networkCostly = mMeteredIfaces.contains(iface); 816 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL); 817 } 818 819 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) { 820 return true; 821 } 822 823 // no restrictive rules; network is visible 824 return false; 825 } 826 827 /** 828 * Return a filtered {@link NetworkInfo}, potentially marked 829 * {@link DetailedState#BLOCKED} based on 830 * {@link #isNetworkWithLinkPropertiesBlocked}. 831 */ 832 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) { 833 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) { 834 // network is blocked; clone and override state 835 info = new NetworkInfo(info); 836 info.setDetailedState(DetailedState.BLOCKED, null, null); 837 if (DBG) { 838 log("returning Blocked NetworkInfo for ifname=" + 839 lp.getInterfaceName() + ", uid=" + uid); 840 } 841 } 842 if (info != null && mLockdownTracker != null) { 843 info = mLockdownTracker.augmentNetworkInfo(info); 844 if (DBG) log("returning Locked NetworkInfo"); 845 } 846 return info; 847 } 848 849 /** 850 * Return NetworkInfo for the active (i.e., connected) network interface. 851 * It is assumed that at most one network is active at a time. If more 852 * than one is active, it is indeterminate which will be returned. 853 * @return the info for the active network, or {@code null} if none is 854 * active 855 */ 856 @Override 857 public NetworkInfo getActiveNetworkInfo() { 858 enforceAccessPermission(); 859 final int uid = Binder.getCallingUid(); 860 NetworkState state = getUnfilteredActiveNetworkState(uid); 861 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid); 862 } 863 864 @Override 865 public Network getActiveNetwork() { 866 enforceAccessPermission(); 867 final int uid = Binder.getCallingUid(); 868 final int user = UserHandle.getUserId(uid); 869 int vpnNetId = NETID_UNSET; 870 synchronized (mVpns) { 871 final Vpn vpn = mVpns.get(user); 872 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId(); 873 } 874 NetworkAgentInfo nai; 875 if (vpnNetId != NETID_UNSET) { 876 synchronized (mNetworkForNetId) { 877 nai = mNetworkForNetId.get(vpnNetId); 878 } 879 if (nai != null) return nai.network; 880 } 881 nai = getDefaultNetwork(); 882 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null; 883 return nai != null ? nai.network : null; 884 } 885 886 /** 887 * Find the first Provisioning network. 888 * 889 * @return NetworkInfo or null if none. 890 */ 891 private NetworkInfo getProvisioningNetworkInfo() { 892 enforceAccessPermission(); 893 894 // Find the first Provisioning Network 895 NetworkInfo provNi = null; 896 for (NetworkInfo ni : getAllNetworkInfo()) { 897 if (ni.isConnectedToProvisioningNetwork()) { 898 provNi = ni; 899 break; 900 } 901 } 902 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi); 903 return provNi; 904 } 905 906 /** 907 * Find the first Provisioning network or the ActiveDefaultNetwork 908 * if there is no Provisioning network 909 * 910 * @return NetworkInfo or null if none. 911 */ 912 @Override 913 public NetworkInfo getProvisioningOrActiveNetworkInfo() { 914 enforceAccessPermission(); 915 916 NetworkInfo provNi = getProvisioningNetworkInfo(); 917 if (provNi == null) { 918 provNi = getActiveNetworkInfo(); 919 } 920 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi); 921 return provNi; 922 } 923 924 public NetworkInfo getActiveNetworkInfoUnfiltered() { 925 enforceAccessPermission(); 926 final int uid = Binder.getCallingUid(); 927 NetworkState state = getUnfilteredActiveNetworkState(uid); 928 return state.networkInfo; 929 } 930 931 @Override 932 public NetworkInfo getActiveNetworkInfoForUid(int uid) { 933 enforceConnectivityInternalPermission(); 934 NetworkState state = getUnfilteredActiveNetworkState(uid); 935 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid); 936 } 937 938 @Override 939 public NetworkInfo getNetworkInfo(int networkType) { 940 enforceAccessPermission(); 941 final int uid = Binder.getCallingUid(); 942 if (getVpnUnderlyingNetworks(uid) != null) { 943 // A VPN is active, so we may need to return one of its underlying networks. This 944 // information is not available in LegacyTypeTracker, so we have to get it from 945 // getUnfilteredActiveNetworkState. 946 NetworkState state = getUnfilteredActiveNetworkState(uid); 947 if (state.networkInfo != null && state.networkInfo.getType() == networkType) { 948 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid); 949 } 950 } 951 NetworkState state = getFilteredNetworkState(networkType, uid); 952 return state.networkInfo; 953 } 954 955 @Override 956 public NetworkInfo getNetworkInfoForNetwork(Network network) { 957 enforceAccessPermission(); 958 final int uid = Binder.getCallingUid(); 959 NetworkInfo info = null; 960 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 961 if (nai != null) { 962 synchronized (nai) { 963 info = new NetworkInfo(nai.networkInfo); 964 info = getFilteredNetworkInfo(info, nai.linkProperties, uid); 965 } 966 } 967 return info; 968 } 969 970 @Override 971 public NetworkInfo[] getAllNetworkInfo() { 972 enforceAccessPermission(); 973 final ArrayList<NetworkInfo> result = Lists.newArrayList(); 974 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE; 975 networkType++) { 976 NetworkInfo info = getNetworkInfo(networkType); 977 if (info != null) { 978 result.add(info); 979 } 980 } 981 return result.toArray(new NetworkInfo[result.size()]); 982 } 983 984 @Override 985 public Network getNetworkForType(int networkType) { 986 enforceAccessPermission(); 987 final int uid = Binder.getCallingUid(); 988 NetworkState state = getFilteredNetworkState(networkType, uid); 989 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) { 990 return state.network; 991 } 992 return null; 993 } 994 995 @Override 996 public Network[] getAllNetworks() { 997 enforceAccessPermission(); 998 synchronized (mNetworkForNetId) { 999 final Network[] result = new Network[mNetworkForNetId.size()]; 1000 for (int i = 0; i < mNetworkForNetId.size(); i++) { 1001 result[i] = mNetworkForNetId.valueAt(i).network; 1002 } 1003 return result; 1004 } 1005 } 1006 1007 private NetworkCapabilities getNetworkCapabilitiesAndValidation(NetworkAgentInfo nai) { 1008 if (nai != null) { 1009 synchronized (nai) { 1010 if (nai.created) { 1011 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities); 1012 if (nai.lastValidated) { 1013 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED); 1014 } else { 1015 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED); 1016 } 1017 return nc; 1018 } 1019 } 1020 } 1021 return null; 1022 } 1023 1024 @Override 1025 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) { 1026 // The basic principle is: if an app's traffic could possibly go over a 1027 // network, without the app doing anything multinetwork-specific, 1028 // (hence, by "default"), then include that network's capabilities in 1029 // the array. 1030 // 1031 // In the normal case, app traffic only goes over the system's default 1032 // network connection, so that's the only network returned. 1033 // 1034 // With a VPN in force, some app traffic may go into the VPN, and thus 1035 // over whatever underlying networks the VPN specifies, while other app 1036 // traffic may go over the system default network (e.g.: a split-tunnel 1037 // VPN, or an app disallowed by the VPN), so the set of networks 1038 // returned includes the VPN's underlying networks and the system 1039 // default. 1040 enforceAccessPermission(); 1041 1042 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>(); 1043 1044 NetworkAgentInfo nai = getDefaultNetwork(); 1045 NetworkCapabilities nc = getNetworkCapabilitiesAndValidation(getDefaultNetwork()); 1046 if (nc != null) { 1047 result.put(nai.network, nc); 1048 } 1049 1050 if (!mLockdownEnabled) { 1051 synchronized (mVpns) { 1052 Vpn vpn = mVpns.get(userId); 1053 if (vpn != null) { 1054 Network[] networks = vpn.getUnderlyingNetworks(); 1055 if (networks != null) { 1056 for (Network network : networks) { 1057 nai = getNetworkAgentInfoForNetwork(network); 1058 nc = getNetworkCapabilitiesAndValidation(nai); 1059 if (nc != null) { 1060 result.put(nai.network, nc); 1061 } 1062 } 1063 } 1064 } 1065 } 1066 } 1067 1068 NetworkCapabilities[] out = new NetworkCapabilities[result.size()]; 1069 out = result.values().toArray(out); 1070 return out; 1071 } 1072 1073 @Override 1074 public boolean isNetworkSupported(int networkType) { 1075 enforceAccessPermission(); 1076 return mLegacyTypeTracker.isTypeSupported(networkType); 1077 } 1078 1079 /** 1080 * Return LinkProperties for the active (i.e., connected) default 1081 * network interface. It is assumed that at most one default network 1082 * is active at a time. If more than one is active, it is indeterminate 1083 * which will be returned. 1084 * @return the ip properties for the active network, or {@code null} if 1085 * none is active 1086 */ 1087 @Override 1088 public LinkProperties getActiveLinkProperties() { 1089 enforceAccessPermission(); 1090 final int uid = Binder.getCallingUid(); 1091 NetworkState state = getUnfilteredActiveNetworkState(uid); 1092 return state.linkProperties; 1093 } 1094 1095 @Override 1096 public LinkProperties getLinkPropertiesForType(int networkType) { 1097 enforceAccessPermission(); 1098 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 1099 if (nai != null) { 1100 synchronized (nai) { 1101 return new LinkProperties(nai.linkProperties); 1102 } 1103 } 1104 return null; 1105 } 1106 1107 // TODO - this should be ALL networks 1108 @Override 1109 public LinkProperties getLinkProperties(Network network) { 1110 enforceAccessPermission(); 1111 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 1112 if (nai != null) { 1113 synchronized (nai) { 1114 return new LinkProperties(nai.linkProperties); 1115 } 1116 } 1117 return null; 1118 } 1119 1120 @Override 1121 public NetworkCapabilities getNetworkCapabilities(Network network) { 1122 enforceAccessPermission(); 1123 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 1124 if (nai != null) { 1125 synchronized (nai) { 1126 return new NetworkCapabilities(nai.networkCapabilities); 1127 } 1128 } 1129 return null; 1130 } 1131 1132 @Override 1133 public NetworkState[] getAllNetworkState() { 1134 // Require internal since we're handing out IMSI details 1135 enforceConnectivityInternalPermission(); 1136 1137 final ArrayList<NetworkState> result = Lists.newArrayList(); 1138 for (Network network : getAllNetworks()) { 1139 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network); 1140 if (nai != null) { 1141 synchronized (nai) { 1142 final String subscriberId = (nai.networkMisc != null) 1143 ? nai.networkMisc.subscriberId : null; 1144 result.add(new NetworkState(nai.networkInfo, nai.linkProperties, 1145 nai.networkCapabilities, network, subscriberId, null)); 1146 } 1147 } 1148 } 1149 return result.toArray(new NetworkState[result.size()]); 1150 } 1151 1152 @Override 1153 public NetworkQuotaInfo getActiveNetworkQuotaInfo() { 1154 enforceAccessPermission(); 1155 final int uid = Binder.getCallingUid(); 1156 final long token = Binder.clearCallingIdentity(); 1157 try { 1158 final NetworkState state = getUnfilteredActiveNetworkState(uid); 1159 if (state.networkInfo != null) { 1160 try { 1161 return mPolicyManager.getNetworkQuotaInfo(state); 1162 } catch (RemoteException e) { 1163 } 1164 } 1165 return null; 1166 } finally { 1167 Binder.restoreCallingIdentity(token); 1168 } 1169 } 1170 1171 @Override 1172 public boolean isActiveNetworkMetered() { 1173 enforceAccessPermission(); 1174 final int uid = Binder.getCallingUid(); 1175 final long token = Binder.clearCallingIdentity(); 1176 try { 1177 return isActiveNetworkMeteredUnchecked(uid); 1178 } finally { 1179 Binder.restoreCallingIdentity(token); 1180 } 1181 } 1182 1183 private boolean isActiveNetworkMeteredUnchecked(int uid) { 1184 final NetworkState state = getUnfilteredActiveNetworkState(uid); 1185 if (state.networkInfo != null) { 1186 try { 1187 return mPolicyManager.isNetworkMetered(state); 1188 } catch (RemoteException e) { 1189 } 1190 } 1191 return false; 1192 } 1193 1194 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() { 1195 @Override 1196 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) { 1197 int deviceType = Integer.parseInt(label); 1198 sendDataActivityBroadcast(deviceType, active, tsNanos); 1199 } 1200 }; 1201 1202 /** 1203 * Ensure that a network route exists to deliver traffic to the specified 1204 * host via the specified network interface. 1205 * @param networkType the type of the network over which traffic to the 1206 * specified host is to be routed 1207 * @param hostAddress the IP address of the host to which the route is 1208 * desired 1209 * @return {@code true} on success, {@code false} on failure 1210 */ 1211 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) { 1212 enforceChangePermission(); 1213 if (mProtectedNetworks.contains(networkType)) { 1214 enforceConnectivityInternalPermission(); 1215 } 1216 1217 InetAddress addr; 1218 try { 1219 addr = InetAddress.getByAddress(hostAddress); 1220 } catch (UnknownHostException e) { 1221 if (DBG) log("requestRouteToHostAddress got " + e.toString()); 1222 return false; 1223 } 1224 1225 if (!ConnectivityManager.isNetworkTypeValid(networkType)) { 1226 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType); 1227 return false; 1228 } 1229 1230 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 1231 if (nai == null) { 1232 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) { 1233 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType); 1234 } else { 1235 if (DBG) log("requestRouteToHostAddress on down network: " + networkType); 1236 } 1237 return false; 1238 } 1239 1240 DetailedState netState; 1241 synchronized (nai) { 1242 netState = nai.networkInfo.getDetailedState(); 1243 } 1244 1245 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) { 1246 if (VDBG) { 1247 log("requestRouteToHostAddress on down network " 1248 + "(" + networkType + ") - dropped" 1249 + " netState=" + netState); 1250 } 1251 return false; 1252 } 1253 1254 final int uid = Binder.getCallingUid(); 1255 final long token = Binder.clearCallingIdentity(); 1256 try { 1257 LinkProperties lp; 1258 int netId; 1259 synchronized (nai) { 1260 lp = nai.linkProperties; 1261 netId = nai.network.netId; 1262 } 1263 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid); 1264 if (DBG) log("requestRouteToHostAddress ok=" + ok); 1265 return ok; 1266 } finally { 1267 Binder.restoreCallingIdentity(token); 1268 } 1269 } 1270 1271 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) { 1272 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr); 1273 if (bestRoute == null) { 1274 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName()); 1275 } else { 1276 String iface = bestRoute.getInterface(); 1277 if (bestRoute.getGateway().equals(addr)) { 1278 // if there is no better route, add the implied hostroute for our gateway 1279 bestRoute = RouteInfo.makeHostRoute(addr, iface); 1280 } else { 1281 // if we will connect to this through another route, add a direct route 1282 // to it's gateway 1283 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface); 1284 } 1285 } 1286 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface()); 1287 try { 1288 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid); 1289 } catch (Exception e) { 1290 // never crash - catch them all 1291 if (DBG) loge("Exception trying to add a route: " + e); 1292 return false; 1293 } 1294 return true; 1295 } 1296 1297 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() { 1298 @Override 1299 public void onUidRulesChanged(int uid, int uidRules) { 1300 // caller is NPMS, since we only register with them 1301 if (LOGD_RULES) { 1302 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")"); 1303 } 1304 1305 synchronized (mRulesLock) { 1306 // skip update when we've already applied rules 1307 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL); 1308 if (oldRules == uidRules) return; 1309 1310 mUidRules.put(uid, uidRules); 1311 } 1312 1313 // TODO: notify UID when it has requested targeted updates 1314 } 1315 1316 @Override 1317 public void onMeteredIfacesChanged(String[] meteredIfaces) { 1318 // caller is NPMS, since we only register with them 1319 if (LOGD_RULES) { 1320 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")"); 1321 } 1322 1323 synchronized (mRulesLock) { 1324 mMeteredIfaces.clear(); 1325 for (String iface : meteredIfaces) { 1326 mMeteredIfaces.add(iface); 1327 } 1328 } 1329 } 1330 1331 @Override 1332 public void onRestrictBackgroundChanged(boolean restrictBackground) { 1333 // caller is NPMS, since we only register with them 1334 if (LOGD_RULES) { 1335 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")"); 1336 } 1337 } 1338 }; 1339 1340 private void enforceInternetPermission() { 1341 mContext.enforceCallingOrSelfPermission( 1342 android.Manifest.permission.INTERNET, 1343 "ConnectivityService"); 1344 } 1345 1346 private void enforceAccessPermission() { 1347 mContext.enforceCallingOrSelfPermission( 1348 android.Manifest.permission.ACCESS_NETWORK_STATE, 1349 "ConnectivityService"); 1350 } 1351 1352 private void enforceChangePermission() { 1353 mContext.enforceCallingOrSelfPermission( 1354 android.Manifest.permission.CHANGE_NETWORK_STATE, 1355 "ConnectivityService"); 1356 } 1357 1358 private void enforceTetherAccessPermission() { 1359 mContext.enforceCallingOrSelfPermission( 1360 android.Manifest.permission.ACCESS_NETWORK_STATE, 1361 "ConnectivityService"); 1362 } 1363 1364 private void enforceConnectivityInternalPermission() { 1365 mContext.enforceCallingOrSelfPermission( 1366 android.Manifest.permission.CONNECTIVITY_INTERNAL, 1367 "ConnectivityService"); 1368 } 1369 1370 public void sendConnectedBroadcast(NetworkInfo info) { 1371 enforceConnectivityInternalPermission(); 1372 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE); 1373 sendGeneralBroadcast(info, CONNECTIVITY_ACTION); 1374 } 1375 1376 private void sendInetConditionBroadcast(NetworkInfo info) { 1377 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION); 1378 } 1379 1380 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) { 1381 if (mLockdownTracker != null) { 1382 info = mLockdownTracker.augmentNetworkInfo(info); 1383 } 1384 1385 Intent intent = new Intent(bcastType); 1386 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info)); 1387 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 1388 if (info.isFailover()) { 1389 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 1390 info.setFailover(false); 1391 } 1392 if (info.getReason() != null) { 1393 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 1394 } 1395 if (info.getExtraInfo() != null) { 1396 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, 1397 info.getExtraInfo()); 1398 } 1399 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished); 1400 return intent; 1401 } 1402 1403 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) { 1404 sendStickyBroadcast(makeGeneralIntent(info, bcastType)); 1405 } 1406 1407 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) { 1408 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE); 1409 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType); 1410 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active); 1411 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos); 1412 final long ident = Binder.clearCallingIdentity(); 1413 try { 1414 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL, 1415 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null); 1416 } finally { 1417 Binder.restoreCallingIdentity(ident); 1418 } 1419 } 1420 1421 private void sendStickyBroadcast(Intent intent) { 1422 synchronized(this) { 1423 if (!mSystemReady) { 1424 mInitialBroadcast = new Intent(intent); 1425 } 1426 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1427 if (DBG) { 1428 log("sendStickyBroadcast: action=" + intent.getAction()); 1429 } 1430 1431 final long ident = Binder.clearCallingIdentity(); 1432 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { 1433 final IBatteryStats bs = BatteryStatsService.getService(); 1434 try { 1435 NetworkInfo ni = intent.getParcelableExtra( 1436 ConnectivityManager.EXTRA_NETWORK_INFO); 1437 bs.noteConnectivityChanged(intent.getIntExtra( 1438 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE), 1439 ni != null ? ni.getState().toString() : "?"); 1440 } catch (RemoteException e) { 1441 } 1442 } 1443 try { 1444 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 1445 } finally { 1446 Binder.restoreCallingIdentity(ident); 1447 } 1448 } 1449 } 1450 1451 void systemReady() { 1452 loadGlobalProxy(); 1453 1454 synchronized(this) { 1455 mSystemReady = true; 1456 if (mInitialBroadcast != null) { 1457 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL); 1458 mInitialBroadcast = null; 1459 } 1460 } 1461 // load the global proxy at startup 1462 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY)); 1463 1464 // Try bringing up tracker, but if KeyStore isn't ready yet, wait 1465 // for user to unlock device. 1466 if (!updateLockdownVpn()) { 1467 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT); 1468 mContext.registerReceiver(mUserPresentReceiver, filter); 1469 } 1470 1471 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY)); 1472 1473 mPermissionMonitor.startMonitoring(); 1474 } 1475 1476 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() { 1477 @Override 1478 public void onReceive(Context context, Intent intent) { 1479 // Try creating lockdown tracker, since user present usually means 1480 // unlocked keystore. 1481 if (updateLockdownVpn()) { 1482 mContext.unregisterReceiver(this); 1483 } 1484 } 1485 }; 1486 1487 /** @hide */ 1488 @Override 1489 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) { 1490 enforceConnectivityInternalPermission(); 1491 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal); 1492// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal); 1493 } 1494 1495 /** 1496 * Setup data activity tracking for the given network. 1497 * 1498 * Every {@code setupDataActivityTracking} should be paired with a 1499 * {@link #removeDataActivityTracking} for cleanup. 1500 */ 1501 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) { 1502 final String iface = networkAgent.linkProperties.getInterfaceName(); 1503 1504 final int timeout; 1505 int type = ConnectivityManager.TYPE_NONE; 1506 1507 if (networkAgent.networkCapabilities.hasTransport( 1508 NetworkCapabilities.TRANSPORT_CELLULAR)) { 1509 timeout = Settings.Global.getInt(mContext.getContentResolver(), 1510 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE, 1511 5); 1512 type = ConnectivityManager.TYPE_MOBILE; 1513 } else if (networkAgent.networkCapabilities.hasTransport( 1514 NetworkCapabilities.TRANSPORT_WIFI)) { 1515 timeout = Settings.Global.getInt(mContext.getContentResolver(), 1516 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI, 1517 5); 1518 type = ConnectivityManager.TYPE_WIFI; 1519 } else { 1520 // do not track any other networks 1521 timeout = 0; 1522 } 1523 1524 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) { 1525 try { 1526 mNetd.addIdleTimer(iface, timeout, type); 1527 } catch (Exception e) { 1528 // You shall not crash! 1529 loge("Exception in setupDataActivityTracking " + e); 1530 } 1531 } 1532 } 1533 1534 /** 1535 * Remove data activity tracking when network disconnects. 1536 */ 1537 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) { 1538 final String iface = networkAgent.linkProperties.getInterfaceName(); 1539 final NetworkCapabilities caps = networkAgent.networkCapabilities; 1540 1541 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || 1542 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) { 1543 try { 1544 // the call fails silently if no idletimer setup for this interface 1545 mNetd.removeIdleTimer(iface); 1546 } catch (Exception e) { 1547 loge("Exception in removeDataActivityTracking " + e); 1548 } 1549 } 1550 } 1551 1552 /** 1553 * Reads the network specific MTU size from reources. 1554 * and set it on it's iface. 1555 */ 1556 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) { 1557 final String iface = newLp.getInterfaceName(); 1558 final int mtu = newLp.getMtu(); 1559 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) { 1560 if (VDBG) log("identical MTU - not setting"); 1561 return; 1562 } 1563 1564 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) { 1565 loge("Unexpected mtu value: " + mtu + ", " + iface); 1566 return; 1567 } 1568 1569 // Cannot set MTU without interface name 1570 if (TextUtils.isEmpty(iface)) { 1571 loge("Setting MTU size with null iface."); 1572 return; 1573 } 1574 1575 try { 1576 if (DBG) log("Setting MTU size: " + iface + ", " + mtu); 1577 mNetd.setMtu(iface, mtu); 1578 } catch (Exception e) { 1579 Slog.e(TAG, "exception in setMtu()" + e); 1580 } 1581 } 1582 1583 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208"; 1584 1585 private void updateTcpBufferSizes(NetworkAgentInfo nai) { 1586 if (isDefaultNetwork(nai) == false) { 1587 return; 1588 } 1589 1590 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes(); 1591 String[] values = null; 1592 if (tcpBufferSizes != null) { 1593 values = tcpBufferSizes.split(","); 1594 } 1595 1596 if (values == null || values.length != 6) { 1597 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults"); 1598 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES; 1599 values = tcpBufferSizes.split(","); 1600 } 1601 1602 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return; 1603 1604 try { 1605 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes); 1606 1607 final String prefix = "/sys/kernel/ipv4/tcp_"; 1608 FileUtils.stringToFile(prefix + "rmem_min", values[0]); 1609 FileUtils.stringToFile(prefix + "rmem_def", values[1]); 1610 FileUtils.stringToFile(prefix + "rmem_max", values[2]); 1611 FileUtils.stringToFile(prefix + "wmem_min", values[3]); 1612 FileUtils.stringToFile(prefix + "wmem_def", values[4]); 1613 FileUtils.stringToFile(prefix + "wmem_max", values[5]); 1614 mCurrentTcpBufferSizes = tcpBufferSizes; 1615 } catch (IOException e) { 1616 loge("Can't set TCP buffer sizes:" + e); 1617 } 1618 1619 final String defaultRwndKey = "net.tcp.default_init_rwnd"; 1620 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0); 1621 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(), 1622 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue); 1623 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd"; 1624 if (rwndValue != 0) { 1625 SystemProperties.set(sysctlKey, rwndValue.toString()); 1626 } 1627 } 1628 1629 private void flushVmDnsCache() { 1630 /* 1631 * Tell the VMs to toss their DNS caches 1632 */ 1633 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE); 1634 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING); 1635 /* 1636 * Connectivity events can happen before boot has completed ... 1637 */ 1638 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1639 final long ident = Binder.clearCallingIdentity(); 1640 try { 1641 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 1642 } finally { 1643 Binder.restoreCallingIdentity(ident); 1644 } 1645 } 1646 1647 @Override 1648 public int getRestoreDefaultNetworkDelay(int networkType) { 1649 String restoreDefaultNetworkDelayStr = SystemProperties.get( 1650 NETWORK_RESTORE_DELAY_PROP_NAME); 1651 if(restoreDefaultNetworkDelayStr != null && 1652 restoreDefaultNetworkDelayStr.length() != 0) { 1653 try { 1654 return Integer.valueOf(restoreDefaultNetworkDelayStr); 1655 } catch (NumberFormatException e) { 1656 } 1657 } 1658 // if the system property isn't set, use the value for the apn type 1659 int ret = RESTORE_DEFAULT_NETWORK_DELAY; 1660 1661 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) && 1662 (mNetConfigs[networkType] != null)) { 1663 ret = mNetConfigs[networkType].restoreTime; 1664 } 1665 return ret; 1666 } 1667 1668 @Override 1669 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) { 1670 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); 1671 if (mContext.checkCallingOrSelfPermission( 1672 android.Manifest.permission.DUMP) 1673 != PackageManager.PERMISSION_GRANTED) { 1674 pw.println("Permission Denial: can't dump ConnectivityService " + 1675 "from from pid=" + Binder.getCallingPid() + ", uid=" + 1676 Binder.getCallingUid()); 1677 return; 1678 } 1679 1680 pw.println("NetworkFactories for:"); 1681 pw.increaseIndent(); 1682 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 1683 pw.println(nfi.name); 1684 } 1685 pw.decreaseIndent(); 1686 pw.println(); 1687 1688 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId); 1689 pw.print("Active default network: "); 1690 if (defaultNai == null) { 1691 pw.println("none"); 1692 } else { 1693 pw.println(defaultNai.network.netId); 1694 } 1695 pw.println(); 1696 1697 pw.println("Current Networks:"); 1698 pw.increaseIndent(); 1699 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 1700 pw.println(nai.toString()); 1701 pw.increaseIndent(); 1702 pw.println("Requests:"); 1703 pw.increaseIndent(); 1704 for (int i = 0; i < nai.networkRequests.size(); i++) { 1705 pw.println(nai.networkRequests.valueAt(i).toString()); 1706 } 1707 pw.decreaseIndent(); 1708 pw.println("Lingered:"); 1709 pw.increaseIndent(); 1710 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString()); 1711 pw.decreaseIndent(); 1712 pw.decreaseIndent(); 1713 } 1714 pw.decreaseIndent(); 1715 pw.println(); 1716 1717 pw.println("Network Requests:"); 1718 pw.increaseIndent(); 1719 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 1720 pw.println(nri.toString()); 1721 } 1722 pw.println(); 1723 pw.decreaseIndent(); 1724 1725 pw.println("mLegacyTypeTracker:"); 1726 pw.increaseIndent(); 1727 mLegacyTypeTracker.dump(pw); 1728 pw.decreaseIndent(); 1729 pw.println(); 1730 1731 synchronized (this) { 1732 pw.println("NetworkTransitionWakeLock is currently " + 1733 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held."); 1734 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy); 1735 } 1736 pw.println(); 1737 1738 mTethering.dump(fd, pw, args); 1739 1740 if (mInetLog != null) { 1741 pw.println(); 1742 pw.println("Inet condition reports:"); 1743 pw.increaseIndent(); 1744 for(int i = 0; i < mInetLog.size(); i++) { 1745 pw.println(mInetLog.get(i)); 1746 } 1747 pw.decreaseIndent(); 1748 } 1749 } 1750 1751 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) { 1752 if (nai.network == null) return false; 1753 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network); 1754 if (officialNai != null && officialNai.equals(nai)) return true; 1755 if (officialNai != null || VDBG) { 1756 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai + 1757 " - " + nai); 1758 } 1759 return false; 1760 } 1761 1762 private boolean isRequest(NetworkRequest request) { 1763 return mNetworkRequests.get(request).isRequest; 1764 } 1765 1766 // must be stateless - things change under us. 1767 private class NetworkStateTrackerHandler extends Handler { 1768 public NetworkStateTrackerHandler(Looper looper) { 1769 super(looper); 1770 } 1771 1772 @Override 1773 public void handleMessage(Message msg) { 1774 NetworkInfo info; 1775 switch (msg.what) { 1776 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: { 1777 handleAsyncChannelHalfConnect(msg); 1778 break; 1779 } 1780 case AsyncChannel.CMD_CHANNEL_DISCONNECT: { 1781 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 1782 if (nai != null) nai.asyncChannel.disconnect(); 1783 break; 1784 } 1785 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: { 1786 handleAsyncChannelDisconnected(msg); 1787 break; 1788 } 1789 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: { 1790 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 1791 if (nai == null) { 1792 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent"); 1793 } else { 1794 updateCapabilities(nai, (NetworkCapabilities)msg.obj); 1795 } 1796 break; 1797 } 1798 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: { 1799 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 1800 if (nai == null) { 1801 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED"); 1802 } else { 1803 if (VDBG) { 1804 log("Update of LinkProperties for " + nai.name() + 1805 "; created=" + nai.created); 1806 } 1807 LinkProperties oldLp = nai.linkProperties; 1808 synchronized (nai) { 1809 nai.linkProperties = (LinkProperties)msg.obj; 1810 } 1811 if (nai.created) updateLinkProperties(nai, oldLp); 1812 } 1813 break; 1814 } 1815 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: { 1816 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 1817 if (nai == null) { 1818 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent"); 1819 break; 1820 } 1821 info = (NetworkInfo) msg.obj; 1822 updateNetworkInfo(nai, info); 1823 break; 1824 } 1825 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: { 1826 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 1827 if (nai == null) { 1828 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent"); 1829 break; 1830 } 1831 Integer score = (Integer) msg.obj; 1832 if (score != null) updateNetworkScore(nai, score.intValue()); 1833 break; 1834 } 1835 case NetworkAgent.EVENT_UID_RANGES_ADDED: { 1836 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 1837 if (nai == null) { 1838 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent"); 1839 break; 1840 } 1841 try { 1842 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj); 1843 } catch (Exception e) { 1844 // Never crash! 1845 loge("Exception in addVpnUidRanges: " + e); 1846 } 1847 break; 1848 } 1849 case NetworkAgent.EVENT_UID_RANGES_REMOVED: { 1850 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 1851 if (nai == null) { 1852 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent"); 1853 break; 1854 } 1855 try { 1856 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj); 1857 } catch (Exception e) { 1858 // Never crash! 1859 loge("Exception in removeVpnUidRanges: " + e); 1860 } 1861 break; 1862 } 1863 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: { 1864 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 1865 if (nai == null) { 1866 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent"); 1867 break; 1868 } 1869 if (nai.created && !nai.networkMisc.explicitlySelected) { 1870 loge("ERROR: created network explicitly selected."); 1871 } 1872 nai.networkMisc.explicitlySelected = true; 1873 break; 1874 } 1875 case NetworkMonitor.EVENT_NETWORK_TESTED: { 1876 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj; 1877 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) { 1878 boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID); 1879 nai.lastValidated = valid; 1880 if (valid) { 1881 if (DBG) log("Validated " + nai.name()); 1882 if (!nai.everValidated) { 1883 nai.everValidated = true; 1884 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED, 1885 ReapUnvalidatedNetworks.REAP); 1886 // If score has changed, rebroadcast to NetworkFactories. b/17726566 1887 sendUpdatedScoreToFactories(nai); 1888 } 1889 } 1890 updateInetCondition(nai); 1891 // Let the NetworkAgent know the state of its network 1892 nai.asyncChannel.sendMessage( 1893 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS, 1894 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK), 1895 0, null); 1896 } 1897 break; 1898 } 1899 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: { 1900 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj; 1901 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) { 1902 handleLingerComplete(nai); 1903 } 1904 break; 1905 } 1906 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: { 1907 if (msg.arg1 == 0) { 1908 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null); 1909 } else { 1910 NetworkAgentInfo nai = null; 1911 synchronized (mNetworkForNetId) { 1912 nai = mNetworkForNetId.get(msg.arg2); 1913 } 1914 if (nai == null) { 1915 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor"); 1916 break; 1917 } 1918 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(), 1919 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj); 1920 } 1921 break; 1922 } 1923 } 1924 } 1925 } 1926 1927 // Cancel any lingering so the linger timeout doesn't teardown a network. 1928 // This should be called when a network begins satisfying a NetworkRequest. 1929 // Note: depending on what state the NetworkMonitor is in (e.g., 1930 // if it's awaiting captive portal login, or if validation failed), this 1931 // may trigger a re-evaluation of the network. 1932 private void unlinger(NetworkAgentInfo nai) { 1933 if (VDBG) log("Canceling linger of " + nai.name()); 1934 // If network has never been validated, it cannot have been lingered, so don't bother 1935 // needlessly triggering a re-evaluation. 1936 if (!nai.everValidated) return; 1937 nai.networkLingered.clear(); 1938 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 1939 } 1940 1941 private void handleAsyncChannelHalfConnect(Message msg) { 1942 AsyncChannel ac = (AsyncChannel) msg.obj; 1943 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) { 1944 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 1945 if (VDBG) log("NetworkFactory connected"); 1946 // A network factory has connected. Send it all current NetworkRequests. 1947 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 1948 if (nri.isRequest == false) continue; 1949 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId); 1950 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, 1951 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request); 1952 } 1953 } else { 1954 loge("Error connecting NetworkFactory"); 1955 mNetworkFactoryInfos.remove(msg.obj); 1956 } 1957 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) { 1958 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 1959 if (VDBG) log("NetworkAgent connected"); 1960 // A network agent has requested a connection. Establish the connection. 1961 mNetworkAgentInfos.get(msg.replyTo).asyncChannel. 1962 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION); 1963 } else { 1964 loge("Error connecting NetworkAgent"); 1965 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo); 1966 if (nai != null) { 1967 synchronized (mNetworkForNetId) { 1968 mNetworkForNetId.remove(nai.network.netId); 1969 mNetIdInUse.delete(nai.network.netId); 1970 } 1971 // Just in case. 1972 mLegacyTypeTracker.remove(nai); 1973 } 1974 } 1975 } 1976 } 1977 1978 private void handleAsyncChannelDisconnected(Message msg) { 1979 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo); 1980 if (nai != null) { 1981 if (DBG) { 1982 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size()); 1983 } 1984 // A network agent has disconnected. 1985 if (nai.created) { 1986 // Tell netd to clean up the configuration for this network 1987 // (routing rules, DNS, etc). 1988 try { 1989 mNetd.removeNetwork(nai.network.netId); 1990 } catch (Exception e) { 1991 loge("Exception removing network: " + e); 1992 } 1993 } 1994 // TODO - if we move the logic to the network agent (have them disconnect 1995 // because they lost all their requests or because their score isn't good) 1996 // then they would disconnect organically, report their new state and then 1997 // disconnect the channel. 1998 if (nai.networkInfo.isConnected()) { 1999 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, 2000 null, null); 2001 } 2002 if (isDefaultNetwork(nai)) { 2003 mDefaultInetConditionPublished = 0; 2004 } 2005 notifyIfacesChanged(); 2006 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST); 2007 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED); 2008 mNetworkAgentInfos.remove(msg.replyTo); 2009 updateClat(null, nai.linkProperties, nai); 2010 mLegacyTypeTracker.remove(nai); 2011 synchronized (mNetworkForNetId) { 2012 mNetworkForNetId.remove(nai.network.netId); 2013 mNetIdInUse.delete(nai.network.netId); 2014 } 2015 // Since we've lost the network, go through all the requests that 2016 // it was satisfying and see if any other factory can satisfy them. 2017 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests 2018 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>(); 2019 for (int i = 0; i < nai.networkRequests.size(); i++) { 2020 NetworkRequest request = nai.networkRequests.valueAt(i); 2021 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId); 2022 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) { 2023 if (DBG) { 2024 log("Checking for replacement network to handle request " + request ); 2025 } 2026 mNetworkForRequestId.remove(request.requestId); 2027 sendUpdatedScoreToFactories(request, 0); 2028 NetworkAgentInfo alternative = null; 2029 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) { 2030 if (existing.satisfies(request) && 2031 (alternative == null || 2032 alternative.getCurrentScore() < existing.getCurrentScore())) { 2033 alternative = existing; 2034 } 2035 } 2036 if (alternative != null) { 2037 if (DBG) log(" found replacement in " + alternative.name()); 2038 if (!toActivate.contains(alternative)) { 2039 toActivate.add(alternative); 2040 } 2041 } 2042 } 2043 } 2044 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 2045 removeDataActivityTracking(nai); 2046 notifyLockdownVpn(nai); 2047 requestNetworkTransitionWakelock(nai.name()); 2048 } 2049 for (NetworkAgentInfo networkToActivate : toActivate) { 2050 unlinger(networkToActivate); 2051 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED, 2052 ReapUnvalidatedNetworks.DONT_REAP); 2053 } 2054 } 2055 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo); 2056 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name); 2057 } 2058 2059 // If this method proves to be too slow then we can maintain a separate 2060 // pendingIntent => NetworkRequestInfo map. 2061 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo. 2062 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) { 2063 Intent intent = pendingIntent.getIntent(); 2064 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) { 2065 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent; 2066 if (existingPendingIntent != null && 2067 existingPendingIntent.getIntent().filterEquals(intent)) { 2068 return entry.getValue(); 2069 } 2070 } 2071 return null; 2072 } 2073 2074 private void handleRegisterNetworkRequestWithIntent(Message msg) { 2075 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj); 2076 2077 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent); 2078 if (existingRequest != null) { // remove the existing request. 2079 if (DBG) log("Replacing " + existingRequest.request + " with " 2080 + nri.request + " because their intents matched."); 2081 handleReleaseNetworkRequest(existingRequest.request, getCallingUid()); 2082 } 2083 handleRegisterNetworkRequest(msg); 2084 } 2085 2086 private void handleRegisterNetworkRequest(Message msg) { 2087 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj); 2088 2089 mNetworkRequests.put(nri.request, nri); 2090 2091 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests 2092 2093 // Check for the best currently alive network that satisfies this request 2094 NetworkAgentInfo bestNetwork = null; 2095 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) { 2096 if (DBG) log("handleRegisterNetworkRequest checking " + network.name()); 2097 if (network.satisfies(nri.request)) { 2098 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore()); 2099 if (!nri.isRequest) { 2100 // Not setting bestNetwork here as a listening NetworkRequest may be 2101 // satisfied by multiple Networks. Instead the request is added to 2102 // each satisfying Network and notified about each. 2103 network.addRequest(nri.request); 2104 notifyNetworkCallback(network, nri); 2105 } else if (bestNetwork == null || 2106 bestNetwork.getCurrentScore() < network.getCurrentScore()) { 2107 bestNetwork = network; 2108 } 2109 } 2110 } 2111 if (bestNetwork != null) { 2112 if (DBG) log("using " + bestNetwork.name()); 2113 unlinger(bestNetwork); 2114 bestNetwork.addRequest(nri.request); 2115 mNetworkForRequestId.put(nri.request.requestId, bestNetwork); 2116 notifyNetworkCallback(bestNetwork, nri); 2117 if (nri.request.legacyType != TYPE_NONE) { 2118 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork); 2119 } 2120 } 2121 2122 if (nri.isRequest) { 2123 if (DBG) log("sending new NetworkRequest to factories"); 2124 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore(); 2125 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 2126 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 2127 0, nri.request); 2128 } 2129 } 2130 } 2131 2132 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent, 2133 int callingUid) { 2134 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent); 2135 if (nri != null) { 2136 handleReleaseNetworkRequest(nri.request, callingUid); 2137 } 2138 } 2139 2140 // Is nai unneeded by all NetworkRequests (and should be disconnected)? 2141 // For validated Networks this is simply whether it is satsifying any NetworkRequests. 2142 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or 2143 // were it to become validated, would it have a chance of satisfying any NetworkRequests. 2144 private boolean unneeded(NetworkAgentInfo nai) { 2145 if (!nai.created || nai.isVPN()) return false; 2146 boolean unneeded = true; 2147 if (nai.everValidated) { 2148 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) { 2149 final NetworkRequest nr = nai.networkRequests.valueAt(i); 2150 try { 2151 if (isRequest(nr)) unneeded = false; 2152 } catch (Exception e) { 2153 loge("Request " + nr + " not found in mNetworkRequests."); 2154 loge(" it came from request list of " + nai.name()); 2155 } 2156 } 2157 } else { 2158 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 2159 // If this Network is already the highest scoring Network for a request, or if 2160 // there is hope for it to become one if it validated, then it is needed. 2161 if (nri.isRequest && nai.satisfies(nri.request) && 2162 (nai.networkRequests.get(nri.request.requestId) != null || 2163 // Note that this catches two important cases: 2164 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi 2165 // is currently satisfying the request. This is desirable when 2166 // cellular ends up validating but WiFi does not. 2167 // 2. Unvalidated WiFi will not be reaped when validated cellular 2168 // is currently satsifying the request. This is desirable when 2169 // WiFi ends up validating and out scoring cellular. 2170 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() < 2171 nai.getCurrentScoreAsValidated())) { 2172 unneeded = false; 2173 break; 2174 } 2175 } 2176 } 2177 return unneeded; 2178 } 2179 2180 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) { 2181 NetworkRequestInfo nri = mNetworkRequests.get(request); 2182 if (nri != null) { 2183 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) { 2184 if (DBG) log("Attempt to release unowned NetworkRequest " + request); 2185 return; 2186 } 2187 if (DBG) log("releasing NetworkRequest " + request); 2188 nri.unlinkDeathRecipient(); 2189 mNetworkRequests.remove(request); 2190 if (nri.isRequest) { 2191 // Find all networks that are satisfying this request and remove the request 2192 // from their request lists. 2193 // TODO - it's my understanding that for a request there is only a single 2194 // network satisfying it, so this loop is wasteful 2195 boolean wasKept = false; 2196 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2197 if (nai.networkRequests.get(nri.request.requestId) != null) { 2198 nai.networkRequests.remove(nri.request.requestId); 2199 if (DBG) { 2200 log(" Removing from current network " + nai.name() + 2201 ", leaving " + nai.networkRequests.size() + 2202 " requests."); 2203 } 2204 if (unneeded(nai)) { 2205 if (DBG) log("no live requests for " + nai.name() + "; disconnecting"); 2206 teardownUnneededNetwork(nai); 2207 } else { 2208 // suspect there should only be one pass through here 2209 // but if any were kept do the check below 2210 wasKept |= true; 2211 } 2212 } 2213 } 2214 2215 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId); 2216 if (nai != null) { 2217 mNetworkForRequestId.remove(nri.request.requestId); 2218 } 2219 // Maintain the illusion. When this request arrived, we might have pretended 2220 // that a network connected to serve it, even though the network was already 2221 // connected. Now that this request has gone away, we might have to pretend 2222 // that the network disconnected. LegacyTypeTracker will generate that 2223 // phantom disconnect for this type. 2224 if (nri.request.legacyType != TYPE_NONE && nai != null) { 2225 boolean doRemove = true; 2226 if (wasKept) { 2227 // check if any of the remaining requests for this network are for the 2228 // same legacy type - if so, don't remove the nai 2229 for (int i = 0; i < nai.networkRequests.size(); i++) { 2230 NetworkRequest otherRequest = nai.networkRequests.valueAt(i); 2231 if (otherRequest.legacyType == nri.request.legacyType && 2232 isRequest(otherRequest)) { 2233 if (DBG) log(" still have other legacy request - leaving"); 2234 doRemove = false; 2235 } 2236 } 2237 } 2238 2239 if (doRemove) { 2240 mLegacyTypeTracker.remove(nri.request.legacyType, nai); 2241 } 2242 } 2243 2244 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 2245 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST, 2246 nri.request); 2247 } 2248 } else { 2249 // listens don't have a singular affectedNetwork. Check all networks to see 2250 // if this listen request applies and remove it. 2251 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2252 nai.networkRequests.remove(nri.request.requestId); 2253 } 2254 } 2255 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED); 2256 } 2257 } 2258 2259 private class InternalHandler extends Handler { 2260 public InternalHandler(Looper looper) { 2261 super(looper); 2262 } 2263 2264 @Override 2265 public void handleMessage(Message msg) { 2266 switch (msg.what) { 2267 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK: 2268 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: { 2269 String causedBy = null; 2270 synchronized (ConnectivityService.this) { 2271 if (msg.arg1 == mNetTransitionWakeLockSerialNumber && 2272 mNetTransitionWakeLock.isHeld()) { 2273 mNetTransitionWakeLock.release(); 2274 causedBy = mNetTransitionWakeLockCausedBy; 2275 } else { 2276 break; 2277 } 2278 } 2279 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) { 2280 log("Failed to find a new network - expiring NetTransition Wakelock"); 2281 } else { 2282 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) + 2283 " cleared because we found a replacement network"); 2284 } 2285 break; 2286 } 2287 case EVENT_APPLY_GLOBAL_HTTP_PROXY: { 2288 handleDeprecatedGlobalHttpProxy(); 2289 break; 2290 } 2291 case EVENT_SEND_STICKY_BROADCAST_INTENT: { 2292 Intent intent = (Intent)msg.obj; 2293 sendStickyBroadcast(intent); 2294 break; 2295 } 2296 case EVENT_PROXY_HAS_CHANGED: { 2297 handleApplyDefaultProxy((ProxyInfo)msg.obj); 2298 break; 2299 } 2300 case EVENT_REGISTER_NETWORK_FACTORY: { 2301 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj); 2302 break; 2303 } 2304 case EVENT_UNREGISTER_NETWORK_FACTORY: { 2305 handleUnregisterNetworkFactory((Messenger)msg.obj); 2306 break; 2307 } 2308 case EVENT_REGISTER_NETWORK_AGENT: { 2309 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj); 2310 break; 2311 } 2312 case EVENT_REGISTER_NETWORK_REQUEST: 2313 case EVENT_REGISTER_NETWORK_LISTENER: { 2314 handleRegisterNetworkRequest(msg); 2315 break; 2316 } 2317 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: { 2318 handleRegisterNetworkRequestWithIntent(msg); 2319 break; 2320 } 2321 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: { 2322 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1); 2323 break; 2324 } 2325 case EVENT_RELEASE_NETWORK_REQUEST: { 2326 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1); 2327 break; 2328 } 2329 case EVENT_SYSTEM_READY: { 2330 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2331 nai.networkMonitor.systemReady = true; 2332 } 2333 break; 2334 } 2335 } 2336 } 2337 } 2338 2339 // javadoc from interface 2340 public int tether(String iface) { 2341 ConnectivityManager.enforceTetherChangePermission(mContext); 2342 if (isTetheringSupported()) { 2343 return mTethering.tether(iface); 2344 } else { 2345 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2346 } 2347 } 2348 2349 // javadoc from interface 2350 public int untether(String iface) { 2351 ConnectivityManager.enforceTetherChangePermission(mContext); 2352 2353 if (isTetheringSupported()) { 2354 return mTethering.untether(iface); 2355 } else { 2356 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2357 } 2358 } 2359 2360 // javadoc from interface 2361 public int getLastTetherError(String iface) { 2362 enforceTetherAccessPermission(); 2363 2364 if (isTetheringSupported()) { 2365 return mTethering.getLastTetherError(iface); 2366 } else { 2367 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2368 } 2369 } 2370 2371 // TODO - proper iface API for selection by property, inspection, etc 2372 public String[] getTetherableUsbRegexs() { 2373 enforceTetherAccessPermission(); 2374 if (isTetheringSupported()) { 2375 return mTethering.getTetherableUsbRegexs(); 2376 } else { 2377 return new String[0]; 2378 } 2379 } 2380 2381 public String[] getTetherableWifiRegexs() { 2382 enforceTetherAccessPermission(); 2383 if (isTetheringSupported()) { 2384 return mTethering.getTetherableWifiRegexs(); 2385 } else { 2386 return new String[0]; 2387 } 2388 } 2389 2390 public String[] getTetherableBluetoothRegexs() { 2391 enforceTetherAccessPermission(); 2392 if (isTetheringSupported()) { 2393 return mTethering.getTetherableBluetoothRegexs(); 2394 } else { 2395 return new String[0]; 2396 } 2397 } 2398 2399 public int setUsbTethering(boolean enable) { 2400 ConnectivityManager.enforceTetherChangePermission(mContext); 2401 if (isTetheringSupported()) { 2402 return mTethering.setUsbTethering(enable); 2403 } else { 2404 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2405 } 2406 } 2407 2408 // TODO - move iface listing, queries, etc to new module 2409 // javadoc from interface 2410 public String[] getTetherableIfaces() { 2411 enforceTetherAccessPermission(); 2412 return mTethering.getTetherableIfaces(); 2413 } 2414 2415 public String[] getTetheredIfaces() { 2416 enforceTetherAccessPermission(); 2417 return mTethering.getTetheredIfaces(); 2418 } 2419 2420 public String[] getTetheringErroredIfaces() { 2421 enforceTetherAccessPermission(); 2422 return mTethering.getErroredIfaces(); 2423 } 2424 2425 public String[] getTetheredDhcpRanges() { 2426 enforceConnectivityInternalPermission(); 2427 return mTethering.getTetheredDhcpRanges(); 2428 } 2429 2430 // if ro.tether.denied = true we default to no tethering 2431 // gservices could set the secure setting to 1 though to enable it on a build where it 2432 // had previously been turned off. 2433 public boolean isTetheringSupported() { 2434 enforceTetherAccessPermission(); 2435 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 2436 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(), 2437 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0) 2438 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING); 2439 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 || 2440 mTethering.getTetherableWifiRegexs().length != 0 || 2441 mTethering.getTetherableBluetoothRegexs().length != 0) && 2442 mTethering.getUpstreamIfaceTypes().length != 0); 2443 } 2444 2445 // Called when we lose the default network and have no replacement yet. 2446 // This will automatically be cleared after X seconds or a new default network 2447 // becomes CONNECTED, whichever happens first. The timer is started by the 2448 // first caller and not restarted by subsequent callers. 2449 private void requestNetworkTransitionWakelock(String forWhom) { 2450 int serialNum = 0; 2451 synchronized (this) { 2452 if (mNetTransitionWakeLock.isHeld()) return; 2453 serialNum = ++mNetTransitionWakeLockSerialNumber; 2454 mNetTransitionWakeLock.acquire(); 2455 mNetTransitionWakeLockCausedBy = forWhom; 2456 } 2457 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2458 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0), 2459 mNetTransitionWakeLockTimeout); 2460 return; 2461 } 2462 2463 // 100 percent is full good, 0 is full bad. 2464 public void reportInetCondition(int networkType, int percentage) { 2465 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 2466 if (nai == null) return; 2467 reportNetworkConnectivity(nai.network, percentage > 50); 2468 } 2469 2470 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) { 2471 enforceAccessPermission(); 2472 enforceInternetPermission(); 2473 2474 NetworkAgentInfo nai; 2475 if (network == null) { 2476 nai = getDefaultNetwork(); 2477 } else { 2478 nai = getNetworkAgentInfoForNetwork(network); 2479 } 2480 if (nai == null) return; 2481 // Revalidate if the app report does not match our current validated state. 2482 if (hasConnectivity == nai.lastValidated) return; 2483 final int uid = Binder.getCallingUid(); 2484 if (DBG) { 2485 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity + 2486 ") by " + uid); 2487 } 2488 synchronized (nai) { 2489 // Validating an uncreated network could result in a call to rematchNetworkAndRequests() 2490 // which isn't meant to work on uncreated networks. 2491 if (!nai.created) return; 2492 2493 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return; 2494 2495 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid); 2496 } 2497 } 2498 2499 public ProxyInfo getDefaultProxy() { 2500 // this information is already available as a world read/writable jvm property 2501 // so this API change wouldn't have a benifit. It also breaks the passing 2502 // of proxy info to all the JVMs. 2503 // enforceAccessPermission(); 2504 synchronized (mProxyLock) { 2505 ProxyInfo ret = mGlobalProxy; 2506 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy; 2507 return ret; 2508 } 2509 } 2510 2511 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present 2512 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific 2513 // proxy is null then there is no proxy in place). 2514 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) { 2515 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 2516 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) { 2517 proxy = null; 2518 } 2519 return proxy; 2520 } 2521 2522 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it 2523 // better for determining if a new proxy broadcast is necessary: 2524 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to 2525 // avoid unnecessary broadcasts. 2526 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL 2527 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler) 2528 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but 2529 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port 2530 // all set. 2531 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) { 2532 a = canonicalizeProxyInfo(a); 2533 b = canonicalizeProxyInfo(b); 2534 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check 2535 // hosts even when PAC URLs are present to account for the legacy PAC resolver. 2536 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost())); 2537 } 2538 2539 public void setGlobalProxy(ProxyInfo proxyProperties) { 2540 enforceConnectivityInternalPermission(); 2541 2542 synchronized (mProxyLock) { 2543 if (proxyProperties == mGlobalProxy) return; 2544 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return; 2545 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return; 2546 2547 String host = ""; 2548 int port = 0; 2549 String exclList = ""; 2550 String pacFileUrl = ""; 2551 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) || 2552 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) { 2553 if (!proxyProperties.isValid()) { 2554 if (DBG) 2555 log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 2556 return; 2557 } 2558 mGlobalProxy = new ProxyInfo(proxyProperties); 2559 host = mGlobalProxy.getHost(); 2560 port = mGlobalProxy.getPort(); 2561 exclList = mGlobalProxy.getExclusionListAsString(); 2562 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) { 2563 pacFileUrl = proxyProperties.getPacFileUrl().toString(); 2564 } 2565 } else { 2566 mGlobalProxy = null; 2567 } 2568 ContentResolver res = mContext.getContentResolver(); 2569 final long token = Binder.clearCallingIdentity(); 2570 try { 2571 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host); 2572 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port); 2573 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 2574 exclList); 2575 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl); 2576 } finally { 2577 Binder.restoreCallingIdentity(token); 2578 } 2579 2580 if (mGlobalProxy == null) { 2581 proxyProperties = mDefaultProxy; 2582 } 2583 sendProxyBroadcast(proxyProperties); 2584 } 2585 } 2586 2587 private void loadGlobalProxy() { 2588 ContentResolver res = mContext.getContentResolver(); 2589 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST); 2590 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0); 2591 String exclList = Settings.Global.getString(res, 2592 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST); 2593 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC); 2594 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) { 2595 ProxyInfo proxyProperties; 2596 if (!TextUtils.isEmpty(pacFileUrl)) { 2597 proxyProperties = new ProxyInfo(pacFileUrl); 2598 } else { 2599 proxyProperties = new ProxyInfo(host, port, exclList); 2600 } 2601 if (!proxyProperties.isValid()) { 2602 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 2603 return; 2604 } 2605 2606 synchronized (mProxyLock) { 2607 mGlobalProxy = proxyProperties; 2608 } 2609 } 2610 } 2611 2612 public ProxyInfo getGlobalProxy() { 2613 // this information is already available as a world read/writable jvm property 2614 // so this API change wouldn't have a benifit. It also breaks the passing 2615 // of proxy info to all the JVMs. 2616 // enforceAccessPermission(); 2617 synchronized (mProxyLock) { 2618 return mGlobalProxy; 2619 } 2620 } 2621 2622 private void handleApplyDefaultProxy(ProxyInfo proxy) { 2623 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 2624 && Uri.EMPTY.equals(proxy.getPacFileUrl())) { 2625 proxy = null; 2626 } 2627 synchronized (mProxyLock) { 2628 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return; 2629 if (mDefaultProxy == proxy) return; // catches repeated nulls 2630 if (proxy != null && !proxy.isValid()) { 2631 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString()); 2632 return; 2633 } 2634 2635 // This call could be coming from the PacManager, containing the port of the local 2636 // proxy. If this new proxy matches the global proxy then copy this proxy to the 2637 // global (to get the correct local port), and send a broadcast. 2638 // TODO: Switch PacManager to have its own message to send back rather than 2639 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy. 2640 if ((mGlobalProxy != null) && (proxy != null) 2641 && (!Uri.EMPTY.equals(proxy.getPacFileUrl())) 2642 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) { 2643 mGlobalProxy = proxy; 2644 sendProxyBroadcast(mGlobalProxy); 2645 return; 2646 } 2647 mDefaultProxy = proxy; 2648 2649 if (mGlobalProxy != null) return; 2650 if (!mDefaultProxyDisabled) { 2651 sendProxyBroadcast(proxy); 2652 } 2653 } 2654 } 2655 2656 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy. 2657 // This method gets called when any network changes proxy, but the broadcast only ever contains 2658 // the default proxy (even if it hasn't changed). 2659 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network 2660 // world where an app might be bound to a non-default network. 2661 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) { 2662 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy(); 2663 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy(); 2664 2665 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) { 2666 sendProxyBroadcast(getDefaultProxy()); 2667 } 2668 } 2669 2670 private void handleDeprecatedGlobalHttpProxy() { 2671 String proxy = Settings.Global.getString(mContext.getContentResolver(), 2672 Settings.Global.HTTP_PROXY); 2673 if (!TextUtils.isEmpty(proxy)) { 2674 String data[] = proxy.split(":"); 2675 if (data.length == 0) { 2676 return; 2677 } 2678 2679 String proxyHost = data[0]; 2680 int proxyPort = 8080; 2681 if (data.length > 1) { 2682 try { 2683 proxyPort = Integer.parseInt(data[1]); 2684 } catch (NumberFormatException e) { 2685 return; 2686 } 2687 } 2688 ProxyInfo p = new ProxyInfo(data[0], proxyPort, ""); 2689 setGlobalProxy(p); 2690 } 2691 } 2692 2693 private void sendProxyBroadcast(ProxyInfo proxy) { 2694 if (proxy == null) proxy = new ProxyInfo("", 0, ""); 2695 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return; 2696 if (DBG) log("sending Proxy Broadcast for " + proxy); 2697 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); 2698 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 2699 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 2700 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy); 2701 final long ident = Binder.clearCallingIdentity(); 2702 try { 2703 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 2704 } finally { 2705 Binder.restoreCallingIdentity(ident); 2706 } 2707 } 2708 2709 private static class SettingsObserver extends ContentObserver { 2710 private int mWhat; 2711 private Handler mHandler; 2712 SettingsObserver(Handler handler, int what) { 2713 super(handler); 2714 mHandler = handler; 2715 mWhat = what; 2716 } 2717 2718 void observe(Context context) { 2719 ContentResolver resolver = context.getContentResolver(); 2720 resolver.registerContentObserver(Settings.Global.getUriFor( 2721 Settings.Global.HTTP_PROXY), false, this); 2722 } 2723 2724 @Override 2725 public void onChange(boolean selfChange) { 2726 mHandler.obtainMessage(mWhat).sendToTarget(); 2727 } 2728 } 2729 2730 private static void log(String s) { 2731 Slog.d(TAG, s); 2732 } 2733 2734 private static void loge(String s) { 2735 Slog.e(TAG, s); 2736 } 2737 2738 private static <T> T checkNotNull(T value, String message) { 2739 if (value == null) { 2740 throw new NullPointerException(message); 2741 } 2742 return value; 2743 } 2744 2745 /** 2746 * Prepare for a VPN application. 2747 * Permissions are checked in Vpn class. 2748 * @hide 2749 */ 2750 @Override 2751 public boolean prepareVpn(String oldPackage, String newPackage) { 2752 throwIfLockdownEnabled(); 2753 int user = UserHandle.getUserId(Binder.getCallingUid()); 2754 synchronized(mVpns) { 2755 return mVpns.get(user).prepare(oldPackage, newPackage); 2756 } 2757 } 2758 2759 /** 2760 * Set whether the current VPN package has the ability to launch VPNs without 2761 * user intervention. This method is used by system-privileged apps. 2762 * Permissions are checked in Vpn class. 2763 * @hide 2764 */ 2765 @Override 2766 public void setVpnPackageAuthorization(boolean authorized) { 2767 int user = UserHandle.getUserId(Binder.getCallingUid()); 2768 synchronized(mVpns) { 2769 mVpns.get(user).setPackageAuthorization(authorized); 2770 } 2771 } 2772 2773 /** 2774 * Configure a TUN interface and return its file descriptor. Parameters 2775 * are encoded and opaque to this class. This method is used by VpnBuilder 2776 * and not available in ConnectivityManager. Permissions are checked in 2777 * Vpn class. 2778 * @hide 2779 */ 2780 @Override 2781 public ParcelFileDescriptor establishVpn(VpnConfig config) { 2782 throwIfLockdownEnabled(); 2783 int user = UserHandle.getUserId(Binder.getCallingUid()); 2784 synchronized(mVpns) { 2785 return mVpns.get(user).establish(config); 2786 } 2787 } 2788 2789 /** 2790 * Start legacy VPN, controlling native daemons as needed. Creates a 2791 * secondary thread to perform connection work, returning quickly. 2792 */ 2793 @Override 2794 public void startLegacyVpn(VpnProfile profile) { 2795 throwIfLockdownEnabled(); 2796 final LinkProperties egress = getActiveLinkProperties(); 2797 if (egress == null) { 2798 throw new IllegalStateException("Missing active network connection"); 2799 } 2800 int user = UserHandle.getUserId(Binder.getCallingUid()); 2801 synchronized(mVpns) { 2802 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress); 2803 } 2804 } 2805 2806 /** 2807 * Return the information of the ongoing legacy VPN. This method is used 2808 * by VpnSettings and not available in ConnectivityManager. Permissions 2809 * are checked in Vpn class. 2810 */ 2811 @Override 2812 public LegacyVpnInfo getLegacyVpnInfo() { 2813 throwIfLockdownEnabled(); 2814 int user = UserHandle.getUserId(Binder.getCallingUid()); 2815 synchronized(mVpns) { 2816 return mVpns.get(user).getLegacyVpnInfo(); 2817 } 2818 } 2819 2820 /** 2821 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService 2822 * and not available in ConnectivityManager. 2823 */ 2824 @Override 2825 public VpnInfo[] getAllVpnInfo() { 2826 enforceConnectivityInternalPermission(); 2827 if (mLockdownEnabled) { 2828 return new VpnInfo[0]; 2829 } 2830 2831 synchronized(mVpns) { 2832 List<VpnInfo> infoList = new ArrayList<>(); 2833 for (int i = 0; i < mVpns.size(); i++) { 2834 VpnInfo info = createVpnInfo(mVpns.valueAt(i)); 2835 if (info != null) { 2836 infoList.add(info); 2837 } 2838 } 2839 return infoList.toArray(new VpnInfo[infoList.size()]); 2840 } 2841 } 2842 2843 /** 2844 * @return VPN information for accounting, or null if we can't retrieve all required 2845 * information, e.g primary underlying iface. 2846 */ 2847 @Nullable 2848 private VpnInfo createVpnInfo(Vpn vpn) { 2849 VpnInfo info = vpn.getVpnInfo(); 2850 if (info == null) { 2851 return null; 2852 } 2853 Network[] underlyingNetworks = vpn.getUnderlyingNetworks(); 2854 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret 2855 // the underlyingNetworks list. 2856 if (underlyingNetworks == null) { 2857 NetworkAgentInfo defaultNetwork = getDefaultNetwork(); 2858 if (defaultNetwork != null && defaultNetwork.linkProperties != null) { 2859 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName(); 2860 } 2861 } else if (underlyingNetworks.length > 0) { 2862 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]); 2863 if (linkProperties != null) { 2864 info.primaryUnderlyingIface = linkProperties.getInterfaceName(); 2865 } 2866 } 2867 return info.primaryUnderlyingIface == null ? null : info; 2868 } 2869 2870 /** 2871 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and 2872 * not available in ConnectivityManager. 2873 * Permissions are checked in Vpn class. 2874 * @hide 2875 */ 2876 @Override 2877 public VpnConfig getVpnConfig() { 2878 int user = UserHandle.getUserId(Binder.getCallingUid()); 2879 synchronized(mVpns) { 2880 return mVpns.get(user).getVpnConfig(); 2881 } 2882 } 2883 2884 @Override 2885 public boolean updateLockdownVpn() { 2886 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 2887 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM"); 2888 return false; 2889 } 2890 2891 // Tear down existing lockdown if profile was removed 2892 mLockdownEnabled = LockdownVpnTracker.isEnabled(); 2893 if (mLockdownEnabled) { 2894 if (!mKeyStore.isUnlocked()) { 2895 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker"); 2896 return false; 2897 } 2898 2899 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN)); 2900 final VpnProfile profile = VpnProfile.decode( 2901 profileName, mKeyStore.get(Credentials.VPN + profileName)); 2902 int user = UserHandle.getUserId(Binder.getCallingUid()); 2903 synchronized(mVpns) { 2904 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user), 2905 profile)); 2906 } 2907 } else { 2908 setLockdownTracker(null); 2909 } 2910 2911 return true; 2912 } 2913 2914 /** 2915 * Internally set new {@link LockdownVpnTracker}, shutting down any existing 2916 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown. 2917 */ 2918 private void setLockdownTracker(LockdownVpnTracker tracker) { 2919 // Shutdown any existing tracker 2920 final LockdownVpnTracker existing = mLockdownTracker; 2921 mLockdownTracker = null; 2922 if (existing != null) { 2923 existing.shutdown(); 2924 } 2925 2926 try { 2927 if (tracker != null) { 2928 mNetd.setFirewallEnabled(true); 2929 mNetd.setFirewallInterfaceRule("lo", true); 2930 mLockdownTracker = tracker; 2931 mLockdownTracker.init(); 2932 } else { 2933 mNetd.setFirewallEnabled(false); 2934 } 2935 } catch (RemoteException e) { 2936 // ignored; NMS lives inside system_server 2937 } 2938 } 2939 2940 private void throwIfLockdownEnabled() { 2941 if (mLockdownEnabled) { 2942 throw new IllegalStateException("Unavailable in lockdown mode"); 2943 } 2944 } 2945 2946 @Override 2947 public int checkMobileProvisioning(int suggestedTimeOutMs) { 2948 // TODO: Remove? Any reason to trigger a provisioning check? 2949 return -1; 2950 } 2951 2952 private static final String NOTIFICATION_ID = "CaptivePortal.Notification"; 2953 private volatile boolean mIsNotificationVisible = false; 2954 2955 private void setProvNotificationVisible(boolean visible, int networkType, String action) { 2956 if (DBG) { 2957 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType 2958 + " action=" + action); 2959 } 2960 Intent intent = new Intent(action); 2961 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); 2962 // Concatenate the range of types onto the range of NetIDs. 2963 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE); 2964 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent); 2965 } 2966 2967 /** 2968 * Show or hide network provisioning notificaitons. 2969 * 2970 * @param id an identifier that uniquely identifies this notification. This must match 2971 * between show and hide calls. We use the NetID value but for legacy callers 2972 * we concatenate the range of types with the range of NetIDs. 2973 */ 2974 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType, 2975 String extraInfo, PendingIntent intent) { 2976 if (DBG) { 2977 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" + 2978 networkType + " extraInfo=" + extraInfo); 2979 } 2980 2981 Resources r = Resources.getSystem(); 2982 NotificationManager notificationManager = (NotificationManager) mContext 2983 .getSystemService(Context.NOTIFICATION_SERVICE); 2984 2985 if (visible) { 2986 CharSequence title; 2987 CharSequence details; 2988 int icon; 2989 Notification notification = new Notification(); 2990 switch (networkType) { 2991 case ConnectivityManager.TYPE_WIFI: 2992 title = r.getString(R.string.wifi_available_sign_in, 0); 2993 details = r.getString(R.string.network_available_sign_in_detailed, 2994 extraInfo); 2995 icon = R.drawable.stat_notify_wifi_in_range; 2996 break; 2997 case ConnectivityManager.TYPE_MOBILE: 2998 case ConnectivityManager.TYPE_MOBILE_HIPRI: 2999 title = r.getString(R.string.network_available_sign_in, 0); 3000 // TODO: Change this to pull from NetworkInfo once a printable 3001 // name has been added to it 3002 details = mTelephonyManager.getNetworkOperatorName(); 3003 icon = R.drawable.stat_notify_rssi_in_range; 3004 break; 3005 default: 3006 title = r.getString(R.string.network_available_sign_in, 0); 3007 details = r.getString(R.string.network_available_sign_in_detailed, 3008 extraInfo); 3009 icon = R.drawable.stat_notify_rssi_in_range; 3010 break; 3011 } 3012 3013 notification.when = 0; 3014 notification.icon = icon; 3015 notification.flags = Notification.FLAG_AUTO_CANCEL; 3016 notification.tickerText = title; 3017 notification.color = mContext.getColor( 3018 com.android.internal.R.color.system_notification_accent_color); 3019 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent); 3020 notification.contentIntent = intent; 3021 3022 try { 3023 notificationManager.notify(NOTIFICATION_ID, id, notification); 3024 } catch (NullPointerException npe) { 3025 loge("setNotificaitionVisible: visible notificationManager npe=" + npe); 3026 npe.printStackTrace(); 3027 } 3028 } else { 3029 try { 3030 notificationManager.cancel(NOTIFICATION_ID, id); 3031 } catch (NullPointerException npe) { 3032 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe); 3033 npe.printStackTrace(); 3034 } 3035 } 3036 mIsNotificationVisible = visible; 3037 } 3038 3039 /** Location to an updatable file listing carrier provisioning urls. 3040 * An example: 3041 * 3042 * <?xml version="1.0" encoding="utf-8"?> 3043 * <provisioningUrls> 3044 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl> 3045 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl> 3046 * </provisioningUrls> 3047 */ 3048 private static final String PROVISIONING_URL_PATH = 3049 "/data/misc/radio/provisioning_urls.xml"; 3050 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH); 3051 3052 /** XML tag for root element. */ 3053 private static final String TAG_PROVISIONING_URLS = "provisioningUrls"; 3054 /** XML tag for individual url */ 3055 private static final String TAG_PROVISIONING_URL = "provisioningUrl"; 3056 /** XML tag for redirected url */ 3057 private static final String TAG_REDIRECTED_URL = "redirectedUrl"; 3058 /** XML attribute for mcc */ 3059 private static final String ATTR_MCC = "mcc"; 3060 /** XML attribute for mnc */ 3061 private static final String ATTR_MNC = "mnc"; 3062 3063 private static final int REDIRECTED_PROVISIONING = 1; 3064 private static final int PROVISIONING = 2; 3065 3066 private String getProvisioningUrlBaseFromFile(int type) { 3067 FileReader fileReader = null; 3068 XmlPullParser parser = null; 3069 Configuration config = mContext.getResources().getConfiguration(); 3070 String tagType; 3071 3072 switch (type) { 3073 case PROVISIONING: 3074 tagType = TAG_PROVISIONING_URL; 3075 break; 3076 case REDIRECTED_PROVISIONING: 3077 tagType = TAG_REDIRECTED_URL; 3078 break; 3079 default: 3080 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " + 3081 type); 3082 } 3083 3084 try { 3085 fileReader = new FileReader(mProvisioningUrlFile); 3086 parser = Xml.newPullParser(); 3087 parser.setInput(fileReader); 3088 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS); 3089 3090 while (true) { 3091 XmlUtils.nextElement(parser); 3092 3093 String element = parser.getName(); 3094 if (element == null) break; 3095 3096 if (element.equals(tagType)) { 3097 String mcc = parser.getAttributeValue(null, ATTR_MCC); 3098 try { 3099 if (mcc != null && Integer.parseInt(mcc) == config.mcc) { 3100 String mnc = parser.getAttributeValue(null, ATTR_MNC); 3101 if (mnc != null && Integer.parseInt(mnc) == config.mnc) { 3102 parser.next(); 3103 if (parser.getEventType() == XmlPullParser.TEXT) { 3104 return parser.getText(); 3105 } 3106 } 3107 } 3108 } catch (NumberFormatException e) { 3109 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e); 3110 } 3111 } 3112 } 3113 return null; 3114 } catch (FileNotFoundException e) { 3115 loge("Carrier Provisioning Urls file not found"); 3116 } catch (XmlPullParserException e) { 3117 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e); 3118 } catch (IOException e) { 3119 loge("I/O exception reading Carrier Provisioning Urls file: " + e); 3120 } finally { 3121 if (fileReader != null) { 3122 try { 3123 fileReader.close(); 3124 } catch (IOException e) {} 3125 } 3126 } 3127 return null; 3128 } 3129 3130 @Override 3131 public String getMobileRedirectedProvisioningUrl() { 3132 enforceConnectivityInternalPermission(); 3133 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING); 3134 if (TextUtils.isEmpty(url)) { 3135 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url); 3136 } 3137 return url; 3138 } 3139 3140 @Override 3141 public String getMobileProvisioningUrl() { 3142 enforceConnectivityInternalPermission(); 3143 String url = getProvisioningUrlBaseFromFile(PROVISIONING); 3144 if (TextUtils.isEmpty(url)) { 3145 url = mContext.getResources().getString(R.string.mobile_provisioning_url); 3146 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url); 3147 } else { 3148 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url); 3149 } 3150 // populate the iccid, imei and phone number in the provisioning url. 3151 if (!TextUtils.isEmpty(url)) { 3152 String phoneNumber = mTelephonyManager.getLine1Number(); 3153 if (TextUtils.isEmpty(phoneNumber)) { 3154 phoneNumber = "0000000000"; 3155 } 3156 url = String.format(url, 3157 mTelephonyManager.getSimSerialNumber() /* ICCID */, 3158 mTelephonyManager.getDeviceId() /* IMEI */, 3159 phoneNumber /* Phone numer */); 3160 } 3161 3162 return url; 3163 } 3164 3165 @Override 3166 public void setProvisioningNotificationVisible(boolean visible, int networkType, 3167 String action) { 3168 enforceConnectivityInternalPermission(); 3169 final long ident = Binder.clearCallingIdentity(); 3170 try { 3171 setProvNotificationVisible(visible, networkType, action); 3172 } finally { 3173 Binder.restoreCallingIdentity(ident); 3174 } 3175 } 3176 3177 @Override 3178 public void setAirplaneMode(boolean enable) { 3179 enforceConnectivityInternalPermission(); 3180 final long ident = Binder.clearCallingIdentity(); 3181 try { 3182 final ContentResolver cr = mContext.getContentResolver(); 3183 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 3184 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 3185 intent.putExtra("state", enable); 3186 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 3187 } finally { 3188 Binder.restoreCallingIdentity(ident); 3189 } 3190 } 3191 3192 private void onUserStart(int userId) { 3193 synchronized(mVpns) { 3194 Vpn userVpn = mVpns.get(userId); 3195 if (userVpn != null) { 3196 loge("Starting user already has a VPN"); 3197 return; 3198 } 3199 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); 3200 mVpns.put(userId, userVpn); 3201 } 3202 } 3203 3204 private void onUserStop(int userId) { 3205 synchronized(mVpns) { 3206 Vpn userVpn = mVpns.get(userId); 3207 if (userVpn == null) { 3208 loge("Stopping user has no VPN"); 3209 return; 3210 } 3211 mVpns.delete(userId); 3212 } 3213 } 3214 3215 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() { 3216 @Override 3217 public void onReceive(Context context, Intent intent) { 3218 final String action = intent.getAction(); 3219 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 3220 if (userId == UserHandle.USER_NULL) return; 3221 3222 if (Intent.ACTION_USER_STARTING.equals(action)) { 3223 onUserStart(userId); 3224 } else if (Intent.ACTION_USER_STOPPING.equals(action)) { 3225 onUserStop(userId); 3226 } 3227 } 3228 }; 3229 3230 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = 3231 new HashMap<Messenger, NetworkFactoryInfo>(); 3232 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = 3233 new HashMap<NetworkRequest, NetworkRequestInfo>(); 3234 3235 private static class NetworkFactoryInfo { 3236 public final String name; 3237 public final Messenger messenger; 3238 public final AsyncChannel asyncChannel; 3239 3240 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) { 3241 this.name = name; 3242 this.messenger = messenger; 3243 this.asyncChannel = asyncChannel; 3244 } 3245 } 3246 3247 /** 3248 * Tracks info about the requester. 3249 * Also used to notice when the calling process dies so we can self-expire 3250 */ 3251 private class NetworkRequestInfo implements IBinder.DeathRecipient { 3252 static final boolean REQUEST = true; 3253 static final boolean LISTEN = false; 3254 3255 final NetworkRequest request; 3256 final PendingIntent mPendingIntent; 3257 boolean mPendingIntentSent; 3258 private final IBinder mBinder; 3259 final int mPid; 3260 final int mUid; 3261 final Messenger messenger; 3262 final boolean isRequest; 3263 3264 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) { 3265 request = r; 3266 mPendingIntent = pi; 3267 messenger = null; 3268 mBinder = null; 3269 mPid = getCallingPid(); 3270 mUid = getCallingUid(); 3271 this.isRequest = isRequest; 3272 } 3273 3274 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) { 3275 super(); 3276 messenger = m; 3277 request = r; 3278 mBinder = binder; 3279 mPid = getCallingPid(); 3280 mUid = getCallingUid(); 3281 this.isRequest = isRequest; 3282 mPendingIntent = null; 3283 3284 try { 3285 mBinder.linkToDeath(this, 0); 3286 } catch (RemoteException e) { 3287 binderDied(); 3288 } 3289 } 3290 3291 void unlinkDeathRecipient() { 3292 if (mBinder != null) { 3293 mBinder.unlinkToDeath(this, 0); 3294 } 3295 } 3296 3297 public void binderDied() { 3298 log("ConnectivityService NetworkRequestInfo binderDied(" + 3299 request + ", " + mBinder + ")"); 3300 releaseNetworkRequest(request); 3301 } 3302 3303 public String toString() { 3304 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" + 3305 mPid + " for " + request + 3306 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent); 3307 } 3308 } 3309 3310 @Override 3311 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities, 3312 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) { 3313 networkCapabilities = new NetworkCapabilities(networkCapabilities); 3314 enforceNetworkRequestPermissions(networkCapabilities); 3315 enforceMeteredApnPolicy(networkCapabilities); 3316 3317 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) { 3318 throw new IllegalArgumentException("Bad timeout specified"); 3319 } 3320 3321 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType, 3322 nextNetworkRequestId()); 3323 if (DBG) log("requestNetwork for " + networkRequest); 3324 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, 3325 NetworkRequestInfo.REQUEST); 3326 3327 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri)); 3328 if (timeoutMs > 0) { 3329 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST, 3330 nri), timeoutMs); 3331 } 3332 return networkRequest; 3333 } 3334 3335 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) { 3336 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED) 3337 == false) { 3338 enforceConnectivityInternalPermission(); 3339 } else { 3340 enforceChangePermission(); 3341 } 3342 } 3343 3344 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) { 3345 // if UID is restricted, don't allow them to bring up metered APNs 3346 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) 3347 == false) { 3348 final int uidRules; 3349 final int uid = Binder.getCallingUid(); 3350 synchronized(mRulesLock) { 3351 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL); 3352 } 3353 if ((uidRules & RULE_REJECT_METERED) != 0) { 3354 // we could silently fail or we can filter the available nets to only give 3355 // them those they have access to. Chose the more useful 3356 networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED); 3357 } 3358 } 3359 } 3360 3361 @Override 3362 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities, 3363 PendingIntent operation) { 3364 checkNotNull(operation, "PendingIntent cannot be null."); 3365 networkCapabilities = new NetworkCapabilities(networkCapabilities); 3366 enforceNetworkRequestPermissions(networkCapabilities); 3367 enforceMeteredApnPolicy(networkCapabilities); 3368 3369 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE, 3370 nextNetworkRequestId()); 3371 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation); 3372 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation, 3373 NetworkRequestInfo.REQUEST); 3374 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT, 3375 nri)); 3376 return networkRequest; 3377 } 3378 3379 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) { 3380 mHandler.sendMessageDelayed( 3381 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, 3382 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs); 3383 } 3384 3385 @Override 3386 public void releasePendingNetworkRequest(PendingIntent operation) { 3387 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT, 3388 getCallingUid(), 0, operation)); 3389 } 3390 3391 @Override 3392 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities, 3393 Messenger messenger, IBinder binder) { 3394 enforceAccessPermission(); 3395 3396 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities( 3397 networkCapabilities), TYPE_NONE, nextNetworkRequestId()); 3398 if (DBG) log("listenForNetwork for " + networkRequest); 3399 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, 3400 NetworkRequestInfo.LISTEN); 3401 3402 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 3403 return networkRequest; 3404 } 3405 3406 @Override 3407 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities, 3408 PendingIntent operation) { 3409 } 3410 3411 @Override 3412 public void releaseNetworkRequest(NetworkRequest networkRequest) { 3413 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 3414 0, networkRequest)); 3415 } 3416 3417 @Override 3418 public void registerNetworkFactory(Messenger messenger, String name) { 3419 enforceConnectivityInternalPermission(); 3420 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel()); 3421 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi)); 3422 } 3423 3424 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) { 3425 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name); 3426 mNetworkFactoryInfos.put(nfi.messenger, nfi); 3427 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger); 3428 } 3429 3430 @Override 3431 public void unregisterNetworkFactory(Messenger messenger) { 3432 enforceConnectivityInternalPermission(); 3433 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger)); 3434 } 3435 3436 private void handleUnregisterNetworkFactory(Messenger messenger) { 3437 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger); 3438 if (nfi == null) { 3439 loge("Failed to find Messenger in unregisterNetworkFactory"); 3440 return; 3441 } 3442 if (DBG) log("unregisterNetworkFactory for " + nfi.name); 3443 } 3444 3445 /** 3446 * NetworkAgentInfo supporting a request by requestId. 3447 * These have already been vetted (their Capabilities satisfy the request) 3448 * and the are the highest scored network available. 3449 * the are keyed off the Requests requestId. 3450 */ 3451 // TODO: Yikes, this is accessed on multiple threads: add synchronization. 3452 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = 3453 new SparseArray<NetworkAgentInfo>(); 3454 3455 // NOTE: Accessed on multiple threads, must be synchronized on itself. 3456 @GuardedBy("mNetworkForNetId") 3457 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = 3458 new SparseArray<NetworkAgentInfo>(); 3459 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId. 3460 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so 3461 // there may not be a strict 1:1 correlation between the two. 3462 @GuardedBy("mNetworkForNetId") 3463 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray(); 3464 3465 // NetworkAgentInfo keyed off its connecting messenger 3466 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays 3467 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump(). 3468 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = 3469 new HashMap<Messenger, NetworkAgentInfo>(); 3470 3471 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated. 3472 private final NetworkRequest mDefaultRequest; 3473 3474 private NetworkAgentInfo getDefaultNetwork() { 3475 return mNetworkForRequestId.get(mDefaultRequest.requestId); 3476 } 3477 3478 private boolean isDefaultNetwork(NetworkAgentInfo nai) { 3479 return nai == getDefaultNetwork(); 3480 } 3481 3482 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo, 3483 LinkProperties linkProperties, NetworkCapabilities networkCapabilities, 3484 int currentScore, NetworkMisc networkMisc) { 3485 enforceConnectivityInternalPermission(); 3486 3487 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network 3488 // satisfies mDefaultRequest. 3489 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), 3490 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties( 3491 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore, 3492 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest); 3493 synchronized (this) { 3494 nai.networkMonitor.systemReady = mSystemReady; 3495 } 3496 if (DBG) log("registerNetworkAgent " + nai); 3497 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai)); 3498 return nai.network.netId; 3499 } 3500 3501 private void handleRegisterNetworkAgent(NetworkAgentInfo na) { 3502 if (VDBG) log("Got NetworkAgent Messenger"); 3503 mNetworkAgentInfos.put(na.messenger, na); 3504 synchronized (mNetworkForNetId) { 3505 mNetworkForNetId.put(na.network.netId, na); 3506 } 3507 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger); 3508 NetworkInfo networkInfo = na.networkInfo; 3509 na.networkInfo = null; 3510 updateNetworkInfo(na, networkInfo); 3511 } 3512 3513 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) { 3514 LinkProperties newLp = networkAgent.linkProperties; 3515 int netId = networkAgent.network.netId; 3516 3517 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before 3518 // we do anything else, make sure its LinkProperties are accurate. 3519 if (networkAgent.clatd != null) { 3520 networkAgent.clatd.fixupLinkProperties(oldLp); 3521 } 3522 3523 updateInterfaces(newLp, oldLp, netId); 3524 updateMtu(newLp, oldLp); 3525 // TODO - figure out what to do for clat 3526// for (LinkProperties lp : newLp.getStackedLinks()) { 3527// updateMtu(lp, null); 3528// } 3529 updateTcpBufferSizes(networkAgent); 3530 3531 // TODO: deprecate and remove mDefaultDns when we can do so safely. 3532 // For now, use it only when the network has Internet access. http://b/18327075 3533 final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability( 3534 NetworkCapabilities.NET_CAPABILITY_INTERNET); 3535 final boolean flushDns = updateRoutes(newLp, oldLp, netId); 3536 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns); 3537 3538 updateClat(newLp, oldLp, networkAgent); 3539 if (isDefaultNetwork(networkAgent)) { 3540 handleApplyDefaultProxy(newLp.getHttpProxy()); 3541 } else { 3542 updateProxy(newLp, oldLp, networkAgent); 3543 } 3544 // TODO - move this check to cover the whole function 3545 if (!Objects.equals(newLp, oldLp)) { 3546 notifyIfacesChanged(); 3547 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED); 3548 } 3549 } 3550 3551 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) { 3552 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted(); 3553 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai); 3554 3555 if (!wasRunningClat && shouldRunClat) { 3556 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai); 3557 nai.clatd.start(); 3558 } else if (wasRunningClat && !shouldRunClat) { 3559 nai.clatd.stop(); 3560 } 3561 } 3562 3563 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) { 3564 CompareResult<String> interfaceDiff = new CompareResult<String>(); 3565 if (oldLp != null) { 3566 interfaceDiff = oldLp.compareAllInterfaceNames(newLp); 3567 } else if (newLp != null) { 3568 interfaceDiff.added = newLp.getAllInterfaceNames(); 3569 } 3570 for (String iface : interfaceDiff.added) { 3571 try { 3572 if (DBG) log("Adding iface " + iface + " to network " + netId); 3573 mNetd.addInterfaceToNetwork(iface, netId); 3574 } catch (Exception e) { 3575 loge("Exception adding interface: " + e); 3576 } 3577 } 3578 for (String iface : interfaceDiff.removed) { 3579 try { 3580 if (DBG) log("Removing iface " + iface + " from network " + netId); 3581 mNetd.removeInterfaceFromNetwork(iface, netId); 3582 } catch (Exception e) { 3583 loge("Exception removing interface: " + e); 3584 } 3585 } 3586 } 3587 3588 /** 3589 * Have netd update routes from oldLp to newLp. 3590 * @return true if routes changed between oldLp and newLp 3591 */ 3592 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) { 3593 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 3594 if (oldLp != null) { 3595 routeDiff = oldLp.compareAllRoutes(newLp); 3596 } else if (newLp != null) { 3597 routeDiff.added = newLp.getAllRoutes(); 3598 } 3599 3600 // add routes before removing old in case it helps with continuous connectivity 3601 3602 // do this twice, adding non-nexthop routes first, then routes they are dependent on 3603 for (RouteInfo route : routeDiff.added) { 3604 if (route.hasGateway()) continue; 3605 if (DBG) log("Adding Route [" + route + "] to network " + netId); 3606 try { 3607 mNetd.addRoute(netId, route); 3608 } catch (Exception e) { 3609 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) { 3610 loge("Exception in addRoute for non-gateway: " + e); 3611 } 3612 } 3613 } 3614 for (RouteInfo route : routeDiff.added) { 3615 if (route.hasGateway() == false) continue; 3616 if (DBG) log("Adding Route [" + route + "] to network " + netId); 3617 try { 3618 mNetd.addRoute(netId, route); 3619 } catch (Exception e) { 3620 if ((route.getGateway() instanceof Inet4Address) || VDBG) { 3621 loge("Exception in addRoute for gateway: " + e); 3622 } 3623 } 3624 } 3625 3626 for (RouteInfo route : routeDiff.removed) { 3627 if (DBG) log("Removing Route [" + route + "] from network " + netId); 3628 try { 3629 mNetd.removeRoute(netId, route); 3630 } catch (Exception e) { 3631 loge("Exception in removeRoute: " + e); 3632 } 3633 } 3634 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty(); 3635 } 3636 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId, 3637 boolean flush, boolean useDefaultDns) { 3638 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) { 3639 Collection<InetAddress> dnses = newLp.getDnsServers(); 3640 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) { 3641 dnses = new ArrayList(); 3642 dnses.add(mDefaultDns); 3643 if (DBG) { 3644 loge("no dns provided for netId " + netId + ", so using defaults"); 3645 } 3646 } 3647 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses); 3648 try { 3649 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), 3650 newLp.getDomains()); 3651 } catch (Exception e) { 3652 loge("Exception in setDnsServersForNetwork: " + e); 3653 } 3654 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId); 3655 if (defaultNai != null && defaultNai.network.netId == netId) { 3656 setDefaultDnsSystemProperties(dnses); 3657 } 3658 flushVmDnsCache(); 3659 } else if (flush) { 3660 try { 3661 mNetd.flushNetworkDnsCache(netId); 3662 } catch (Exception e) { 3663 loge("Exception in flushNetworkDnsCache: " + e); 3664 } 3665 flushVmDnsCache(); 3666 } 3667 } 3668 3669 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) { 3670 int last = 0; 3671 for (InetAddress dns : dnses) { 3672 ++last; 3673 String key = "net.dns" + last; 3674 String value = dns.getHostAddress(); 3675 SystemProperties.set(key, value); 3676 } 3677 for (int i = last + 1; i <= mNumDnsEntries; ++i) { 3678 String key = "net.dns" + i; 3679 SystemProperties.set(key, ""); 3680 } 3681 mNumDnsEntries = last; 3682 } 3683 3684 private void updateCapabilities(NetworkAgentInfo networkAgent, 3685 NetworkCapabilities networkCapabilities) { 3686 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) { 3687 synchronized (networkAgent) { 3688 networkAgent.networkCapabilities = networkCapabilities; 3689 } 3690 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore()); 3691 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED); 3692 } 3693 } 3694 3695 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) { 3696 for (int i = 0; i < nai.networkRequests.size(); i++) { 3697 NetworkRequest nr = nai.networkRequests.valueAt(i); 3698 // Don't send listening requests to factories. b/17393458 3699 if (!isRequest(nr)) continue; 3700 sendUpdatedScoreToFactories(nr, nai.getCurrentScore()); 3701 } 3702 } 3703 3704 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) { 3705 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString()); 3706 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 3707 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0, 3708 networkRequest); 3709 } 3710 } 3711 3712 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent, 3713 int notificationType) { 3714 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) { 3715 Intent intent = new Intent(); 3716 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network); 3717 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request); 3718 nri.mPendingIntentSent = true; 3719 sendIntent(nri.mPendingIntent, intent); 3720 } 3721 // else not handled 3722 } 3723 3724 private void sendIntent(PendingIntent pendingIntent, Intent intent) { 3725 mPendingIntentWakeLock.acquire(); 3726 try { 3727 if (DBG) log("Sending " + pendingIntent); 3728 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */); 3729 } catch (PendingIntent.CanceledException e) { 3730 if (DBG) log(pendingIntent + " was not sent, it had been canceled."); 3731 mPendingIntentWakeLock.release(); 3732 releasePendingNetworkRequest(pendingIntent); 3733 } 3734 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished() 3735 } 3736 3737 @Override 3738 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, 3739 String resultData, Bundle resultExtras) { 3740 if (DBG) log("Finished sending " + pendingIntent); 3741 mPendingIntentWakeLock.release(); 3742 // Release with a delay so the receiving client has an opportunity to put in its 3743 // own request. 3744 releasePendingNetworkRequestWithDelay(pendingIntent); 3745 } 3746 3747 private void callCallbackForRequest(NetworkRequestInfo nri, 3748 NetworkAgentInfo networkAgent, int notificationType) { 3749 if (nri.messenger == null) return; // Default request has no msgr 3750 Bundle bundle = new Bundle(); 3751 bundle.putParcelable(NetworkRequest.class.getSimpleName(), 3752 new NetworkRequest(nri.request)); 3753 Message msg = Message.obtain(); 3754 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL && 3755 notificationType != ConnectivityManager.CALLBACK_RELEASED) { 3756 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network); 3757 } 3758 switch (notificationType) { 3759 case ConnectivityManager.CALLBACK_LOSING: { 3760 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor 3761 break; 3762 } 3763 case ConnectivityManager.CALLBACK_CAP_CHANGED: { 3764 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(), 3765 new NetworkCapabilities(networkAgent.networkCapabilities)); 3766 break; 3767 } 3768 case ConnectivityManager.CALLBACK_IP_CHANGED: { 3769 bundle.putParcelable(LinkProperties.class.getSimpleName(), 3770 new LinkProperties(networkAgent.linkProperties)); 3771 break; 3772 } 3773 } 3774 msg.what = notificationType; 3775 msg.setData(bundle); 3776 try { 3777 if (VDBG) { 3778 log("sending notification " + notifyTypeToName(notificationType) + 3779 " for " + nri.request); 3780 } 3781 nri.messenger.send(msg); 3782 } catch (RemoteException e) { 3783 // may occur naturally in the race of binder death. 3784 loge("RemoteException caught trying to send a callback msg for " + nri.request); 3785 } 3786 } 3787 3788 private void teardownUnneededNetwork(NetworkAgentInfo nai) { 3789 for (int i = 0; i < nai.networkRequests.size(); i++) { 3790 NetworkRequest nr = nai.networkRequests.valueAt(i); 3791 // Ignore listening requests. 3792 if (!isRequest(nr)) continue; 3793 loge("Dead network still had at least " + nr); 3794 break; 3795 } 3796 nai.asyncChannel.disconnect(); 3797 } 3798 3799 private void handleLingerComplete(NetworkAgentInfo oldNetwork) { 3800 if (oldNetwork == null) { 3801 loge("Unknown NetworkAgentInfo in handleLingerComplete"); 3802 return; 3803 } 3804 if (DBG) log("handleLingerComplete for " + oldNetwork.name()); 3805 teardownUnneededNetwork(oldNetwork); 3806 } 3807 3808 private void makeDefault(NetworkAgentInfo newNetwork) { 3809 if (DBG) log("Switching to new default network: " + newNetwork); 3810 setupDataActivityTracking(newNetwork); 3811 try { 3812 mNetd.setDefaultNetId(newNetwork.network.netId); 3813 } catch (Exception e) { 3814 loge("Exception setting default network :" + e); 3815 } 3816 notifyLockdownVpn(newNetwork); 3817 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy()); 3818 updateTcpBufferSizes(newNetwork); 3819 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers()); 3820 } 3821 3822 // Handles a network appearing or improving its score. 3823 // 3824 // - Evaluates all current NetworkRequests that can be 3825 // satisfied by newNetwork, and reassigns to newNetwork 3826 // any such requests for which newNetwork is the best. 3827 // 3828 // - Lingers any validated Networks that as a result are no longer 3829 // needed. A network is needed if it is the best network for 3830 // one or more NetworkRequests, or if it is a VPN. 3831 // 3832 // - Tears down newNetwork if it just became validated 3833 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded. 3834 // 3835 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated 3836 // networks that have no chance (i.e. even if validated) 3837 // of becoming the highest scoring network. 3838 // 3839 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy, 3840 // it does not remove NetworkRequests that other Networks could better satisfy. 3841 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}. 3842 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests} 3843 // as it performs better by a factor of the number of Networks. 3844 // 3845 // @param newNetwork is the network to be matched against NetworkRequests. 3846 // @param nascent indicates if newNetwork just became validated, in which case it should be 3847 // torn down if unneeded. 3848 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be 3849 // performed to tear down unvalidated networks that have no chance (i.e. even if 3850 // validated) of becoming the highest scoring network. 3851 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent, 3852 ReapUnvalidatedNetworks reapUnvalidatedNetworks) { 3853 if (!newNetwork.created) return; 3854 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) { 3855 loge("ERROR: nascent network not validated."); 3856 } 3857 boolean keep = newNetwork.isVPN(); 3858 boolean isNewDefault = false; 3859 NetworkAgentInfo oldDefaultNetwork = null; 3860 if (DBG) log("rematching " + newNetwork.name()); 3861 // Find and migrate to this Network any NetworkRequests for 3862 // which this network is now the best. 3863 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>(); 3864 if (VDBG) log(" network has: " + newNetwork.networkCapabilities); 3865 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 3866 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId); 3867 if (newNetwork == currentNetwork) { 3868 if (DBG) { 3869 log("Network " + newNetwork.name() + " was already satisfying" + 3870 " request " + nri.request.requestId + ". No change."); 3871 } 3872 keep = true; 3873 continue; 3874 } 3875 3876 // check if it satisfies the NetworkCapabilities 3877 if (VDBG) log(" checking if request is satisfied: " + nri.request); 3878 if (newNetwork.satisfies(nri.request)) { 3879 if (!nri.isRequest) { 3880 // This is not a request, it's a callback listener. 3881 // Add it to newNetwork regardless of score. 3882 newNetwork.addRequest(nri.request); 3883 continue; 3884 } 3885 3886 // next check if it's better than any current network we're using for 3887 // this request 3888 if (VDBG) { 3889 log("currentScore = " + 3890 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) + 3891 ", newScore = " + newNetwork.getCurrentScore()); 3892 } 3893 if (currentNetwork == null || 3894 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) { 3895 if (currentNetwork != null) { 3896 if (DBG) log(" accepting network in place of " + currentNetwork.name()); 3897 currentNetwork.networkRequests.remove(nri.request.requestId); 3898 currentNetwork.networkLingered.add(nri.request); 3899 affectedNetworks.add(currentNetwork); 3900 } else { 3901 if (DBG) log(" accepting network in place of null"); 3902 } 3903 unlinger(newNetwork); 3904 mNetworkForRequestId.put(nri.request.requestId, newNetwork); 3905 newNetwork.addRequest(nri.request); 3906 keep = true; 3907 // Tell NetworkFactories about the new score, so they can stop 3908 // trying to connect if they know they cannot match it. 3909 // TODO - this could get expensive if we have alot of requests for this 3910 // network. Think about if there is a way to reduce this. Push 3911 // netid->request mapping to each factory? 3912 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore()); 3913 if (mDefaultRequest.requestId == nri.request.requestId) { 3914 isNewDefault = true; 3915 oldDefaultNetwork = currentNetwork; 3916 } 3917 } 3918 } 3919 } 3920 // Linger any networks that are no longer needed. 3921 for (NetworkAgentInfo nai : affectedNetworks) { 3922 if (nai.everValidated && unneeded(nai)) { 3923 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER); 3924 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING); 3925 } else { 3926 unlinger(nai); 3927 } 3928 } 3929 if (keep) { 3930 if (isNewDefault) { 3931 // Notify system services that this network is up. 3932 makeDefault(newNetwork); 3933 synchronized (ConnectivityService.this) { 3934 // have a new default network, release the transition wakelock in 3935 // a second if it's held. The second pause is to allow apps 3936 // to reconnect over the new network 3937 if (mNetTransitionWakeLock.isHeld()) { 3938 mHandler.sendMessageDelayed(mHandler.obtainMessage( 3939 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 3940 mNetTransitionWakeLockSerialNumber, 0), 3941 1000); 3942 } 3943 } 3944 } 3945 3946 // do this after the default net is switched, but 3947 // before LegacyTypeTracker sends legacy broadcasts 3948 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE); 3949 3950 if (isNewDefault) { 3951 // Maintain the illusion: since the legacy API only 3952 // understands one network at a time, we must pretend 3953 // that the current default network disconnected before 3954 // the new one connected. 3955 if (oldDefaultNetwork != null) { 3956 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(), 3957 oldDefaultNetwork); 3958 } 3959 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0; 3960 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork); 3961 notifyLockdownVpn(newNetwork); 3962 } 3963 3964 // Notify battery stats service about this network, both the normal 3965 // interface and any stacked links. 3966 // TODO: Avoid redoing this; this must only be done once when a network comes online. 3967 try { 3968 final IBatteryStats bs = BatteryStatsService.getService(); 3969 final int type = newNetwork.networkInfo.getType(); 3970 3971 final String baseIface = newNetwork.linkProperties.getInterfaceName(); 3972 bs.noteNetworkInterfaceType(baseIface, type); 3973 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) { 3974 final String stackedIface = stacked.getInterfaceName(); 3975 bs.noteNetworkInterfaceType(stackedIface, type); 3976 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface); 3977 } 3978 } catch (RemoteException ignored) { 3979 } 3980 3981 // This has to happen after the notifyNetworkCallbacks as that tickles each 3982 // ConnectivityManager instance so that legacy requests correctly bind dns 3983 // requests to this network. The legacy users are listening for this bcast 3984 // and will generally do a dns request so they can ensureRouteToHost and if 3985 // they do that before the callbacks happen they'll use the default network. 3986 // 3987 // TODO: Is there still a race here? We send the broadcast 3988 // after sending the callback, but if the app can receive the 3989 // broadcast before the callback, it might still break. 3990 // 3991 // This *does* introduce a race where if the user uses the new api 3992 // (notification callbacks) and then uses the old api (getNetworkInfo(type)) 3993 // they may get old info. Reverse this after the old startUsing api is removed. 3994 // This is on top of the multiple intent sequencing referenced in the todo above. 3995 for (int i = 0; i < newNetwork.networkRequests.size(); i++) { 3996 NetworkRequest nr = newNetwork.networkRequests.valueAt(i); 3997 if (nr.legacyType != TYPE_NONE && isRequest(nr)) { 3998 // legacy type tracker filters out repeat adds 3999 mLegacyTypeTracker.add(nr.legacyType, newNetwork); 4000 } 4001 } 4002 4003 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above, 4004 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest 4005 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the 4006 // newNetwork to the tracker explicitly (it's a no-op if it has already been added). 4007 if (newNetwork.isVPN()) { 4008 mLegacyTypeTracker.add(TYPE_VPN, newNetwork); 4009 } 4010 } else if (nascent == NascentState.JUST_VALIDATED) { 4011 // Only tear down newly validated networks here. Leave unvalidated to either become 4012 // validated (and get evaluated against peers, one losing here), or get reaped (see 4013 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring 4014 // network. Networks that have been up for a while and are validated should be torn 4015 // down via the lingering process so communication on that network is given time to 4016 // wrap up. 4017 if (DBG) log("Validated network turns out to be unwanted. Tear it down."); 4018 teardownUnneededNetwork(newNetwork); 4019 } 4020 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) { 4021 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 4022 if (!nai.everValidated && unneeded(nai)) { 4023 if (DBG) log("Reaping " + nai.name()); 4024 teardownUnneededNetwork(nai); 4025 } 4026 } 4027 } 4028 } 4029 4030 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks 4031 // being disconnected. 4032 // If only one Network's score or capabilities have been modified since the last time 4033 // this function was called, pass this Network in via the "changed" arugment, otherwise 4034 // pass null. 4035 // If only one Network has been changed but its NetworkCapabilities have not changed, 4036 // pass in the Network's score (from getCurrentScore()) prior to the change via 4037 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null. 4038 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) { 4039 // TODO: This may get slow. The "changed" parameter is provided for future optimization 4040 // to avoid the slowness. It is not simply enough to process just "changed", for 4041 // example in the case where "changed"'s score decreases and another network should begin 4042 // satifying a NetworkRequest that "changed" currently satisfies. 4043 4044 // Optimization: Only reprocess "changed" if its score improved. This is safe because it 4045 // can only add more NetworkRequests satisfied by "changed", and this is exactly what 4046 // rematchNetworkAndRequests() handles. 4047 if (changed != null && oldScore < changed.getCurrentScore()) { 4048 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED, 4049 ReapUnvalidatedNetworks.REAP); 4050 } else { 4051 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) { 4052 rematchNetworkAndRequests((NetworkAgentInfo)i.next(), 4053 NascentState.NOT_JUST_VALIDATED, 4054 // Only reap the last time through the loop. Reaping before all rematching 4055 // is complete could incorrectly teardown a network that hasn't yet been 4056 // rematched. 4057 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP 4058 : ReapUnvalidatedNetworks.REAP); 4059 } 4060 } 4061 } 4062 4063 private void updateInetCondition(NetworkAgentInfo nai) { 4064 // Don't bother updating until we've graduated to validated at least once. 4065 if (!nai.everValidated) return; 4066 // For now only update icons for default connection. 4067 // TODO: Update WiFi and cellular icons separately. b/17237507 4068 if (!isDefaultNetwork(nai)) return; 4069 4070 int newInetCondition = nai.lastValidated ? 100 : 0; 4071 // Don't repeat publish. 4072 if (newInetCondition == mDefaultInetConditionPublished) return; 4073 4074 mDefaultInetConditionPublished = newInetCondition; 4075 sendInetConditionBroadcast(nai.networkInfo); 4076 } 4077 4078 private void notifyLockdownVpn(NetworkAgentInfo nai) { 4079 if (mLockdownTracker != null) { 4080 if (nai != null && nai.isVPN()) { 4081 mLockdownTracker.onVpnStateChanged(nai.networkInfo); 4082 } else { 4083 mLockdownTracker.onNetworkInfoChanged(); 4084 } 4085 } 4086 } 4087 4088 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) { 4089 NetworkInfo.State state = newInfo.getState(); 4090 NetworkInfo oldInfo = null; 4091 synchronized (networkAgent) { 4092 oldInfo = networkAgent.networkInfo; 4093 networkAgent.networkInfo = newInfo; 4094 } 4095 notifyLockdownVpn(networkAgent); 4096 4097 if (oldInfo != null && oldInfo.getState() == state) { 4098 if (VDBG) log("ignoring duplicate network state non-change"); 4099 return; 4100 } 4101 if (DBG) { 4102 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " + 4103 (oldInfo == null ? "null" : oldInfo.getState()) + 4104 " to " + state); 4105 } 4106 4107 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) { 4108 try { 4109 // This should never fail. Specifying an already in use NetID will cause failure. 4110 if (networkAgent.isVPN()) { 4111 mNetd.createVirtualNetwork(networkAgent.network.netId, 4112 !networkAgent.linkProperties.getDnsServers().isEmpty(), 4113 (networkAgent.networkMisc == null || 4114 !networkAgent.networkMisc.allowBypass)); 4115 } else { 4116 mNetd.createPhysicalNetwork(networkAgent.network.netId); 4117 } 4118 } catch (Exception e) { 4119 loge("Error creating network " + networkAgent.network.netId + ": " 4120 + e.getMessage()); 4121 return; 4122 } 4123 networkAgent.created = true; 4124 updateLinkProperties(networkAgent, null); 4125 notifyIfacesChanged(); 4126 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK); 4127 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 4128 if (networkAgent.isVPN()) { 4129 // Temporarily disable the default proxy (not global). 4130 synchronized (mProxyLock) { 4131 if (!mDefaultProxyDisabled) { 4132 mDefaultProxyDisabled = true; 4133 if (mGlobalProxy == null && mDefaultProxy != null) { 4134 sendProxyBroadcast(null); 4135 } 4136 } 4137 } 4138 // TODO: support proxy per network. 4139 } 4140 // Consider network even though it is not yet validated. 4141 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED, 4142 ReapUnvalidatedNetworks.REAP); 4143 } else if (state == NetworkInfo.State.DISCONNECTED || 4144 state == NetworkInfo.State.SUSPENDED) { 4145 networkAgent.asyncChannel.disconnect(); 4146 if (networkAgent.isVPN()) { 4147 synchronized (mProxyLock) { 4148 if (mDefaultProxyDisabled) { 4149 mDefaultProxyDisabled = false; 4150 if (mGlobalProxy == null && mDefaultProxy != null) { 4151 sendProxyBroadcast(mDefaultProxy); 4152 } 4153 } 4154 } 4155 } 4156 } 4157 } 4158 4159 private void updateNetworkScore(NetworkAgentInfo nai, int score) { 4160 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score); 4161 if (score < 0) { 4162 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score + 4163 "). Bumping score to min of 0"); 4164 score = 0; 4165 } 4166 4167 final int oldScore = nai.getCurrentScore(); 4168 nai.setCurrentScore(score); 4169 4170 rematchAllNetworksAndRequests(nai, oldScore); 4171 4172 sendUpdatedScoreToFactories(nai); 4173 } 4174 4175 // notify only this one new request of the current state 4176 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) { 4177 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE; 4178 // TODO - read state from monitor to decide what to send. 4179// if (nai.networkMonitor.isLingering()) { 4180// notifyType = NetworkCallbacks.LOSING; 4181// } else if (nai.networkMonitor.isEvaluating()) { 4182// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType); 4183// } 4184 if (nri.mPendingIntent == null) { 4185 callCallbackForRequest(nri, nai, notifyType); 4186 } else { 4187 sendPendingIntentForRequest(nri, nai, notifyType); 4188 } 4189 } 4190 4191 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) { 4192 // The NetworkInfo we actually send out has no bearing on the real 4193 // state of affairs. For example, if the default connection is mobile, 4194 // and a request for HIPRI has just gone away, we need to pretend that 4195 // HIPRI has just disconnected. So we need to set the type to HIPRI and 4196 // the state to DISCONNECTED, even though the network is of type MOBILE 4197 // and is still connected. 4198 NetworkInfo info = new NetworkInfo(nai.networkInfo); 4199 info.setType(type); 4200 if (connected) { 4201 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo()); 4202 sendConnectedBroadcast(info); 4203 } else { 4204 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo()); 4205 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 4206 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 4207 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 4208 if (info.isFailover()) { 4209 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 4210 nai.networkInfo.setFailover(false); 4211 } 4212 if (info.getReason() != null) { 4213 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 4214 } 4215 if (info.getExtraInfo() != null) { 4216 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo()); 4217 } 4218 NetworkAgentInfo newDefaultAgent = null; 4219 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 4220 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId); 4221 if (newDefaultAgent != null) { 4222 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, 4223 newDefaultAgent.networkInfo); 4224 } else { 4225 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 4226 } 4227 } 4228 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, 4229 mDefaultInetConditionPublished); 4230 final Intent immediateIntent = new Intent(intent); 4231 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE); 4232 sendStickyBroadcast(immediateIntent); 4233 sendStickyBroadcast(intent); 4234 if (newDefaultAgent != null) { 4235 sendConnectedBroadcast(newDefaultAgent.networkInfo); 4236 } 4237 } 4238 } 4239 4240 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) { 4241 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name()); 4242 for (int i = 0; i < networkAgent.networkRequests.size(); i++) { 4243 NetworkRequest nr = networkAgent.networkRequests.valueAt(i); 4244 NetworkRequestInfo nri = mNetworkRequests.get(nr); 4245 if (VDBG) log(" sending notification for " + nr); 4246 if (nri.mPendingIntent == null) { 4247 callCallbackForRequest(nri, networkAgent, notifyType); 4248 } else { 4249 sendPendingIntentForRequest(nri, networkAgent, notifyType); 4250 } 4251 } 4252 } 4253 4254 private String notifyTypeToName(int notifyType) { 4255 switch (notifyType) { 4256 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK"; 4257 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE"; 4258 case ConnectivityManager.CALLBACK_LOSING: return "LOSING"; 4259 case ConnectivityManager.CALLBACK_LOST: return "LOST"; 4260 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE"; 4261 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED"; 4262 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED"; 4263 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED"; 4264 } 4265 return "UNKNOWN"; 4266 } 4267 4268 /** 4269 * Notify other system services that set of active ifaces has changed. 4270 */ 4271 private void notifyIfacesChanged() { 4272 try { 4273 mStatsService.forceUpdateIfaces(); 4274 } catch (Exception ignored) { 4275 } 4276 } 4277 4278 @Override 4279 public boolean addVpnAddress(String address, int prefixLength) { 4280 throwIfLockdownEnabled(); 4281 int user = UserHandle.getUserId(Binder.getCallingUid()); 4282 synchronized (mVpns) { 4283 return mVpns.get(user).addAddress(address, prefixLength); 4284 } 4285 } 4286 4287 @Override 4288 public boolean removeVpnAddress(String address, int prefixLength) { 4289 throwIfLockdownEnabled(); 4290 int user = UserHandle.getUserId(Binder.getCallingUid()); 4291 synchronized (mVpns) { 4292 return mVpns.get(user).removeAddress(address, prefixLength); 4293 } 4294 } 4295 4296 @Override 4297 public boolean setUnderlyingNetworksForVpn(Network[] networks) { 4298 throwIfLockdownEnabled(); 4299 int user = UserHandle.getUserId(Binder.getCallingUid()); 4300 boolean success; 4301 synchronized (mVpns) { 4302 success = mVpns.get(user).setUnderlyingNetworks(networks); 4303 } 4304 if (success) { 4305 notifyIfacesChanged(); 4306 } 4307 return success; 4308 } 4309} 4310