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