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