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