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