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