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