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