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