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