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