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