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