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