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