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