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