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