ConnectivityService.java revision 1bbcaa0fc4e514baf8242b147f5ad40782d9f801
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 if (!nri.isRequest) { 2113 // Not setting bestNetwork here as a listening NetworkRequest may be 2114 // satisfied by multiple Networks. Instead the request is added to 2115 // each satisfying Network and notified about each. 2116 network.addRequest(nri.request); 2117 notifyNetworkCallback(network, nri); 2118 } else { 2119 bestNetwork = network; 2120 } 2121 } 2122 } 2123 } 2124 if (bestNetwork != null) { 2125 if (VDBG) log("using " + bestNetwork.name()); 2126 if (bestNetwork.networkInfo.isConnected()) { 2127 // Cancel any lingering so the linger timeout doesn't teardown this network 2128 // even though we have a request for it. 2129 bestNetwork.networkLingered.clear(); 2130 bestNetwork.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 2131 } 2132 bestNetwork.addRequest(nri.request); 2133 mNetworkForRequestId.put(nri.request.requestId, bestNetwork); 2134 notifyNetworkCallback(bestNetwork, nri); 2135 score = bestNetwork.currentScore; 2136 if (nri.request.legacyType != TYPE_NONE) { 2137 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork); 2138 } 2139 } 2140 mNetworkRequests.put(nri.request, nri); 2141 if (nri.isRequest) { 2142 if (DBG) log("sending new NetworkRequest to factories"); 2143 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 2144 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 2145 0, nri.request); 2146 } 2147 } 2148 } 2149 2150 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) { 2151 NetworkRequestInfo nri = mNetworkRequests.get(request); 2152 if (nri != null) { 2153 if (nri.mUid != callingUid) { 2154 if (DBG) log("Attempt to release unowned NetworkRequest " + request); 2155 return; 2156 } 2157 if (DBG) log("releasing NetworkRequest " + request); 2158 nri.unlinkDeathRecipient(); 2159 mNetworkRequests.remove(request); 2160 // tell the network currently servicing this that it's no longer interested 2161 NetworkAgentInfo affectedNetwork = mNetworkForRequestId.get(nri.request.requestId); 2162 if (affectedNetwork != null) { 2163 mNetworkForRequestId.remove(nri.request.requestId); 2164 affectedNetwork.networkRequests.remove(nri.request.requestId); 2165 if (VDBG) { 2166 log(" Removing from current network " + affectedNetwork.name() + ", leaving " + 2167 affectedNetwork.networkRequests.size() + " requests."); 2168 } 2169 if (nri.isRequest && nri.request.legacyType != TYPE_NONE) { 2170 mLegacyTypeTracker.remove(nri.request.legacyType, affectedNetwork); 2171 } 2172 } 2173 2174 if (nri.isRequest) { 2175 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 2176 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST, 2177 nri.request); 2178 } 2179 2180 if (affectedNetwork != null) { 2181 // check if this network still has live requests - otherwise, tear down 2182 // TODO - probably push this to the NF/NA 2183 boolean keep = affectedNetwork.isVPN(); 2184 for (int i = 0; i < affectedNetwork.networkRequests.size() && !keep; i++) { 2185 NetworkRequest r = affectedNetwork.networkRequests.valueAt(i); 2186 if (mNetworkRequests.get(r).isRequest) { 2187 keep = true; 2188 } 2189 } 2190 if (keep == false) { 2191 if (DBG) log("no live requests for " + affectedNetwork.name() + 2192 "; disconnecting"); 2193 affectedNetwork.asyncChannel.disconnect(); 2194 } 2195 } 2196 } 2197 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED); 2198 } 2199 } 2200 2201 private class InternalHandler extends Handler { 2202 public InternalHandler(Looper looper) { 2203 super(looper); 2204 } 2205 2206 @Override 2207 public void handleMessage(Message msg) { 2208 NetworkInfo info; 2209 switch (msg.what) { 2210 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK: 2211 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: { 2212 String causedBy = null; 2213 synchronized (ConnectivityService.this) { 2214 if (msg.arg1 == mNetTransitionWakeLockSerialNumber && 2215 mNetTransitionWakeLock.isHeld()) { 2216 mNetTransitionWakeLock.release(); 2217 causedBy = mNetTransitionWakeLockCausedBy; 2218 } else { 2219 break; 2220 } 2221 } 2222 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) { 2223 log("Failed to find a new network - expiring NetTransition Wakelock"); 2224 } else { 2225 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) + 2226 " cleared because we found a replacement network"); 2227 } 2228 break; 2229 } 2230 case EVENT_APPLY_GLOBAL_HTTP_PROXY: { 2231 handleDeprecatedGlobalHttpProxy(); 2232 break; 2233 } 2234 case EVENT_SET_DEPENDENCY_MET: { 2235 boolean met = (msg.arg1 == ENABLED); 2236 handleSetDependencyMet(msg.arg2, met); 2237 break; 2238 } 2239 case EVENT_SEND_STICKY_BROADCAST_INTENT: { 2240 Intent intent = (Intent)msg.obj; 2241 sendStickyBroadcast(intent); 2242 break; 2243 } 2244 case EVENT_SET_POLICY_DATA_ENABLE: { 2245 final int networkType = msg.arg1; 2246 final boolean enabled = msg.arg2 == ENABLED; 2247 handleSetPolicyDataEnable(networkType, enabled); 2248 break; 2249 } 2250 case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: { 2251 int tag = mEnableFailFastMobileDataTag.get(); 2252 if (msg.arg1 == tag) { 2253 MobileDataStateTracker mobileDst = 2254 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 2255 if (mobileDst != null) { 2256 mobileDst.setEnableFailFastMobileData(msg.arg2); 2257 } 2258 } else { 2259 log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1 2260 + " != tag:" + tag); 2261 } 2262 break; 2263 } 2264 case EVENT_SAMPLE_INTERVAL_ELAPSED: { 2265 handleNetworkSamplingTimeout(); 2266 break; 2267 } 2268 case EVENT_PROXY_HAS_CHANGED: { 2269 handleApplyDefaultProxy((ProxyInfo)msg.obj); 2270 break; 2271 } 2272 case EVENT_REGISTER_NETWORK_FACTORY: { 2273 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj); 2274 break; 2275 } 2276 case EVENT_UNREGISTER_NETWORK_FACTORY: { 2277 handleUnregisterNetworkFactory((Messenger)msg.obj); 2278 break; 2279 } 2280 case EVENT_REGISTER_NETWORK_AGENT: { 2281 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj); 2282 break; 2283 } 2284 case EVENT_REGISTER_NETWORK_REQUEST: 2285 case EVENT_REGISTER_NETWORK_LISTENER: { 2286 handleRegisterNetworkRequest(msg); 2287 break; 2288 } 2289 case EVENT_RELEASE_NETWORK_REQUEST: { 2290 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1); 2291 break; 2292 } 2293 case EVENT_SYSTEM_READY: { 2294 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) { 2295 nai.networkMonitor.systemReady = true; 2296 } 2297 break; 2298 } 2299 } 2300 } 2301 } 2302 2303 // javadoc from interface 2304 public int tether(String iface) { 2305 enforceTetherChangePermission(); 2306 2307 if (isTetheringSupported()) { 2308 return mTethering.tether(iface); 2309 } else { 2310 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2311 } 2312 } 2313 2314 // javadoc from interface 2315 public int untether(String iface) { 2316 enforceTetherChangePermission(); 2317 2318 if (isTetheringSupported()) { 2319 return mTethering.untether(iface); 2320 } else { 2321 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2322 } 2323 } 2324 2325 // javadoc from interface 2326 public int getLastTetherError(String iface) { 2327 enforceTetherAccessPermission(); 2328 2329 if (isTetheringSupported()) { 2330 return mTethering.getLastTetherError(iface); 2331 } else { 2332 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2333 } 2334 } 2335 2336 // TODO - proper iface API for selection by property, inspection, etc 2337 public String[] getTetherableUsbRegexs() { 2338 enforceTetherAccessPermission(); 2339 if (isTetheringSupported()) { 2340 return mTethering.getTetherableUsbRegexs(); 2341 } else { 2342 return new String[0]; 2343 } 2344 } 2345 2346 public String[] getTetherableWifiRegexs() { 2347 enforceTetherAccessPermission(); 2348 if (isTetheringSupported()) { 2349 return mTethering.getTetherableWifiRegexs(); 2350 } else { 2351 return new String[0]; 2352 } 2353 } 2354 2355 public String[] getTetherableBluetoothRegexs() { 2356 enforceTetherAccessPermission(); 2357 if (isTetheringSupported()) { 2358 return mTethering.getTetherableBluetoothRegexs(); 2359 } else { 2360 return new String[0]; 2361 } 2362 } 2363 2364 public int setUsbTethering(boolean enable) { 2365 enforceTetherChangePermission(); 2366 if (isTetheringSupported()) { 2367 return mTethering.setUsbTethering(enable); 2368 } else { 2369 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED; 2370 } 2371 } 2372 2373 // TODO - move iface listing, queries, etc to new module 2374 // javadoc from interface 2375 public String[] getTetherableIfaces() { 2376 enforceTetherAccessPermission(); 2377 return mTethering.getTetherableIfaces(); 2378 } 2379 2380 public String[] getTetheredIfaces() { 2381 enforceTetherAccessPermission(); 2382 return mTethering.getTetheredIfaces(); 2383 } 2384 2385 public String[] getTetheringErroredIfaces() { 2386 enforceTetherAccessPermission(); 2387 return mTethering.getErroredIfaces(); 2388 } 2389 2390 public String[] getTetheredDhcpRanges() { 2391 enforceConnectivityInternalPermission(); 2392 return mTethering.getTetheredDhcpRanges(); 2393 } 2394 2395 // if ro.tether.denied = true we default to no tethering 2396 // gservices could set the secure setting to 1 though to enable it on a build where it 2397 // had previously been turned off. 2398 public boolean isTetheringSupported() { 2399 enforceTetherAccessPermission(); 2400 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1); 2401 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(), 2402 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0) 2403 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING); 2404 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 || 2405 mTethering.getTetherableWifiRegexs().length != 0 || 2406 mTethering.getTetherableBluetoothRegexs().length != 0) && 2407 mTethering.getUpstreamIfaceTypes().length != 0); 2408 } 2409 2410 // Called when we lose the default network and have no replacement yet. 2411 // This will automatically be cleared after X seconds or a new default network 2412 // becomes CONNECTED, whichever happens first. The timer is started by the 2413 // first caller and not restarted by subsequent callers. 2414 private void requestNetworkTransitionWakelock(String forWhom) { 2415 int serialNum = 0; 2416 synchronized (this) { 2417 if (mNetTransitionWakeLock.isHeld()) return; 2418 serialNum = ++mNetTransitionWakeLockSerialNumber; 2419 mNetTransitionWakeLock.acquire(); 2420 mNetTransitionWakeLockCausedBy = forWhom; 2421 } 2422 mHandler.sendMessageDelayed(mHandler.obtainMessage( 2423 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0), 2424 mNetTransitionWakeLockTimeout); 2425 return; 2426 } 2427 2428 // 100 percent is full good, 0 is full bad. 2429 public void reportInetCondition(int networkType, int percentage) { 2430 if (percentage > 50) return; // don't handle good network reports 2431 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 2432 if (nai != null) reportBadNetwork(nai.network); 2433 } 2434 2435 public void reportBadNetwork(Network network) { 2436 //TODO 2437 } 2438 2439 public ProxyInfo getProxy() { 2440 // this information is already available as a world read/writable jvm property 2441 // so this API change wouldn't have a benifit. It also breaks the passing 2442 // of proxy info to all the JVMs. 2443 // enforceAccessPermission(); 2444 synchronized (mProxyLock) { 2445 ProxyInfo ret = mGlobalProxy; 2446 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy; 2447 return ret; 2448 } 2449 } 2450 2451 public void setGlobalProxy(ProxyInfo proxyProperties) { 2452 enforceConnectivityInternalPermission(); 2453 2454 synchronized (mProxyLock) { 2455 if (proxyProperties == mGlobalProxy) return; 2456 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return; 2457 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return; 2458 2459 String host = ""; 2460 int port = 0; 2461 String exclList = ""; 2462 String pacFileUrl = ""; 2463 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) || 2464 (proxyProperties.getPacFileUrl() != null))) { 2465 if (!proxyProperties.isValid()) { 2466 if (DBG) 2467 log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 2468 return; 2469 } 2470 mGlobalProxy = new ProxyInfo(proxyProperties); 2471 host = mGlobalProxy.getHost(); 2472 port = mGlobalProxy.getPort(); 2473 exclList = mGlobalProxy.getExclusionListAsString(); 2474 if (proxyProperties.getPacFileUrl() != null) { 2475 pacFileUrl = proxyProperties.getPacFileUrl().toString(); 2476 } 2477 } else { 2478 mGlobalProxy = null; 2479 } 2480 ContentResolver res = mContext.getContentResolver(); 2481 final long token = Binder.clearCallingIdentity(); 2482 try { 2483 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host); 2484 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port); 2485 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 2486 exclList); 2487 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl); 2488 } finally { 2489 Binder.restoreCallingIdentity(token); 2490 } 2491 } 2492 2493 if (mGlobalProxy == null) { 2494 proxyProperties = mDefaultProxy; 2495 } 2496 sendProxyBroadcast(proxyProperties); 2497 } 2498 2499 private void loadGlobalProxy() { 2500 ContentResolver res = mContext.getContentResolver(); 2501 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST); 2502 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0); 2503 String exclList = Settings.Global.getString(res, 2504 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST); 2505 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC); 2506 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) { 2507 ProxyInfo proxyProperties; 2508 if (!TextUtils.isEmpty(pacFileUrl)) { 2509 proxyProperties = new ProxyInfo(pacFileUrl); 2510 } else { 2511 proxyProperties = new ProxyInfo(host, port, exclList); 2512 } 2513 if (!proxyProperties.isValid()) { 2514 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString()); 2515 return; 2516 } 2517 2518 synchronized (mProxyLock) { 2519 mGlobalProxy = proxyProperties; 2520 } 2521 } 2522 } 2523 2524 public ProxyInfo getGlobalProxy() { 2525 // this information is already available as a world read/writable jvm property 2526 // so this API change wouldn't have a benifit. It also breaks the passing 2527 // of proxy info to all the JVMs. 2528 // enforceAccessPermission(); 2529 synchronized (mProxyLock) { 2530 return mGlobalProxy; 2531 } 2532 } 2533 2534 private void handleApplyDefaultProxy(ProxyInfo proxy) { 2535 if (proxy != null && TextUtils.isEmpty(proxy.getHost()) 2536 && (proxy.getPacFileUrl() == null)) { 2537 proxy = null; 2538 } 2539 synchronized (mProxyLock) { 2540 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return; 2541 if (mDefaultProxy == proxy) return; // catches repeated nulls 2542 if (proxy != null && !proxy.isValid()) { 2543 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString()); 2544 return; 2545 } 2546 2547 // This call could be coming from the PacManager, containing the port of the local 2548 // proxy. If this new proxy matches the global proxy then copy this proxy to the 2549 // global (to get the correct local port), and send a broadcast. 2550 // TODO: Switch PacManager to have its own message to send back rather than 2551 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy. 2552 if ((mGlobalProxy != null) && (proxy != null) && (proxy.getPacFileUrl() != null) 2553 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) { 2554 mGlobalProxy = proxy; 2555 sendProxyBroadcast(mGlobalProxy); 2556 return; 2557 } 2558 mDefaultProxy = proxy; 2559 2560 if (mGlobalProxy != null) return; 2561 if (!mDefaultProxyDisabled) { 2562 sendProxyBroadcast(proxy); 2563 } 2564 } 2565 } 2566 2567 private void handleDeprecatedGlobalHttpProxy() { 2568 String proxy = Settings.Global.getString(mContext.getContentResolver(), 2569 Settings.Global.HTTP_PROXY); 2570 if (!TextUtils.isEmpty(proxy)) { 2571 String data[] = proxy.split(":"); 2572 if (data.length == 0) { 2573 return; 2574 } 2575 2576 String proxyHost = data[0]; 2577 int proxyPort = 8080; 2578 if (data.length > 1) { 2579 try { 2580 proxyPort = Integer.parseInt(data[1]); 2581 } catch (NumberFormatException e) { 2582 return; 2583 } 2584 } 2585 ProxyInfo p = new ProxyInfo(data[0], proxyPort, ""); 2586 setGlobalProxy(p); 2587 } 2588 } 2589 2590 private void sendProxyBroadcast(ProxyInfo proxy) { 2591 if (proxy == null) proxy = new ProxyInfo("", 0, ""); 2592 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return; 2593 if (DBG) log("sending Proxy Broadcast for " + proxy); 2594 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION); 2595 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING | 2596 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 2597 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy); 2598 final long ident = Binder.clearCallingIdentity(); 2599 try { 2600 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 2601 } finally { 2602 Binder.restoreCallingIdentity(ident); 2603 } 2604 } 2605 2606 private static class SettingsObserver extends ContentObserver { 2607 private int mWhat; 2608 private Handler mHandler; 2609 SettingsObserver(Handler handler, int what) { 2610 super(handler); 2611 mHandler = handler; 2612 mWhat = what; 2613 } 2614 2615 void observe(Context context) { 2616 ContentResolver resolver = context.getContentResolver(); 2617 resolver.registerContentObserver(Settings.Global.getUriFor( 2618 Settings.Global.HTTP_PROXY), false, this); 2619 } 2620 2621 @Override 2622 public void onChange(boolean selfChange) { 2623 mHandler.obtainMessage(mWhat).sendToTarget(); 2624 } 2625 } 2626 2627 private static void log(String s) { 2628 Slog.d(TAG, s); 2629 } 2630 2631 private static void loge(String s) { 2632 Slog.e(TAG, s); 2633 } 2634 2635 int convertFeatureToNetworkType(int networkType, String feature) { 2636 int usedNetworkType = networkType; 2637 2638 if(networkType == ConnectivityManager.TYPE_MOBILE) { 2639 if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) { 2640 usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS; 2641 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) { 2642 usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL; 2643 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) || 2644 TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) { 2645 usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN; 2646 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) { 2647 usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI; 2648 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) { 2649 usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA; 2650 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) { 2651 usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS; 2652 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) { 2653 usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS; 2654 } else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_EMERGENCY)) { 2655 usedNetworkType = ConnectivityManager.TYPE_MOBILE_EMERGENCY; 2656 } else { 2657 Slog.e(TAG, "Can't match any mobile netTracker!"); 2658 } 2659 } else if (networkType == ConnectivityManager.TYPE_WIFI) { 2660 if (TextUtils.equals(feature, "p2p")) { 2661 usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P; 2662 } else { 2663 Slog.e(TAG, "Can't match any wifi netTracker!"); 2664 } 2665 } else { 2666 Slog.e(TAG, "Unexpected network type"); 2667 } 2668 return usedNetworkType; 2669 } 2670 2671 private static <T> T checkNotNull(T value, String message) { 2672 if (value == null) { 2673 throw new NullPointerException(message); 2674 } 2675 return value; 2676 } 2677 2678 /** 2679 * Prepare for a VPN application. This method is used by VpnDialogs 2680 * and not available in ConnectivityManager. Permissions are checked 2681 * in Vpn class. 2682 * @hide 2683 */ 2684 @Override 2685 public boolean prepareVpn(String oldPackage, String newPackage) { 2686 throwIfLockdownEnabled(); 2687 int user = UserHandle.getUserId(Binder.getCallingUid()); 2688 synchronized(mVpns) { 2689 return mVpns.get(user).prepare(oldPackage, newPackage); 2690 } 2691 } 2692 2693 /** 2694 * Set whether the current VPN package has the ability to launch VPNs without 2695 * user intervention. This method is used by system UIs and not available 2696 * in ConnectivityManager. Permissions are checked in Vpn class. 2697 * @hide 2698 */ 2699 @Override 2700 public void setVpnPackageAuthorization(boolean authorized) { 2701 int user = UserHandle.getUserId(Binder.getCallingUid()); 2702 synchronized(mVpns) { 2703 mVpns.get(user).setPackageAuthorization(authorized); 2704 } 2705 } 2706 2707 /** 2708 * Configure a TUN interface and return its file descriptor. Parameters 2709 * are encoded and opaque to this class. This method is used by VpnBuilder 2710 * and not available in ConnectivityManager. Permissions are checked in 2711 * Vpn class. 2712 * @hide 2713 */ 2714 @Override 2715 public ParcelFileDescriptor establishVpn(VpnConfig config) { 2716 throwIfLockdownEnabled(); 2717 int user = UserHandle.getUserId(Binder.getCallingUid()); 2718 synchronized(mVpns) { 2719 return mVpns.get(user).establish(config); 2720 } 2721 } 2722 2723 /** 2724 * Start legacy VPN, controlling native daemons as needed. Creates a 2725 * secondary thread to perform connection work, returning quickly. 2726 */ 2727 @Override 2728 public void startLegacyVpn(VpnProfile profile) { 2729 throwIfLockdownEnabled(); 2730 final LinkProperties egress = getActiveLinkProperties(); 2731 if (egress == null) { 2732 throw new IllegalStateException("Missing active network connection"); 2733 } 2734 int user = UserHandle.getUserId(Binder.getCallingUid()); 2735 synchronized(mVpns) { 2736 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress); 2737 } 2738 } 2739 2740 /** 2741 * Return the information of the ongoing legacy VPN. This method is used 2742 * by VpnSettings and not available in ConnectivityManager. Permissions 2743 * are checked in Vpn class. 2744 * @hide 2745 */ 2746 @Override 2747 public LegacyVpnInfo getLegacyVpnInfo() { 2748 throwIfLockdownEnabled(); 2749 int user = UserHandle.getUserId(Binder.getCallingUid()); 2750 synchronized(mVpns) { 2751 return mVpns.get(user).getLegacyVpnInfo(); 2752 } 2753 } 2754 2755 /** 2756 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and 2757 * not available in ConnectivityManager. 2758 * Permissions are checked in Vpn class. 2759 * @hide 2760 */ 2761 @Override 2762 public VpnConfig getVpnConfig() { 2763 int user = UserHandle.getUserId(Binder.getCallingUid()); 2764 synchronized(mVpns) { 2765 return mVpns.get(user).getVpnConfig(); 2766 } 2767 } 2768 2769 @Override 2770 public boolean updateLockdownVpn() { 2771 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 2772 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM"); 2773 return false; 2774 } 2775 2776 // Tear down existing lockdown if profile was removed 2777 mLockdownEnabled = LockdownVpnTracker.isEnabled(); 2778 if (mLockdownEnabled) { 2779 if (!mKeyStore.isUnlocked()) { 2780 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker"); 2781 return false; 2782 } 2783 2784 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN)); 2785 final VpnProfile profile = VpnProfile.decode( 2786 profileName, mKeyStore.get(Credentials.VPN + profileName)); 2787 int user = UserHandle.getUserId(Binder.getCallingUid()); 2788 synchronized(mVpns) { 2789 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user), 2790 profile)); 2791 } 2792 } else { 2793 setLockdownTracker(null); 2794 } 2795 2796 return true; 2797 } 2798 2799 /** 2800 * Internally set new {@link LockdownVpnTracker}, shutting down any existing 2801 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown. 2802 */ 2803 private void setLockdownTracker(LockdownVpnTracker tracker) { 2804 // Shutdown any existing tracker 2805 final LockdownVpnTracker existing = mLockdownTracker; 2806 mLockdownTracker = null; 2807 if (existing != null) { 2808 existing.shutdown(); 2809 } 2810 2811 try { 2812 if (tracker != null) { 2813 mNetd.setFirewallEnabled(true); 2814 mNetd.setFirewallInterfaceRule("lo", true); 2815 mLockdownTracker = tracker; 2816 mLockdownTracker.init(); 2817 } else { 2818 mNetd.setFirewallEnabled(false); 2819 } 2820 } catch (RemoteException e) { 2821 // ignored; NMS lives inside system_server 2822 } 2823 } 2824 2825 private void throwIfLockdownEnabled() { 2826 if (mLockdownEnabled) { 2827 throw new IllegalStateException("Unavailable in lockdown mode"); 2828 } 2829 } 2830 2831 public void supplyMessenger(int networkType, Messenger messenger) { 2832 enforceConnectivityInternalPermission(); 2833 2834 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) { 2835 mNetTrackers[networkType].supplyMessenger(messenger); 2836 } 2837 } 2838 2839 public int findConnectionTypeForIface(String iface) { 2840 enforceConnectivityInternalPermission(); 2841 2842 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE; 2843 for (NetworkStateTracker tracker : mNetTrackers) { 2844 if (tracker != null) { 2845 LinkProperties lp = tracker.getLinkProperties(); 2846 if (lp != null && iface.equals(lp.getInterfaceName())) { 2847 return tracker.getNetworkInfo().getType(); 2848 } 2849 } 2850 } 2851 return ConnectivityManager.TYPE_NONE; 2852 } 2853 2854 /** 2855 * Have mobile data fail fast if enabled. 2856 * 2857 * @param enabled DctConstants.ENABLED/DISABLED 2858 */ 2859 private void setEnableFailFastMobileData(int enabled) { 2860 int tag; 2861 2862 if (enabled == DctConstants.ENABLED) { 2863 tag = mEnableFailFastMobileDataTag.incrementAndGet(); 2864 } else { 2865 tag = mEnableFailFastMobileDataTag.get(); 2866 } 2867 mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag, 2868 enabled)); 2869 } 2870 2871 private boolean isMobileDataStateTrackerReady() { 2872 MobileDataStateTracker mdst = 2873 (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 2874 return (mdst != null) && (mdst.isReady()); 2875 } 2876 2877 /** 2878 * The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE) 2879 */ 2880 2881 /** 2882 * No connection was possible to the network. 2883 * This is NOT a warm sim. 2884 */ 2885 private static final int CMP_RESULT_CODE_NO_CONNECTION = 0; 2886 2887 /** 2888 * A connection was made to the internet, all is well. 2889 * This is NOT a warm sim. 2890 */ 2891 private static final int CMP_RESULT_CODE_CONNECTABLE = 1; 2892 2893 /** 2894 * A connection was made but no dns server was available to resolve a name to address. 2895 * This is NOT a warm sim since provisioning network is supported. 2896 */ 2897 private static final int CMP_RESULT_CODE_NO_DNS = 2; 2898 2899 /** 2900 * A connection was made but could not open a TCP connection. 2901 * This is NOT a warm sim since provisioning network is supported. 2902 */ 2903 private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3; 2904 2905 /** 2906 * A connection was made but there was a redirection, we appear to be in walled garden. 2907 * This is an indication of a warm sim on a mobile network such as T-Mobile. 2908 */ 2909 private static final int CMP_RESULT_CODE_REDIRECTED = 4; 2910 2911 /** 2912 * The mobile network is a provisioning network. 2913 * This is an indication of a warm sim on a mobile network such as AT&T. 2914 */ 2915 private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5; 2916 2917 /** 2918 * The mobile network is provisioning 2919 */ 2920 private static final int CMP_RESULT_CODE_IS_PROVISIONING = 6; 2921 2922 private AtomicBoolean mIsProvisioningNetwork = new AtomicBoolean(false); 2923 private AtomicBoolean mIsStartingProvisioning = new AtomicBoolean(false); 2924 2925 private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false); 2926 2927 @Override 2928 public int checkMobileProvisioning(int suggestedTimeOutMs) { 2929 int timeOutMs = -1; 2930 if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs); 2931 enforceConnectivityInternalPermission(); 2932 2933 final long token = Binder.clearCallingIdentity(); 2934 try { 2935 timeOutMs = suggestedTimeOutMs; 2936 if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) { 2937 timeOutMs = CheckMp.MAX_TIMEOUT_MS; 2938 } 2939 2940 // Check that mobile networks are supported 2941 if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE) 2942 || !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) { 2943 if (DBG) log("checkMobileProvisioning: X no mobile network"); 2944 return timeOutMs; 2945 } 2946 2947 // If we're already checking don't do it again 2948 // TODO: Add a queue of results... 2949 if (mIsCheckingMobileProvisioning.getAndSet(true)) { 2950 if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment"); 2951 return timeOutMs; 2952 } 2953 2954 // Start off with mobile notification off 2955 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null); 2956 2957 CheckMp checkMp = new CheckMp(mContext, this); 2958 CheckMp.CallBack cb = new CheckMp.CallBack() { 2959 @Override 2960 void onComplete(Integer result) { 2961 if (DBG) log("CheckMp.onComplete: result=" + result); 2962 NetworkInfo ni = 2963 mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo(); 2964 switch(result) { 2965 case CMP_RESULT_CODE_CONNECTABLE: 2966 case CMP_RESULT_CODE_NO_CONNECTION: 2967 case CMP_RESULT_CODE_NO_DNS: 2968 case CMP_RESULT_CODE_NO_TCP_CONNECTION: { 2969 if (DBG) log("CheckMp.onComplete: ignore, connected or no connection"); 2970 break; 2971 } 2972 case CMP_RESULT_CODE_REDIRECTED: { 2973 if (DBG) log("CheckMp.onComplete: warm sim"); 2974 String url = getMobileProvisioningUrl(); 2975 if (TextUtils.isEmpty(url)) { 2976 url = getMobileRedirectedProvisioningUrl(); 2977 } 2978 if (TextUtils.isEmpty(url) == false) { 2979 if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url); 2980 setProvNotificationVisible(true, 2981 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(), 2982 url); 2983 } else { 2984 if (DBG) log("CheckMp.onComplete: warm (redirected), no url"); 2985 } 2986 break; 2987 } 2988 case CMP_RESULT_CODE_PROVISIONING_NETWORK: { 2989 String url = getMobileProvisioningUrl(); 2990 if (TextUtils.isEmpty(url) == false) { 2991 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url); 2992 setProvNotificationVisible(true, 2993 ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(), 2994 url); 2995 // Mark that we've got a provisioning network and 2996 // Disable Mobile Data until user actually starts provisioning. 2997 mIsProvisioningNetwork.set(true); 2998 MobileDataStateTracker mdst = (MobileDataStateTracker) 2999 mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 3000 3001 // Disable radio until user starts provisioning 3002 mdst.setRadio(false); 3003 } else { 3004 if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url"); 3005 } 3006 break; 3007 } 3008 case CMP_RESULT_CODE_IS_PROVISIONING: { 3009 // FIXME: Need to know when provisioning is done. Probably we can 3010 // check the completion status if successful we're done if we 3011 // "timedout" or still connected to provisioning APN turn off data? 3012 if (DBG) log("CheckMp.onComplete: provisioning started"); 3013 mIsStartingProvisioning.set(false); 3014 break; 3015 } 3016 default: { 3017 loge("CheckMp.onComplete: ignore unexpected result=" + result); 3018 break; 3019 } 3020 } 3021 mIsCheckingMobileProvisioning.set(false); 3022 } 3023 }; 3024 CheckMp.Params params = 3025 new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb); 3026 if (DBG) log("checkMobileProvisioning: params=" + params); 3027 // TODO: Reenable when calls to the now defunct 3028 // MobileDataStateTracker.isProvisioningNetwork() are removed. 3029 // This code should be moved to the Telephony code. 3030 // checkMp.execute(params); 3031 } finally { 3032 Binder.restoreCallingIdentity(token); 3033 if (DBG) log("checkMobileProvisioning: X"); 3034 } 3035 return timeOutMs; 3036 } 3037 3038 static class CheckMp extends 3039 AsyncTask<CheckMp.Params, Void, Integer> { 3040 private static final String CHECKMP_TAG = "CheckMp"; 3041 3042 // adb shell setprop persist.checkmp.testfailures 1 to enable testing failures 3043 private static boolean mTestingFailures; 3044 3045 // Choosing 4 loops as half of them will use HTTPS and the other half HTTP 3046 private static final int MAX_LOOPS = 4; 3047 3048 // Number of milli-seconds to complete all of the retires 3049 public static final int MAX_TIMEOUT_MS = 60000; 3050 3051 // The socket should retry only 5 seconds, the default is longer 3052 private static final int SOCKET_TIMEOUT_MS = 5000; 3053 3054 // Sleep time for network errors 3055 private static final int NET_ERROR_SLEEP_SEC = 3; 3056 3057 // Sleep time for network route establishment 3058 private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3; 3059 3060 // Short sleep time for polling :( 3061 private static final int POLLING_SLEEP_SEC = 1; 3062 3063 private Context mContext; 3064 private ConnectivityService mCs; 3065 private TelephonyManager mTm; 3066 private Params mParams; 3067 3068 /** 3069 * Parameters for AsyncTask.execute 3070 */ 3071 static class Params { 3072 private String mUrl; 3073 private long mTimeOutMs; 3074 private CallBack mCb; 3075 3076 Params(String url, long timeOutMs, CallBack cb) { 3077 mUrl = url; 3078 mTimeOutMs = timeOutMs; 3079 mCb = cb; 3080 } 3081 3082 @Override 3083 public String toString() { 3084 return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}"; 3085 } 3086 } 3087 3088 // As explained to me by Brian Carlstrom and Kenny Root, Certificates can be 3089 // issued by name or ip address, for Google its by name so when we construct 3090 // this HostnameVerifier we'll pass the original Uri and use it to verify 3091 // the host. If the host name in the original uril fails we'll test the 3092 // hostname parameter just incase things change. 3093 static class CheckMpHostnameVerifier implements HostnameVerifier { 3094 Uri mOrgUri; 3095 3096 CheckMpHostnameVerifier(Uri orgUri) { 3097 mOrgUri = orgUri; 3098 } 3099 3100 @Override 3101 public boolean verify(String hostname, SSLSession session) { 3102 HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier(); 3103 String orgUriHost = mOrgUri.getHost(); 3104 boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session); 3105 if (DBG) { 3106 log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname 3107 + " orgUriHost=" + orgUriHost); 3108 } 3109 return retVal; 3110 } 3111 } 3112 3113 /** 3114 * The call back object passed in Params. onComplete will be called 3115 * on the main thread. 3116 */ 3117 abstract static class CallBack { 3118 // Called on the main thread. 3119 abstract void onComplete(Integer result); 3120 } 3121 3122 public CheckMp(Context context, ConnectivityService cs) { 3123 if (Build.IS_DEBUGGABLE) { 3124 mTestingFailures = 3125 SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1; 3126 } else { 3127 mTestingFailures = false; 3128 } 3129 3130 mContext = context; 3131 mCs = cs; 3132 3133 // Setup access to TelephonyService we'll be using. 3134 mTm = (TelephonyManager) mContext.getSystemService( 3135 Context.TELEPHONY_SERVICE); 3136 } 3137 3138 /** 3139 * Get the default url to use for the test. 3140 */ 3141 public String getDefaultUrl() { 3142 // See http://go/clientsdns for usage approval 3143 String server = Settings.Global.getString(mContext.getContentResolver(), 3144 Settings.Global.CAPTIVE_PORTAL_SERVER); 3145 if (server == null) { 3146 server = "clients3.google.com"; 3147 } 3148 return "http://" + server + "/generate_204"; 3149 } 3150 3151 /** 3152 * Detect if its possible to connect to the http url. DNS based detection techniques 3153 * do not work at all hotspots. The best way to check is to perform a request to 3154 * a known address that fetches the data we expect. 3155 */ 3156 private synchronized Integer isMobileOk(Params params) { 3157 Integer result = CMP_RESULT_CODE_NO_CONNECTION; 3158 Uri orgUri = Uri.parse(params.mUrl); 3159 Random rand = new Random(); 3160 mParams = params; 3161 3162 if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) { 3163 result = CMP_RESULT_CODE_NO_CONNECTION; 3164 log("isMobileOk: X not mobile capable result=" + result); 3165 return result; 3166 } 3167 3168 if (mCs.mIsStartingProvisioning.get()) { 3169 result = CMP_RESULT_CODE_IS_PROVISIONING; 3170 log("isMobileOk: X is provisioning result=" + result); 3171 return result; 3172 } 3173 3174 // See if we've already determined we've got a provisioning connection, 3175 // if so we don't need to do anything active. 3176 MobileDataStateTracker mdstDefault = (MobileDataStateTracker) 3177 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 3178 boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork(); 3179 log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning); 3180 3181 MobileDataStateTracker mdstHipri = (MobileDataStateTracker) 3182 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 3183 boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork(); 3184 log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning); 3185 3186 if (isDefaultProvisioning || isHipriProvisioning) { 3187 result = CMP_RESULT_CODE_PROVISIONING_NETWORK; 3188 log("isMobileOk: X default || hipri is provisioning result=" + result); 3189 return result; 3190 } 3191 3192 try { 3193 // Continue trying to connect until time has run out 3194 long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs; 3195 3196 if (!mCs.isMobileDataStateTrackerReady()) { 3197 // Wait for MobileDataStateTracker to be ready. 3198 if (DBG) log("isMobileOk: mdst is not ready"); 3199 while(SystemClock.elapsedRealtime() < endTime) { 3200 if (mCs.isMobileDataStateTrackerReady()) { 3201 // Enable fail fast as we'll do retries here and use a 3202 // hipri connection so the default connection stays active. 3203 if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data"); 3204 mCs.setEnableFailFastMobileData(DctConstants.ENABLED); 3205 break; 3206 } 3207 sleep(POLLING_SLEEP_SEC); 3208 } 3209 } 3210 3211 log("isMobileOk: start hipri url=" + params.mUrl); 3212 3213 // First wait until we can start using hipri 3214 Binder binder = new Binder(); 3215/* 3216 while(SystemClock.elapsedRealtime() < endTime) { 3217 int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, 3218 Phone.FEATURE_ENABLE_HIPRI, binder); 3219 if ((ret == PhoneConstants.APN_ALREADY_ACTIVE) 3220 || (ret == PhoneConstants.APN_REQUEST_STARTED)) { 3221 log("isMobileOk: hipri started"); 3222 break; 3223 } 3224 if (VDBG) log("isMobileOk: hipri not started yet"); 3225 result = CMP_RESULT_CODE_NO_CONNECTION; 3226 sleep(POLLING_SLEEP_SEC); 3227 } 3228*/ 3229 // Continue trying to connect until time has run out 3230 while(SystemClock.elapsedRealtime() < endTime) { 3231 try { 3232 // Wait for hipri to connect. 3233 // TODO: Don't poll and handle situation where hipri fails 3234 // because default is retrying. See b/9569540 3235 NetworkInfo.State state = mCs 3236 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); 3237 if (state != NetworkInfo.State.CONNECTED) { 3238 if (true/*VDBG*/) { 3239 log("isMobileOk: not connected ni=" + 3240 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI)); 3241 } 3242 sleep(POLLING_SLEEP_SEC); 3243 result = CMP_RESULT_CODE_NO_CONNECTION; 3244 continue; 3245 } 3246 3247 // Hipri has started check if this is a provisioning url 3248 MobileDataStateTracker mdst = (MobileDataStateTracker) 3249 mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI]; 3250 if (mdst.isProvisioningNetwork()) { 3251 result = CMP_RESULT_CODE_PROVISIONING_NETWORK; 3252 if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result); 3253 return result; 3254 } else { 3255 if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue"); 3256 } 3257 3258 // Get of the addresses associated with the url host. We need to use the 3259 // address otherwise HttpURLConnection object will use the name to get 3260 // the addresses and will try every address but that will bypass the 3261 // route to host we setup and the connection could succeed as the default 3262 // interface might be connected to the internet via wifi or other interface. 3263 InetAddress[] addresses; 3264 try { 3265 addresses = InetAddress.getAllByName(orgUri.getHost()); 3266 } catch (UnknownHostException e) { 3267 result = CMP_RESULT_CODE_NO_DNS; 3268 log("isMobileOk: X UnknownHostException result=" + result); 3269 return result; 3270 } 3271 log("isMobileOk: addresses=" + inetAddressesToString(addresses)); 3272 3273 // Get the type of addresses supported by this link 3274 LinkProperties lp = mCs.getLinkPropertiesForTypeInternal( 3275 ConnectivityManager.TYPE_MOBILE_HIPRI); 3276 boolean linkHasIpv4 = lp.hasIPv4Address(); 3277 boolean linkHasIpv6 = lp.hasGlobalIPv6Address(); 3278 log("isMobileOk: linkHasIpv4=" + linkHasIpv4 3279 + " linkHasIpv6=" + linkHasIpv6); 3280 3281 final ArrayList<InetAddress> validAddresses = 3282 new ArrayList<InetAddress>(addresses.length); 3283 3284 for (InetAddress addr : addresses) { 3285 if (((addr instanceof Inet4Address) && linkHasIpv4) || 3286 ((addr instanceof Inet6Address) && linkHasIpv6)) { 3287 validAddresses.add(addr); 3288 } 3289 } 3290 3291 if (validAddresses.size() == 0) { 3292 return CMP_RESULT_CODE_NO_CONNECTION; 3293 } 3294 3295 int addrTried = 0; 3296 while (true) { 3297 // Loop through at most MAX_LOOPS valid addresses or until 3298 // we run out of time 3299 if (addrTried++ >= MAX_LOOPS) { 3300 log("isMobileOk: too many loops tried - giving up"); 3301 break; 3302 } 3303 if (SystemClock.elapsedRealtime() >= endTime) { 3304 log("isMobileOk: spend too much time - giving up"); 3305 break; 3306 } 3307 3308 InetAddress hostAddr = validAddresses.get(rand.nextInt( 3309 validAddresses.size())); 3310 3311 // Make a route to host so we check the specific interface. 3312 if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI, 3313 hostAddr.getAddress())) { 3314 // Wait a short time to be sure the route is established ?? 3315 log("isMobileOk:" 3316 + " wait to establish route to hostAddr=" + hostAddr); 3317 sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC); 3318 } else { 3319 log("isMobileOk:" 3320 + " could not establish route to hostAddr=" + hostAddr); 3321 // Wait a short time before the next attempt 3322 sleep(NET_ERROR_SLEEP_SEC); 3323 continue; 3324 } 3325 3326 // Rewrite the url to have numeric address to use the specific route 3327 // using http for half the attempts and https for the other half. 3328 // Doing https first and http second as on a redirected walled garden 3329 // such as t-mobile uses we get a SocketTimeoutException: "SSL 3330 // handshake timed out" which we declare as 3331 // CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by 3332 // having http second we will be using logic used for some time. 3333 URL newUrl; 3334 String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http"; 3335 newUrl = new URL(scheme, hostAddr.getHostAddress(), 3336 orgUri.getPath()); 3337 log("isMobileOk: newUrl=" + newUrl); 3338 3339 HttpURLConnection urlConn = null; 3340 try { 3341 // Open the connection set the request headers and get the response 3342 urlConn = (HttpURLConnection)newUrl.openConnection( 3343 java.net.Proxy.NO_PROXY); 3344 if (scheme.equals("https")) { 3345 ((HttpsURLConnection)urlConn).setHostnameVerifier( 3346 new CheckMpHostnameVerifier(orgUri)); 3347 } 3348 urlConn.setInstanceFollowRedirects(false); 3349 urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS); 3350 urlConn.setReadTimeout(SOCKET_TIMEOUT_MS); 3351 urlConn.setUseCaches(false); 3352 urlConn.setAllowUserInteraction(false); 3353 // Set the "Connection" to "Close" as by default "Keep-Alive" 3354 // is used which is useless in this case. 3355 urlConn.setRequestProperty("Connection", "close"); 3356 int responseCode = urlConn.getResponseCode(); 3357 3358 // For debug display the headers 3359 Map<String, List<String>> headers = urlConn.getHeaderFields(); 3360 log("isMobileOk: headers=" + headers); 3361 3362 // Close the connection 3363 urlConn.disconnect(); 3364 urlConn = null; 3365 3366 if (mTestingFailures) { 3367 // Pretend no connection, this tests using http and https 3368 result = CMP_RESULT_CODE_NO_CONNECTION; 3369 log("isMobileOk: TESTING_FAILURES, pretend no connction"); 3370 continue; 3371 } 3372 3373 if (responseCode == 204) { 3374 // Return 3375 result = CMP_RESULT_CODE_CONNECTABLE; 3376 log("isMobileOk: X got expected responseCode=" + responseCode 3377 + " result=" + result); 3378 return result; 3379 } else { 3380 // Retry to be sure this was redirected, we've gotten 3381 // occasions where a server returned 200 even though 3382 // the device didn't have a "warm" sim. 3383 log("isMobileOk: not expected responseCode=" + responseCode); 3384 // TODO - it would be nice in the single-address case to do 3385 // another DNS resolve here, but flushing the cache is a bit 3386 // heavy-handed. 3387 result = CMP_RESULT_CODE_REDIRECTED; 3388 } 3389 } catch (Exception e) { 3390 log("isMobileOk: HttpURLConnection Exception" + e); 3391 result = CMP_RESULT_CODE_NO_TCP_CONNECTION; 3392 if (urlConn != null) { 3393 urlConn.disconnect(); 3394 urlConn = null; 3395 } 3396 sleep(NET_ERROR_SLEEP_SEC); 3397 continue; 3398 } 3399 } 3400 log("isMobileOk: X loops|timed out result=" + result); 3401 return result; 3402 } catch (Exception e) { 3403 log("isMobileOk: Exception e=" + e); 3404 continue; 3405 } 3406 } 3407 log("isMobileOk: timed out"); 3408 } finally { 3409 log("isMobileOk: F stop hipri"); 3410 mCs.setEnableFailFastMobileData(DctConstants.DISABLED); 3411// mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, 3412// Phone.FEATURE_ENABLE_HIPRI); 3413 3414 // Wait for hipri to disconnect. 3415 long endTime = SystemClock.elapsedRealtime() + 5000; 3416 3417 while(SystemClock.elapsedRealtime() < endTime) { 3418 NetworkInfo.State state = mCs 3419 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState(); 3420 if (state != NetworkInfo.State.DISCONNECTED) { 3421 if (VDBG) { 3422 log("isMobileOk: connected ni=" + 3423 mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI)); 3424 } 3425 sleep(POLLING_SLEEP_SEC); 3426 continue; 3427 } 3428 } 3429 3430 log("isMobileOk: X result=" + result); 3431 } 3432 return result; 3433 } 3434 3435 @Override 3436 protected Integer doInBackground(Params... params) { 3437 return isMobileOk(params[0]); 3438 } 3439 3440 @Override 3441 protected void onPostExecute(Integer result) { 3442 log("onPostExecute: result=" + result); 3443 if ((mParams != null) && (mParams.mCb != null)) { 3444 mParams.mCb.onComplete(result); 3445 } 3446 } 3447 3448 private String inetAddressesToString(InetAddress[] addresses) { 3449 StringBuffer sb = new StringBuffer(); 3450 boolean firstTime = true; 3451 for(InetAddress addr : addresses) { 3452 if (firstTime) { 3453 firstTime = false; 3454 } else { 3455 sb.append(","); 3456 } 3457 sb.append(addr); 3458 } 3459 return sb.toString(); 3460 } 3461 3462 private void printNetworkInfo() { 3463 boolean hasIccCard = mTm.hasIccCard(); 3464 int simState = mTm.getSimState(); 3465 log("hasIccCard=" + hasIccCard 3466 + " simState=" + simState); 3467 NetworkInfo[] ni = mCs.getAllNetworkInfo(); 3468 if (ni != null) { 3469 log("ni.length=" + ni.length); 3470 for (NetworkInfo netInfo: ni) { 3471 log("netInfo=" + netInfo.toString()); 3472 } 3473 } else { 3474 log("no network info ni=null"); 3475 } 3476 } 3477 3478 /** 3479 * Sleep for a few seconds then return. 3480 * @param seconds 3481 */ 3482 private static void sleep(int seconds) { 3483 long stopTime = System.nanoTime() + (seconds * 1000000000); 3484 long sleepTime; 3485 while ((sleepTime = stopTime - System.nanoTime()) > 0) { 3486 try { 3487 Thread.sleep(sleepTime / 1000000); 3488 } catch (InterruptedException ignored) { 3489 } 3490 } 3491 } 3492 3493 private static void log(String s) { 3494 Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s); 3495 } 3496 } 3497 3498 // TODO: Move to ConnectivityManager and make public? 3499 private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION = 3500 "com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION"; 3501 3502 private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() { 3503 @Override 3504 public void onReceive(Context context, Intent intent) { 3505 if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) { 3506 handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL")); 3507 } 3508 } 3509 }; 3510 3511 private void handleMobileProvisioningAction(String url) { 3512 // Mark notification as not visible 3513 setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null); 3514 3515 // Check airplane mode 3516 boolean isAirplaneModeOn = Settings.System.getInt(mContext.getContentResolver(), 3517 Settings.Global.AIRPLANE_MODE_ON, 0) == 1; 3518 // If provisioning network and not in airplane mode handle as a special case, 3519 // otherwise launch browser with the intent directly. 3520 if (mIsProvisioningNetwork.get() && !isAirplaneModeOn) { 3521 if (DBG) log("handleMobileProvisioningAction: on prov network enable then launch"); 3522 mIsProvisioningNetwork.set(false); 3523// mIsStartingProvisioning.set(true); 3524// MobileDataStateTracker mdst = (MobileDataStateTracker) 3525// mNetTrackers[ConnectivityManager.TYPE_MOBILE]; 3526 // Radio was disabled on CMP_RESULT_CODE_PROVISIONING_NETWORK, enable it here 3527// mdst.setRadio(true); 3528// mdst.setEnableFailFastMobileData(DctConstants.ENABLED); 3529// mdst.enableMobileProvisioning(url); 3530 } else { 3531 if (DBG) log("handleMobileProvisioningAction: not prov network"); 3532 mIsProvisioningNetwork.set(false); 3533 // Check for apps that can handle provisioning first 3534 Intent provisioningIntent = new Intent(TelephonyIntents.ACTION_CARRIER_SETUP); 3535 List<String> carrierPackages = 3536 mTelephonyManager.getCarrierPackageNamesForBroadcastIntent(provisioningIntent); 3537 if (carrierPackages != null && !carrierPackages.isEmpty()) { 3538 if (carrierPackages.size() != 1) { 3539 if (DBG) log("Multiple matching carrier apps found, launching the first."); 3540 } 3541 provisioningIntent.setPackage(carrierPackages.get(0)); 3542 provisioningIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 3543 Intent.FLAG_ACTIVITY_NEW_TASK); 3544 mContext.startActivity(provisioningIntent); 3545 } else { 3546 // If no apps exist, use standard URL ACTION_VIEW method 3547 Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, 3548 Intent.CATEGORY_APP_BROWSER); 3549 newIntent.setData(Uri.parse(url)); 3550 newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 3551 Intent.FLAG_ACTIVITY_NEW_TASK); 3552 try { 3553 mContext.startActivity(newIntent); 3554 } catch (ActivityNotFoundException e) { 3555 loge("handleMobileProvisioningAction: startActivity failed" + e); 3556 } 3557 } 3558 } 3559 } 3560 3561 private static final String NOTIFICATION_ID = "CaptivePortal.Notification"; 3562 private volatile boolean mIsNotificationVisible = false; 3563 3564 private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo, 3565 String url) { 3566 if (DBG) { 3567 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType 3568 + " extraInfo=" + extraInfo + " url=" + url); 3569 } 3570 Intent intent = null; 3571 PendingIntent pendingIntent = null; 3572 if (visible) { 3573 switch (networkType) { 3574 case ConnectivityManager.TYPE_WIFI: 3575 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 3576 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 3577 Intent.FLAG_ACTIVITY_NEW_TASK); 3578 pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0); 3579 break; 3580 case ConnectivityManager.TYPE_MOBILE: 3581 case ConnectivityManager.TYPE_MOBILE_HIPRI: 3582 intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION); 3583 intent.putExtra("EXTRA_URL", url); 3584 intent.setFlags(0); 3585 pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); 3586 break; 3587 default: 3588 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 3589 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | 3590 Intent.FLAG_ACTIVITY_NEW_TASK); 3591 pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0); 3592 break; 3593 } 3594 } 3595 // Concatenate the range of types onto the range of NetIDs. 3596 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE); 3597 setProvNotificationVisibleIntent(visible, id, networkType, extraInfo, pendingIntent); 3598 } 3599 3600 /** 3601 * Show or hide network provisioning notificaitons. 3602 * 3603 * @param id an identifier that uniquely identifies this notification. This must match 3604 * between show and hide calls. We use the NetID value but for legacy callers 3605 * we concatenate the range of types with the range of NetIDs. 3606 */ 3607 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType, 3608 String extraInfo, PendingIntent intent) { 3609 if (DBG) { 3610 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" + 3611 networkType + " extraInfo=" + extraInfo); 3612 } 3613 3614 Resources r = Resources.getSystem(); 3615 NotificationManager notificationManager = (NotificationManager) mContext 3616 .getSystemService(Context.NOTIFICATION_SERVICE); 3617 3618 if (visible) { 3619 CharSequence title; 3620 CharSequence details; 3621 int icon; 3622 Notification notification = new Notification(); 3623 switch (networkType) { 3624 case ConnectivityManager.TYPE_WIFI: 3625 title = r.getString(R.string.wifi_available_sign_in, 0); 3626 details = r.getString(R.string.network_available_sign_in_detailed, 3627 extraInfo); 3628 icon = R.drawable.stat_notify_wifi_in_range; 3629 break; 3630 case ConnectivityManager.TYPE_MOBILE: 3631 case ConnectivityManager.TYPE_MOBILE_HIPRI: 3632 title = r.getString(R.string.network_available_sign_in, 0); 3633 // TODO: Change this to pull from NetworkInfo once a printable 3634 // name has been added to it 3635 details = mTelephonyManager.getNetworkOperatorName(); 3636 icon = R.drawable.stat_notify_rssi_in_range; 3637 break; 3638 default: 3639 title = r.getString(R.string.network_available_sign_in, 0); 3640 details = r.getString(R.string.network_available_sign_in_detailed, 3641 extraInfo); 3642 icon = R.drawable.stat_notify_rssi_in_range; 3643 break; 3644 } 3645 3646 notification.when = 0; 3647 notification.icon = icon; 3648 notification.flags = Notification.FLAG_AUTO_CANCEL; 3649 notification.tickerText = title; 3650 notification.color = mContext.getResources().getColor( 3651 com.android.internal.R.color.system_notification_accent_color); 3652 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent); 3653 notification.contentIntent = intent; 3654 3655 try { 3656 notificationManager.notify(NOTIFICATION_ID, id, notification); 3657 } catch (NullPointerException npe) { 3658 loge("setNotificaitionVisible: visible notificationManager npe=" + npe); 3659 npe.printStackTrace(); 3660 } 3661 } else { 3662 try { 3663 notificationManager.cancel(NOTIFICATION_ID, id); 3664 } catch (NullPointerException npe) { 3665 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe); 3666 npe.printStackTrace(); 3667 } 3668 } 3669 mIsNotificationVisible = visible; 3670 } 3671 3672 /** Location to an updatable file listing carrier provisioning urls. 3673 * An example: 3674 * 3675 * <?xml version="1.0" encoding="utf-8"?> 3676 * <provisioningUrls> 3677 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl> 3678 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl> 3679 * </provisioningUrls> 3680 */ 3681 private static final String PROVISIONING_URL_PATH = 3682 "/data/misc/radio/provisioning_urls.xml"; 3683 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH); 3684 3685 /** XML tag for root element. */ 3686 private static final String TAG_PROVISIONING_URLS = "provisioningUrls"; 3687 /** XML tag for individual url */ 3688 private static final String TAG_PROVISIONING_URL = "provisioningUrl"; 3689 /** XML tag for redirected url */ 3690 private static final String TAG_REDIRECTED_URL = "redirectedUrl"; 3691 /** XML attribute for mcc */ 3692 private static final String ATTR_MCC = "mcc"; 3693 /** XML attribute for mnc */ 3694 private static final String ATTR_MNC = "mnc"; 3695 3696 private static final int REDIRECTED_PROVISIONING = 1; 3697 private static final int PROVISIONING = 2; 3698 3699 private String getProvisioningUrlBaseFromFile(int type) { 3700 FileReader fileReader = null; 3701 XmlPullParser parser = null; 3702 Configuration config = mContext.getResources().getConfiguration(); 3703 String tagType; 3704 3705 switch (type) { 3706 case PROVISIONING: 3707 tagType = TAG_PROVISIONING_URL; 3708 break; 3709 case REDIRECTED_PROVISIONING: 3710 tagType = TAG_REDIRECTED_URL; 3711 break; 3712 default: 3713 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " + 3714 type); 3715 } 3716 3717 try { 3718 fileReader = new FileReader(mProvisioningUrlFile); 3719 parser = Xml.newPullParser(); 3720 parser.setInput(fileReader); 3721 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS); 3722 3723 while (true) { 3724 XmlUtils.nextElement(parser); 3725 3726 String element = parser.getName(); 3727 if (element == null) break; 3728 3729 if (element.equals(tagType)) { 3730 String mcc = parser.getAttributeValue(null, ATTR_MCC); 3731 try { 3732 if (mcc != null && Integer.parseInt(mcc) == config.mcc) { 3733 String mnc = parser.getAttributeValue(null, ATTR_MNC); 3734 if (mnc != null && Integer.parseInt(mnc) == config.mnc) { 3735 parser.next(); 3736 if (parser.getEventType() == XmlPullParser.TEXT) { 3737 return parser.getText(); 3738 } 3739 } 3740 } 3741 } catch (NumberFormatException e) { 3742 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e); 3743 } 3744 } 3745 } 3746 return null; 3747 } catch (FileNotFoundException e) { 3748 loge("Carrier Provisioning Urls file not found"); 3749 } catch (XmlPullParserException e) { 3750 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e); 3751 } catch (IOException e) { 3752 loge("I/O exception reading Carrier Provisioning Urls file: " + e); 3753 } finally { 3754 if (fileReader != null) { 3755 try { 3756 fileReader.close(); 3757 } catch (IOException e) {} 3758 } 3759 } 3760 return null; 3761 } 3762 3763 @Override 3764 public String getMobileRedirectedProvisioningUrl() { 3765 enforceConnectivityInternalPermission(); 3766 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING); 3767 if (TextUtils.isEmpty(url)) { 3768 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url); 3769 } 3770 return url; 3771 } 3772 3773 @Override 3774 public String getMobileProvisioningUrl() { 3775 enforceConnectivityInternalPermission(); 3776 String url = getProvisioningUrlBaseFromFile(PROVISIONING); 3777 if (TextUtils.isEmpty(url)) { 3778 url = mContext.getResources().getString(R.string.mobile_provisioning_url); 3779 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url); 3780 } else { 3781 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url); 3782 } 3783 // populate the iccid, imei and phone number in the provisioning url. 3784 if (!TextUtils.isEmpty(url)) { 3785 String phoneNumber = mTelephonyManager.getLine1Number(); 3786 if (TextUtils.isEmpty(phoneNumber)) { 3787 phoneNumber = "0000000000"; 3788 } 3789 url = String.format(url, 3790 mTelephonyManager.getSimSerialNumber() /* ICCID */, 3791 mTelephonyManager.getDeviceId() /* IMEI */, 3792 phoneNumber /* Phone numer */); 3793 } 3794 3795 return url; 3796 } 3797 3798 @Override 3799 public void setProvisioningNotificationVisible(boolean visible, int networkType, 3800 String extraInfo, String url) { 3801 enforceConnectivityInternalPermission(); 3802 setProvNotificationVisible(visible, networkType, extraInfo, url); 3803 } 3804 3805 @Override 3806 public void setAirplaneMode(boolean enable) { 3807 enforceConnectivityInternalPermission(); 3808 final long ident = Binder.clearCallingIdentity(); 3809 try { 3810 final ContentResolver cr = mContext.getContentResolver(); 3811 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0); 3812 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED); 3813 intent.putExtra("state", enable); 3814 mContext.sendBroadcast(intent); 3815 } finally { 3816 Binder.restoreCallingIdentity(ident); 3817 } 3818 } 3819 3820 private void onUserStart(int userId) { 3821 synchronized(mVpns) { 3822 Vpn userVpn = mVpns.get(userId); 3823 if (userVpn != null) { 3824 loge("Starting user already has a VPN"); 3825 return; 3826 } 3827 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, this, userId); 3828 mVpns.put(userId, userVpn); 3829 } 3830 } 3831 3832 private void onUserStop(int userId) { 3833 synchronized(mVpns) { 3834 Vpn userVpn = mVpns.get(userId); 3835 if (userVpn == null) { 3836 loge("Stopping user has no VPN"); 3837 return; 3838 } 3839 mVpns.delete(userId); 3840 } 3841 } 3842 3843 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() { 3844 @Override 3845 public void onReceive(Context context, Intent intent) { 3846 final String action = intent.getAction(); 3847 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL); 3848 if (userId == UserHandle.USER_NULL) return; 3849 3850 if (Intent.ACTION_USER_STARTING.equals(action)) { 3851 onUserStart(userId); 3852 } else if (Intent.ACTION_USER_STOPPING.equals(action)) { 3853 onUserStop(userId); 3854 } 3855 } 3856 }; 3857 3858 @Override 3859 public LinkQualityInfo getLinkQualityInfo(int networkType) { 3860 enforceAccessPermission(); 3861 if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) { 3862 return mNetTrackers[networkType].getLinkQualityInfo(); 3863 } else { 3864 return null; 3865 } 3866 } 3867 3868 @Override 3869 public LinkQualityInfo getActiveLinkQualityInfo() { 3870 enforceAccessPermission(); 3871 if (isNetworkTypeValid(mActiveDefaultNetwork) && 3872 mNetTrackers[mActiveDefaultNetwork] != null) { 3873 return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo(); 3874 } else { 3875 return null; 3876 } 3877 } 3878 3879 @Override 3880 public LinkQualityInfo[] getAllLinkQualityInfo() { 3881 enforceAccessPermission(); 3882 final ArrayList<LinkQualityInfo> result = Lists.newArrayList(); 3883 for (NetworkStateTracker tracker : mNetTrackers) { 3884 if (tracker != null) { 3885 LinkQualityInfo li = tracker.getLinkQualityInfo(); 3886 if (li != null) { 3887 result.add(li); 3888 } 3889 } 3890 } 3891 3892 return result.toArray(new LinkQualityInfo[result.size()]); 3893 } 3894 3895 /* Infrastructure for network sampling */ 3896 3897 private void handleNetworkSamplingTimeout() { 3898 3899 log("Sampling interval elapsed, updating statistics .."); 3900 3901 // initialize list of interfaces .. 3902 Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample = 3903 new HashMap<String, SamplingDataTracker.SamplingSnapshot>(); 3904 for (NetworkStateTracker tracker : mNetTrackers) { 3905 if (tracker != null) { 3906 String ifaceName = tracker.getNetworkInterfaceName(); 3907 if (ifaceName != null) { 3908 mapIfaceToSample.put(ifaceName, null); 3909 } 3910 } 3911 } 3912 3913 // Read samples for all interfaces 3914 SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample); 3915 3916 // process samples for all networks 3917 for (NetworkStateTracker tracker : mNetTrackers) { 3918 if (tracker != null) { 3919 String ifaceName = tracker.getNetworkInterfaceName(); 3920 SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName); 3921 if (ss != null) { 3922 // end the previous sampling cycle 3923 tracker.stopSampling(ss); 3924 // start a new sampling cycle .. 3925 tracker.startSampling(ss); 3926 } 3927 } 3928 } 3929 3930 log("Done."); 3931 3932 int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(), 3933 Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS, 3934 DEFAULT_SAMPLING_INTERVAL_IN_SECONDS); 3935 3936 if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds"); 3937 3938 setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent); 3939 } 3940 3941 /** 3942 * Sets a network sampling alarm. 3943 */ 3944 void setAlarm(int timeoutInMilliseconds, PendingIntent intent) { 3945 long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds; 3946 int alarmType; 3947 if (Resources.getSystem().getBoolean( 3948 R.bool.config_networkSamplingWakesDevice)) { 3949 alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP; 3950 } else { 3951 alarmType = AlarmManager.ELAPSED_REALTIME; 3952 } 3953 mAlarmManager.set(alarmType, wakeupTime, intent); 3954 } 3955 3956 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos = 3957 new HashMap<Messenger, NetworkFactoryInfo>(); 3958 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = 3959 new HashMap<NetworkRequest, NetworkRequestInfo>(); 3960 3961 private static class NetworkFactoryInfo { 3962 public final String name; 3963 public final Messenger messenger; 3964 public final AsyncChannel asyncChannel; 3965 3966 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) { 3967 this.name = name; 3968 this.messenger = messenger; 3969 this.asyncChannel = asyncChannel; 3970 } 3971 } 3972 3973 /** 3974 * Tracks info about the requester. 3975 * Also used to notice when the calling process dies so we can self-expire 3976 */ 3977 private class NetworkRequestInfo implements IBinder.DeathRecipient { 3978 static final boolean REQUEST = true; 3979 static final boolean LISTEN = false; 3980 3981 final NetworkRequest request; 3982 IBinder mBinder; 3983 final int mPid; 3984 final int mUid; 3985 final Messenger messenger; 3986 final boolean isRequest; 3987 3988 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) { 3989 super(); 3990 messenger = m; 3991 request = r; 3992 mBinder = binder; 3993 mPid = getCallingPid(); 3994 mUid = getCallingUid(); 3995 this.isRequest = isRequest; 3996 3997 try { 3998 mBinder.linkToDeath(this, 0); 3999 } catch (RemoteException e) { 4000 binderDied(); 4001 } 4002 } 4003 4004 void unlinkDeathRecipient() { 4005 mBinder.unlinkToDeath(this, 0); 4006 } 4007 4008 public void binderDied() { 4009 log("ConnectivityService NetworkRequestInfo binderDied(" + 4010 request + ", " + mBinder + ")"); 4011 releaseNetworkRequest(request); 4012 } 4013 4014 public String toString() { 4015 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" + 4016 mPid + " for " + request; 4017 } 4018 } 4019 4020 @Override 4021 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities, 4022 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) { 4023 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED) 4024 == false) { 4025 enforceConnectivityInternalPermission(); 4026 } else { 4027 enforceChangePermission(); 4028 } 4029 4030 networkCapabilities = new NetworkCapabilities(networkCapabilities); 4031 4032 // if UID is restricted, don't allow them to bring up metered APNs 4033 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) 4034 == false) { 4035 final int uidRules; 4036 synchronized(mRulesLock) { 4037 uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL); 4038 } 4039 if ((uidRules & RULE_REJECT_METERED) != 0) { 4040 // we could silently fail or we can filter the available nets to only give 4041 // them those they have access to. Chose the more useful 4042 networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED); 4043 } 4044 } 4045 4046 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) { 4047 throw new IllegalArgumentException("Bad timeout specified"); 4048 } 4049 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType, 4050 nextNetworkRequestId()); 4051 if (DBG) log("requestNetwork for " + networkRequest); 4052 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, 4053 NetworkRequestInfo.REQUEST); 4054 4055 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri)); 4056 if (timeoutMs > 0) { 4057 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST, 4058 nri), timeoutMs); 4059 } 4060 return networkRequest; 4061 } 4062 4063 @Override 4064 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities, 4065 PendingIntent operation) { 4066 // TODO 4067 return null; 4068 } 4069 4070 @Override 4071 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities, 4072 Messenger messenger, IBinder binder) { 4073 enforceAccessPermission(); 4074 4075 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities( 4076 networkCapabilities), TYPE_NONE, nextNetworkRequestId()); 4077 if (DBG) log("listenForNetwork for " + networkRequest); 4078 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, 4079 NetworkRequestInfo.LISTEN); 4080 4081 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); 4082 return networkRequest; 4083 } 4084 4085 @Override 4086 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities, 4087 PendingIntent operation) { 4088 } 4089 4090 @Override 4091 public void releaseNetworkRequest(NetworkRequest networkRequest) { 4092 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 4093 0, networkRequest)); 4094 } 4095 4096 @Override 4097 public void registerNetworkFactory(Messenger messenger, String name) { 4098 enforceConnectivityInternalPermission(); 4099 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel()); 4100 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi)); 4101 } 4102 4103 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) { 4104 if (VDBG) log("Got NetworkFactory Messenger for " + nfi.name); 4105 mNetworkFactoryInfos.put(nfi.messenger, nfi); 4106 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger); 4107 } 4108 4109 @Override 4110 public void unregisterNetworkFactory(Messenger messenger) { 4111 enforceConnectivityInternalPermission(); 4112 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger)); 4113 } 4114 4115 private void handleUnregisterNetworkFactory(Messenger messenger) { 4116 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger); 4117 if (nfi == null) { 4118 if (VDBG) log("Failed to find Messenger in unregisterNetworkFactory"); 4119 return; 4120 } 4121 if (VDBG) log("unregisterNetworkFactory for " + nfi.name); 4122 } 4123 4124 /** 4125 * NetworkAgentInfo supporting a request by requestId. 4126 * These have already been vetted (their Capabilities satisfy the request) 4127 * and the are the highest scored network available. 4128 * the are keyed off the Requests requestId. 4129 */ 4130 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId = 4131 new SparseArray<NetworkAgentInfo>(); 4132 4133 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = 4134 new SparseArray<NetworkAgentInfo>(); 4135 4136 // NetworkAgentInfo keyed off its connecting messenger 4137 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays 4138 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = 4139 new HashMap<Messenger, NetworkAgentInfo>(); 4140 4141 private final NetworkRequest mDefaultRequest; 4142 4143 private boolean isDefaultNetwork(NetworkAgentInfo nai) { 4144 return mNetworkForRequestId.get(mDefaultRequest.requestId) == nai; 4145 } 4146 4147 public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo, 4148 LinkProperties linkProperties, NetworkCapabilities networkCapabilities, 4149 int currentScore, NetworkMisc networkMisc) { 4150 enforceConnectivityInternalPermission(); 4151 4152 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(), nextNetId(), 4153 new NetworkInfo(networkInfo), new LinkProperties(linkProperties), 4154 new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler, 4155 networkMisc); 4156 synchronized (this) { 4157 nai.networkMonitor.systemReady = mSystemReady; 4158 } 4159 if (VDBG) log("registerNetworkAgent " + nai); 4160 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai)); 4161 } 4162 4163 private void handleRegisterNetworkAgent(NetworkAgentInfo na) { 4164 if (VDBG) log("Got NetworkAgent Messenger"); 4165 mNetworkAgentInfos.put(na.messenger, na); 4166 synchronized (mNetworkForNetId) { 4167 mNetworkForNetId.put(na.network.netId, na); 4168 } 4169 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger); 4170 NetworkInfo networkInfo = na.networkInfo; 4171 na.networkInfo = null; 4172 updateNetworkInfo(na, networkInfo); 4173 } 4174 4175 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) { 4176 LinkProperties newLp = networkAgent.linkProperties; 4177 int netId = networkAgent.network.netId; 4178 4179 updateInterfaces(newLp, oldLp, netId); 4180 updateMtu(newLp, oldLp); 4181 updateTcpBufferSizes(networkAgent); 4182 // TODO - figure out what to do for clat 4183// for (LinkProperties lp : newLp.getStackedLinks()) { 4184// updateMtu(lp, null); 4185// } 4186 final boolean flushDns = updateRoutes(newLp, oldLp, netId); 4187 updateDnses(newLp, oldLp, netId, flushDns); 4188 updateClat(newLp, oldLp, networkAgent); 4189 } 4190 4191 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo na) { 4192 // Update 464xlat state. 4193 if (mClat.requiresClat(na)) { 4194 4195 // If the connection was previously using clat, but is not using it now, stop the clat 4196 // daemon. Normally, this happens automatically when the connection disconnects, but if 4197 // the disconnect is not reported, or if the connection's LinkProperties changed for 4198 // some other reason (e.g., handoff changes the IP addresses on the link), it would 4199 // still be running. If it's not running, then stopping it is a no-op. 4200 if (Nat464Xlat.isRunningClat(oldLp) && !Nat464Xlat.isRunningClat(newLp)) { 4201 mClat.stopClat(); 4202 } 4203 // If the link requires clat to be running, then start the daemon now. 4204 if (na.networkInfo.isConnected()) { 4205 mClat.startClat(na); 4206 } else { 4207 mClat.stopClat(); 4208 } 4209 } 4210 } 4211 4212 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) { 4213 CompareResult<String> interfaceDiff = new CompareResult<String>(); 4214 if (oldLp != null) { 4215 interfaceDiff = oldLp.compareAllInterfaceNames(newLp); 4216 } else if (newLp != null) { 4217 interfaceDiff.added = newLp.getAllInterfaceNames(); 4218 } 4219 for (String iface : interfaceDiff.added) { 4220 try { 4221 mNetd.addInterfaceToNetwork(iface, netId); 4222 } catch (Exception e) { 4223 loge("Exception adding interface: " + e); 4224 } 4225 } 4226 for (String iface : interfaceDiff.removed) { 4227 try { 4228 mNetd.removeInterfaceFromNetwork(iface, netId); 4229 } catch (Exception e) { 4230 loge("Exception removing interface: " + e); 4231 } 4232 } 4233 } 4234 4235 /** 4236 * Have netd update routes from oldLp to newLp. 4237 * @return true if routes changed between oldLp and newLp 4238 */ 4239 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) { 4240 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(); 4241 if (oldLp != null) { 4242 routeDiff = oldLp.compareAllRoutes(newLp); 4243 } else if (newLp != null) { 4244 routeDiff.added = newLp.getAllRoutes(); 4245 } 4246 4247 // add routes before removing old in case it helps with continuous connectivity 4248 4249 // do this twice, adding non-nexthop routes first, then routes they are dependent on 4250 for (RouteInfo route : routeDiff.added) { 4251 if (route.hasGateway()) continue; 4252 try { 4253 mNetd.addRoute(netId, route); 4254 } catch (Exception e) { 4255 loge("Exception in addRoute for non-gateway: " + e); 4256 } 4257 } 4258 for (RouteInfo route : routeDiff.added) { 4259 if (route.hasGateway() == false) continue; 4260 try { 4261 mNetd.addRoute(netId, route); 4262 } catch (Exception e) { 4263 loge("Exception in addRoute for gateway: " + e); 4264 } 4265 } 4266 4267 for (RouteInfo route : routeDiff.removed) { 4268 try { 4269 mNetd.removeRoute(netId, route); 4270 } catch (Exception e) { 4271 loge("Exception in removeRoute: " + e); 4272 } 4273 } 4274 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty(); 4275 } 4276 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId, boolean flush) { 4277 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) { 4278 Collection<InetAddress> dnses = newLp.getDnsServers(); 4279 if (dnses.size() == 0 && mDefaultDns != null) { 4280 dnses = new ArrayList(); 4281 dnses.add(mDefaultDns); 4282 if (DBG) { 4283 loge("no dns provided for netId " + netId + ", so using defaults"); 4284 } 4285 } 4286 try { 4287 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses), 4288 newLp.getDomains()); 4289 } catch (Exception e) { 4290 loge("Exception in setDnsServersForNetwork: " + e); 4291 } 4292 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId); 4293 if (defaultNai != null && defaultNai.network.netId == netId) { 4294 setDefaultDnsSystemProperties(dnses); 4295 } 4296 flushVmDnsCache(); 4297 } else if (flush) { 4298 try { 4299 mNetd.flushNetworkDnsCache(netId); 4300 } catch (Exception e) { 4301 loge("Exception in flushNetworkDnsCache: " + e); 4302 } 4303 flushVmDnsCache(); 4304 } 4305 } 4306 4307 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) { 4308 int last = 0; 4309 for (InetAddress dns : dnses) { 4310 ++last; 4311 String key = "net.dns" + last; 4312 String value = dns.getHostAddress(); 4313 SystemProperties.set(key, value); 4314 } 4315 for (int i = last + 1; i <= mNumDnsEntries; ++i) { 4316 String key = "net.dns" + i; 4317 SystemProperties.set(key, ""); 4318 } 4319 mNumDnsEntries = last; 4320 } 4321 4322 4323 private void updateCapabilities(NetworkAgentInfo networkAgent, 4324 NetworkCapabilities networkCapabilities) { 4325 // TODO - what else here? Verify still satisfies everybody? 4326 // Check if satisfies somebody new? call callbacks? 4327 synchronized (networkAgent) { 4328 networkAgent.networkCapabilities = networkCapabilities; 4329 } 4330 } 4331 4332 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) { 4333 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString()); 4334 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) { 4335 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0, 4336 networkRequest); 4337 } 4338 } 4339 4340 private void callCallbackForRequest(NetworkRequestInfo nri, 4341 NetworkAgentInfo networkAgent, int notificationType) { 4342 if (nri.messenger == null) return; // Default request has no msgr 4343 Object o; 4344 int a1 = 0; 4345 int a2 = 0; 4346 switch (notificationType) { 4347 case ConnectivityManager.CALLBACK_LOSING: 4348 a1 = 30 * 1000; // TODO - read this from NetworkMonitor 4349 // fall through 4350 case ConnectivityManager.CALLBACK_PRECHECK: 4351 case ConnectivityManager.CALLBACK_AVAILABLE: 4352 case ConnectivityManager.CALLBACK_LOST: 4353 case ConnectivityManager.CALLBACK_CAP_CHANGED: 4354 case ConnectivityManager.CALLBACK_IP_CHANGED: { 4355 o = new NetworkRequest(nri.request); 4356 a2 = networkAgent.network.netId; 4357 break; 4358 } 4359 case ConnectivityManager.CALLBACK_UNAVAIL: 4360 case ConnectivityManager.CALLBACK_RELEASED: { 4361 o = new NetworkRequest(nri.request); 4362 break; 4363 } 4364 default: { 4365 loge("Unknown notificationType " + notificationType); 4366 return; 4367 } 4368 } 4369 Message msg = Message.obtain(); 4370 msg.arg1 = a1; 4371 msg.arg2 = a2; 4372 msg.obj = o; 4373 msg.what = notificationType; 4374 try { 4375 if (VDBG) log("sending notification " + notificationType + " for " + nri.request); 4376 nri.messenger.send(msg); 4377 } catch (RemoteException e) { 4378 // may occur naturally in the race of binder death. 4379 loge("RemoteException caught trying to send a callback msg for " + nri.request); 4380 } 4381 } 4382 4383 private void handleLingerComplete(NetworkAgentInfo oldNetwork) { 4384 if (oldNetwork == null) { 4385 loge("Unknown NetworkAgentInfo in handleLingerComplete"); 4386 return; 4387 } 4388 if (DBG) log("handleLingerComplete for " + oldNetwork.name()); 4389 if (DBG) { 4390 if (oldNetwork.networkRequests.size() != 0) { 4391 loge("Dead network still had " + oldNetwork.networkRequests.size() + " requests"); 4392 } 4393 } 4394 oldNetwork.asyncChannel.disconnect(); 4395 } 4396 4397 private void makeDefault(NetworkAgentInfo newNetwork) { 4398 if (VDBG) log("Switching to new default network: " + newNetwork); 4399 mActiveDefaultNetwork = newNetwork.networkInfo.getType(); 4400 setupDataActivityTracking(newNetwork); 4401 try { 4402 mNetd.setDefaultNetId(newNetwork.network.netId); 4403 } catch (Exception e) { 4404 loge("Exception setting default network :" + e); 4405 } 4406 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy()); 4407 updateTcpBufferSizes(newNetwork); 4408 } 4409 4410 private void handleConnectionValidated(NetworkAgentInfo newNetwork) { 4411 if (newNetwork == null) { 4412 loge("Unknown NetworkAgentInfo in handleConnectionValidated"); 4413 return; 4414 } 4415 boolean keep = newNetwork.isVPN(); 4416 boolean isNewDefault = false; 4417 if (DBG) log("handleConnectionValidated for "+newNetwork.name()); 4418 // check if any NetworkRequest wants this NetworkAgent 4419 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>(); 4420 if (VDBG) log(" new Network has: " + newNetwork.networkCapabilities); 4421 for (NetworkRequestInfo nri : mNetworkRequests.values()) { 4422 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId); 4423 if (newNetwork == currentNetwork) { 4424 if (VDBG) log("Network " + newNetwork.name() + " was already satisfying" + 4425 " request " + nri.request.requestId + ". No change."); 4426 keep = true; 4427 continue; 4428 } 4429 4430 // check if it satisfies the NetworkCapabilities 4431 if (VDBG) log(" checking if request is satisfied: " + nri.request); 4432 if (nri.request.networkCapabilities.satisfiedByNetworkCapabilities( 4433 newNetwork.networkCapabilities)) { 4434 if (!nri.isRequest) { 4435 newNetwork.addRequest(nri.request); 4436 continue; 4437 } 4438 // next check if it's better than any current network we're using for 4439 // this request 4440 if (VDBG) { 4441 log("currentScore = " + 4442 (currentNetwork != null ? currentNetwork.currentScore : 0) + 4443 ", newScore = " + newNetwork.currentScore); 4444 } 4445 if (currentNetwork == null || 4446 currentNetwork.currentScore < newNetwork.currentScore) { 4447 if (currentNetwork != null) { 4448 if (VDBG) log(" accepting network in place of " + currentNetwork.name()); 4449 currentNetwork.networkRequests.remove(nri.request.requestId); 4450 currentNetwork.networkLingered.add(nri.request); 4451 affectedNetworks.add(currentNetwork); 4452 } else { 4453 if (VDBG) log(" accepting network in place of null"); 4454 } 4455 mNetworkForRequestId.put(nri.request.requestId, newNetwork); 4456 newNetwork.addRequest(nri.request); 4457 if (nri.isRequest && nri.request.legacyType != TYPE_NONE) { 4458 mLegacyTypeTracker.add(nri.request.legacyType, newNetwork); 4459 } 4460 keep = true; 4461 // TODO - this could get expensive if we have alot of requests for this 4462 // network. Think about if there is a way to reduce this. Push 4463 // netid->request mapping to each factory? 4464 sendUpdatedScoreToFactories(nri.request, newNetwork.currentScore); 4465 if (mDefaultRequest.requestId == nri.request.requestId) { 4466 isNewDefault = true; 4467 updateActiveDefaultNetwork(newNetwork); 4468 if (newNetwork.linkProperties != null) { 4469 updateTcpBufferSizes(newNetwork); 4470 setDefaultDnsSystemProperties( 4471 newNetwork.linkProperties.getDnsServers()); 4472 } else { 4473 setDefaultDnsSystemProperties(new ArrayList<InetAddress>()); 4474 } 4475 // Maintain the illusion: since the legacy API only 4476 // understands one network at a time, we must pretend 4477 // that the current default network disconnected before 4478 // the new one connected. 4479 if (currentNetwork != null) { 4480 mLegacyTypeTracker.remove(currentNetwork.networkInfo.getType(), 4481 currentNetwork); 4482 } 4483 mDefaultInetConditionPublished = 100; 4484 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork); 4485 } 4486 } 4487 } 4488 } 4489 for (NetworkAgentInfo nai : affectedNetworks) { 4490 boolean teardown = !nai.isVPN(); 4491 for (int i = 0; i < nai.networkRequests.size() && teardown; i++) { 4492 NetworkRequest nr = nai.networkRequests.valueAt(i); 4493 try { 4494 if (mNetworkRequests.get(nr).isRequest) { 4495 teardown = false; 4496 } 4497 } catch (Exception e) { 4498 loge("Request " + nr + " not found in mNetworkRequests."); 4499 loge(" it came from request list of " + nai.name()); 4500 } 4501 } 4502 if (teardown) { 4503 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER); 4504 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING); 4505 } else { 4506 // not going to linger, so kill the list of linger networks.. only 4507 // notify them of linger if it happens as the result of gaining another, 4508 // but if they transition and old network stays up, don't tell them of linger 4509 // or very delayed loss 4510 nai.networkLingered.clear(); 4511 if (VDBG) log("Lingered for " + nai.name() + " cleared"); 4512 } 4513 } 4514 if (keep) { 4515 if (isNewDefault) { 4516 makeDefault(newNetwork); 4517 synchronized (ConnectivityService.this) { 4518 // have a new default network, release the transition wakelock in 4519 // a second if it's held. The second pause is to allow apps 4520 // to reconnect over the new network 4521 if (mNetTransitionWakeLock.isHeld()) { 4522 mHandler.sendMessageDelayed(mHandler.obtainMessage( 4523 EVENT_CLEAR_NET_TRANSITION_WAKELOCK, 4524 mNetTransitionWakeLockSerialNumber, 0), 4525 1000); 4526 } 4527 } 4528 } 4529 4530 // Notify battery stats service about this network, both the normal 4531 // interface and any stacked links. 4532 try { 4533 final IBatteryStats bs = BatteryStatsService.getService(); 4534 final int type = newNetwork.networkInfo.getType(); 4535 4536 final String baseIface = newNetwork.linkProperties.getInterfaceName(); 4537 bs.noteNetworkInterfaceType(baseIface, type); 4538 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) { 4539 final String stackedIface = stacked.getInterfaceName(); 4540 bs.noteNetworkInterfaceType(stackedIface, type); 4541 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface); 4542 } 4543 } catch (RemoteException ignored) { 4544 } 4545 4546 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE); 4547 } else { 4548 if (DBG && newNetwork.networkRequests.size() != 0) { 4549 loge("tearing down network with live requests:"); 4550 for (int i=0; i < newNetwork.networkRequests.size(); i++) { 4551 loge(" " + newNetwork.networkRequests.valueAt(i)); 4552 } 4553 } 4554 if (VDBG) log("Validated network turns out to be unwanted. Tear it down."); 4555 newNetwork.asyncChannel.disconnect(); 4556 } 4557 } 4558 4559 4560 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) { 4561 NetworkInfo.State state = newInfo.getState(); 4562 NetworkInfo oldInfo = null; 4563 synchronized (networkAgent) { 4564 oldInfo = networkAgent.networkInfo; 4565 networkAgent.networkInfo = newInfo; 4566 } 4567 if (networkAgent.isVPN() && mLockdownTracker != null) { 4568 mLockdownTracker.onVpnStateChanged(newInfo); 4569 } 4570 4571 if (oldInfo != null && oldInfo.getState() == state) { 4572 if (VDBG) log("ignoring duplicate network state non-change"); 4573 return; 4574 } 4575 if (DBG) { 4576 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " + 4577 (oldInfo == null ? "null" : oldInfo.getState()) + 4578 " to " + state); 4579 } 4580 4581 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) { 4582 try { 4583 // This should never fail. Specifying an already in use NetID will cause failure. 4584 if (networkAgent.isVPN()) { 4585 mNetd.createVirtualNetwork(networkAgent.network.netId, 4586 !networkAgent.linkProperties.getDnsServers().isEmpty(), 4587 (networkAgent.networkMisc == null || 4588 !networkAgent.networkMisc.allowBypass)); 4589 } else { 4590 mNetd.createPhysicalNetwork(networkAgent.network.netId); 4591 } 4592 } catch (Exception e) { 4593 loge("Error creating network " + networkAgent.network.netId + ": " 4594 + e.getMessage()); 4595 return; 4596 } 4597 networkAgent.created = true; 4598 updateLinkProperties(networkAgent, null); 4599 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK); 4600 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED); 4601 if (networkAgent.isVPN()) { 4602 // Temporarily disable the default proxy (not global). 4603 synchronized (mProxyLock) { 4604 if (!mDefaultProxyDisabled) { 4605 mDefaultProxyDisabled = true; 4606 if (mGlobalProxy == null && mDefaultProxy != null) { 4607 sendProxyBroadcast(null); 4608 } 4609 } 4610 } 4611 // TODO: support proxy per network. 4612 } 4613 // Make default network if we have no default. Any network is better than no network. 4614 if (mNetworkForRequestId.get(mDefaultRequest.requestId) == null && 4615 networkAgent.isVPN() == false && 4616 mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities( 4617 networkAgent.networkCapabilities)) { 4618 makeDefault(networkAgent); 4619 } 4620 } else if (state == NetworkInfo.State.DISCONNECTED || 4621 state == NetworkInfo.State.SUSPENDED) { 4622 networkAgent.asyncChannel.disconnect(); 4623 if (networkAgent.isVPN()) { 4624 synchronized (mProxyLock) { 4625 if (mDefaultProxyDisabled) { 4626 mDefaultProxyDisabled = false; 4627 if (mGlobalProxy == null && mDefaultProxy != null) { 4628 sendProxyBroadcast(mDefaultProxy); 4629 } 4630 } 4631 } 4632 } 4633 } 4634 } 4635 4636 private void updateNetworkScore(NetworkAgentInfo nai, int score) { 4637 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score); 4638 4639 nai.currentScore = score; 4640 4641 // TODO - This will not do the right thing if this network is lowering 4642 // its score and has requests that can be served by other 4643 // currently-active networks, or if the network is increasing its 4644 // score and other networks have requests that can be better served 4645 // by this network. 4646 // 4647 // Really we want to see if any of our requests migrate to other 4648 // active/lingered networks and if any other requests migrate to us (depending 4649 // on increasing/decreasing currentScore. That's a bit of work and probably our 4650 // score checking/network allocation code needs to be modularized so we can understand 4651 // (see handleConnectionValided for an example). 4652 // 4653 // As a first order approx, lets just advertise the new score to factories. If 4654 // somebody can beat it they will nominate a network and our normal net replacement 4655 // code will fire. 4656 for (int i = 0; i < nai.networkRequests.size(); i++) { 4657 NetworkRequest nr = nai.networkRequests.valueAt(i); 4658 sendUpdatedScoreToFactories(nr, score); 4659 } 4660 } 4661 4662 // notify only this one new request of the current state 4663 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) { 4664 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE; 4665 // TODO - read state from monitor to decide what to send. 4666// if (nai.networkMonitor.isLingering()) { 4667// notifyType = NetworkCallbacks.LOSING; 4668// } else if (nai.networkMonitor.isEvaluating()) { 4669// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType); 4670// } 4671 callCallbackForRequest(nri, nai, notifyType); 4672 } 4673 4674 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) { 4675 // The NetworkInfo we actually send out has no bearing on the real 4676 // state of affairs. For example, if the default connection is mobile, 4677 // and a request for HIPRI has just gone away, we need to pretend that 4678 // HIPRI has just disconnected. So we need to set the type to HIPRI and 4679 // the state to DISCONNECTED, even though the network is of type MOBILE 4680 // and is still connected. 4681 NetworkInfo info = new NetworkInfo(nai.networkInfo); 4682 info.setType(type); 4683 if (connected) { 4684 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo()); 4685 sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay()); 4686 } else { 4687 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo()); 4688 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION); 4689 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info); 4690 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType()); 4691 if (info.isFailover()) { 4692 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true); 4693 nai.networkInfo.setFailover(false); 4694 } 4695 if (info.getReason() != null) { 4696 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason()); 4697 } 4698 if (info.getExtraInfo() != null) { 4699 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo()); 4700 } 4701 NetworkAgentInfo newDefaultAgent = null; 4702 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) { 4703 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId); 4704 if (newDefaultAgent != null) { 4705 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, 4706 newDefaultAgent.networkInfo); 4707 } else { 4708 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true); 4709 } 4710 } 4711 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, 4712 mDefaultInetConditionPublished); 4713 final Intent immediateIntent = new Intent(intent); 4714 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE); 4715 sendStickyBroadcast(immediateIntent); 4716 sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay()); 4717 if (newDefaultAgent != null) { 4718 sendConnectedBroadcastDelayed(newDefaultAgent.networkInfo, 4719 getConnectivityChangeDelay()); 4720 } 4721 } 4722 } 4723 4724 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) { 4725 if (VDBG) log("notifyType " + notifyType + " for " + networkAgent.name()); 4726 for (int i = 0; i < networkAgent.networkRequests.size(); i++) { 4727 NetworkRequest nr = networkAgent.networkRequests.valueAt(i); 4728 NetworkRequestInfo nri = mNetworkRequests.get(nr); 4729 if (VDBG) log(" sending notification for " + nr); 4730 callCallbackForRequest(nri, networkAgent, notifyType); 4731 } 4732 } 4733 4734 private LinkProperties getLinkPropertiesForTypeInternal(int networkType) { 4735 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 4736 if (nai != null) { 4737 synchronized (nai) { 4738 return new LinkProperties(nai.linkProperties); 4739 } 4740 } 4741 return new LinkProperties(); 4742 } 4743 4744 private NetworkInfo getNetworkInfoForType(int networkType) { 4745 if (!mLegacyTypeTracker.isTypeSupported(networkType)) 4746 return null; 4747 4748 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 4749 if (nai != null) { 4750 NetworkInfo result = new NetworkInfo(nai.networkInfo); 4751 result.setType(networkType); 4752 return result; 4753 } else { 4754 return new NetworkInfo(networkType, 0, "Unknown", ""); 4755 } 4756 } 4757 4758 private NetworkCapabilities getNetworkCapabilitiesForType(int networkType) { 4759 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType); 4760 if (nai != null) { 4761 synchronized (nai) { 4762 return new NetworkCapabilities(nai.networkCapabilities); 4763 } 4764 } 4765 return new NetworkCapabilities(); 4766 } 4767 4768 @Override 4769 public boolean addVpnAddress(String address, int prefixLength) { 4770 throwIfLockdownEnabled(); 4771 int user = UserHandle.getUserId(Binder.getCallingUid()); 4772 synchronized (mVpns) { 4773 return mVpns.get(user).addAddress(address, prefixLength); 4774 } 4775 } 4776 4777 @Override 4778 public boolean removeVpnAddress(String address, int prefixLength) { 4779 throwIfLockdownEnabled(); 4780 int user = UserHandle.getUserId(Binder.getCallingUid()); 4781 synchronized (mVpns) { 4782 return mVpns.get(user).removeAddress(address, prefixLength); 4783 } 4784 } 4785} 4786