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