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