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