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