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