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