From 051135c956e372c7b57e76df4e4530dbbcefdd39 Mon Sep 17 00:00:00 2001 From: Paul Jensen Date: Fri, 13 Mar 2015 14:06:12 -0400 Subject: [PATCH 1/7] Fix javadoc braces for ConnectivityManager.EXTRA_NETWORK. Change-Id: I5ad30a34f96e9e99a557b5bae9a30bfc08c89620 --- core/java/android/net/ConnectivityManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java index eb2df0bf0d..3b0d567ce1 100644 --- a/core/java/android/net/ConnectivityManager.java +++ b/core/java/android/net/ConnectivityManager.java @@ -2370,7 +2370,7 @@ public class ConnectivityManager { * successfully finding a network for the applications request. Retrieve it with * {@link android.content.Intent#getParcelableExtra(String)}. *

- * Note that if you intend to invoke (@link #setProcessDefaultNetwork(Network)) or + * Note that if you intend to invoke {@link #setProcessDefaultNetwork} or * {@link Network#openConnection(java.net.URL)} then you must get a * ConnectivityManager instance before doing so. */ From e82e0f0a8c163e39b3339d83bce662d5864d4490 Mon Sep 17 00:00:00 2001 From: Lorenzo Colitti Date: Tue, 10 Mar 2015 01:32:40 +0900 Subject: [PATCH 2/7] Add two utility methods for IPv4 netmasks. 1. Add a validating method to convert a netmask to a prefix length. 2. Add a function to get the implicit netmask of an IPv4 address. 3. Add a unit test. Bug: 19704592 Change-Id: Icb9f58d3903ea01df9e3720383c9bd5db6dd8f26 --- core/java/android/net/NetworkUtils.java | 35 ++++++++++ .../src/android/net/NetworkUtilsTest.java | 70 +++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 core/tests/coretests/src/android/net/NetworkUtilsTest.java diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java index 8003afb3e8..4f35a22b45 100644 --- a/core/java/android/net/NetworkUtils.java +++ b/core/java/android/net/NetworkUtils.java @@ -229,6 +229,25 @@ public class NetworkUtils { return Integer.bitCount(netmask); } + /** + * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous. + * @param netmask as a {@code Inet4Address}. + * @return the network prefix length + * @throws IllegalArgumentException the specified netmask was not contiguous. + * @hide + */ + public static int netmaskToPrefixLength(Inet4Address netmask) { + // inetAddressToInt returns an int in *network* byte order. + int i = Integer.reverseBytes(inetAddressToInt(netmask)); + int prefixLength = Integer.bitCount(i); + int trailingZeros = Integer.numberOfTrailingZeros(i); + if (trailingZeros != 32 - prefixLength) { + throw new IllegalArgumentException("Non-contiguous netmask: " + Integer.toHexString(i)); + } + return prefixLength; + } + + /** * Create an InetAddress from a string where the string must be a standard * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure @@ -308,6 +327,22 @@ public class NetworkUtils { return netPart; } + /** + * Returns the implicit netmask of an IPv4 address, as was the custom before 1993. + */ + public static int getImplicitNetmask(Inet4Address address) { + int firstByte = address.getAddress()[0] & 0xff; // Convert to an unsigned value. + if (firstByte < 128) { + return 8; + } else if (firstByte < 192) { + return 16; + } else if (firstByte < 224) { + return 24; + } else { + return 32; // Will likely not end well for other reasons. + } + } + /** * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64". * @hide diff --git a/core/tests/coretests/src/android/net/NetworkUtilsTest.java b/core/tests/coretests/src/android/net/NetworkUtilsTest.java new file mode 100644 index 0000000000..8d51c3b012 --- /dev/null +++ b/core/tests/coretests/src/android/net/NetworkUtilsTest.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.net; + +import android.net.NetworkUtils; +import android.test.suitebuilder.annotation.SmallTest; + +import java.net.Inet4Address; +import java.net.InetAddress; + +import junit.framework.TestCase; + +public class NetworkUtilsTest extends TestCase { + + private InetAddress Address(String addr) { + return InetAddress.parseNumericAddress(addr); + } + + private Inet4Address IPv4Address(String addr) { + return (Inet4Address) Address(addr); + } + + @SmallTest + public void testGetImplicitNetmask() { + assertEquals(8, NetworkUtils.getImplicitNetmask(IPv4Address("4.2.2.2"))); + assertEquals(8, NetworkUtils.getImplicitNetmask(IPv4Address("10.5.6.7"))); + assertEquals(16, NetworkUtils.getImplicitNetmask(IPv4Address("173.194.72.105"))); + assertEquals(16, NetworkUtils.getImplicitNetmask(IPv4Address("172.23.68.145"))); + assertEquals(24, NetworkUtils.getImplicitNetmask(IPv4Address("192.0.2.1"))); + assertEquals(24, NetworkUtils.getImplicitNetmask(IPv4Address("192.168.5.1"))); + assertEquals(32, NetworkUtils.getImplicitNetmask(IPv4Address("224.0.0.1"))); + assertEquals(32, NetworkUtils.getImplicitNetmask(IPv4Address("255.6.7.8"))); + } + + private void assertInvalidNetworkMask(Inet4Address addr) { + try { + NetworkUtils.netmaskToPrefixLength(addr); + fail("Invalid netmask " + addr.getHostAddress() + " did not cause exception"); + } catch (IllegalArgumentException expected) { + } + } + + @SmallTest + public void testNetmaskToPrefixLength() { + assertEquals(0, NetworkUtils.netmaskToPrefixLength(IPv4Address("0.0.0.0"))); + assertEquals(9, NetworkUtils.netmaskToPrefixLength(IPv4Address("255.128.0.0"))); + assertEquals(17, NetworkUtils.netmaskToPrefixLength(IPv4Address("255.255.128.0"))); + assertEquals(23, NetworkUtils.netmaskToPrefixLength(IPv4Address("255.255.254.0"))); + assertEquals(31, NetworkUtils.netmaskToPrefixLength(IPv4Address("255.255.255.254"))); + assertEquals(32, NetworkUtils.netmaskToPrefixLength(IPv4Address("255.255.255.255"))); + + assertInvalidNetworkMask(IPv4Address("0.0.0.1")); + assertInvalidNetworkMask(IPv4Address("255.255.255.253")); + assertInvalidNetworkMask(IPv4Address("255.255.0.255")); + } +} From c70fbac892c49707ef98ecddfeda0ff785c6f90f Mon Sep 17 00:00:00 2001 From: Lorenzo Colitti Date: Fri, 6 Mar 2015 19:57:39 +0900 Subject: [PATCH 3/7] DHCP: Add a native method for making a DHCP socket. Bug: 19704592 Change-Id: Iadd60d39c93aaabd2917e76791101a7d313b34be --- core/java/android/net/NetworkUtils.java | 7 ++++ core/jni/android_net_NetUtils.cpp | 50 +++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java index 4f35a22b45..01704e5363 100644 --- a/core/java/android/net/NetworkUtils.java +++ b/core/java/android/net/NetworkUtils.java @@ -16,9 +16,11 @@ package android.net; +import java.io.FileDescriptor; import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; +import java.net.SocketException; import java.net.UnknownHostException; import java.util.Collection; import java.util.Locale; @@ -138,6 +140,11 @@ public class NetworkUtils { */ public native static String getDhcpError(); + /** + * Attaches a socket filter that accepts DHCP packets to the given socket. + */ + public native static void attachDhcpFilter(FileDescriptor fd) throws SocketException; + /** * Binds the current process to the network designated by {@code netId}. All sockets created * in the future (and not explicitly bound via a bound {@link SocketFactory} (see diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp index e64f1defb6..2ba8e8c16e 100644 --- a/core/jni/android_net_NetUtils.cpp +++ b/core/jni/android_net_NetUtils.cpp @@ -24,6 +24,14 @@ #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include #include extern "C" { @@ -53,6 +61,8 @@ char *dhcp_get_errmsg(); namespace android { +static const uint16_t kDhcpClientPort = 68; + /* * The following remembers the jfieldID's of the fields * of the DhcpInfo Java object, so that we don't have @@ -215,6 +225,44 @@ static jstring android_net_utils_getDhcpError(JNIEnv* env, jobject clazz) return env->NewStringUTF(::dhcp_get_errmsg()); } +static void android_net_utils_attachDhcpFilter(JNIEnv *env, jobject clazz, jobject javaFd) +{ + int fd = jniGetFDFromFileDescriptor(env, javaFd); + uint32_t ip_offset = sizeof(ether_header); + uint32_t proto_offset = ip_offset + offsetof(iphdr, protocol); + uint32_t flags_offset = ip_offset + offsetof(iphdr, frag_off); + uint32_t dport_indirect_offset = ip_offset + offsetof(udphdr, dest); + struct sock_filter filter_code[] = { + // Check the protocol is UDP. + BPF_STMT(BPF_LD | BPF_B | BPF_ABS, proto_offset), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_UDP, 0, 6), + + // Check this is not a fragment. + BPF_STMT(BPF_LD | BPF_H | BPF_ABS, flags_offset), + BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K, 0x1fff, 4, 0), + + // Get the IP header length. + BPF_STMT(BPF_LDX | BPF_B | BPF_MSH, ip_offset), + + // Check the destination port. + BPF_STMT(BPF_LD | BPF_H | BPF_IND, dport_indirect_offset), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, kDhcpClientPort, 0, 1), + + // Accept or reject. + BPF_STMT(BPF_RET | BPF_K, 0xffff), + BPF_STMT(BPF_RET | BPF_K, 0) + }; + struct sock_fprog filter = { + sizeof(filter_code) / sizeof(filter_code[0]), + filter_code, + }; + + if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) { + jniThrowExceptionFmt(env, "java/net/SocketException", + "setsockopt(SO_ATTACH_FILTER): %s", strerror(errno)); + } +} + static jboolean android_net_utils_bindProcessToNetwork(JNIEnv *env, jobject thiz, jint netId) { return (jboolean) !setNetworkForProcess(netId); @@ -242,6 +290,7 @@ static jboolean android_net_utils_protectFromVpn(JNIEnv *env, jobject thiz, jint return (jboolean) !protectFromVpn(socket); } + // ---------------------------------------------------------------------------- /* @@ -261,6 +310,7 @@ static JNINativeMethod gNetworkUtilMethods[] = { { "bindProcessToNetworkForHostResolution", "(I)Z", (void*) android_net_utils_bindProcessToNetworkForHostResolution }, { "bindSocketToNetwork", "(II)I", (void*) android_net_utils_bindSocketToNetwork }, { "protectFromVpn", "(I)Z", (void*)android_net_utils_protectFromVpn }, + { "attachDhcpFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_attachDhcpFilter }, }; int register_android_net_NetworkUtils(JNIEnv* env) From b85f0b44a78b12140c088b4bc58ec3b02d081a22 Mon Sep 17 00:00:00 2001 From: Lorenzo Colitti Date: Tue, 17 Mar 2015 17:56:10 +0900 Subject: [PATCH 4/7] Add a protectFromVpn method that takes a FileDescriptor Bug: 19704592 Change-Id: I9aeb29c2f6cf55fa010bc606c99b21a797ac5a19 --- core/java/android/net/NetworkUtils.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java index 01704e5363..02fbe7350b 100644 --- a/core/java/android/net/NetworkUtils.java +++ b/core/java/android/net/NetworkUtils.java @@ -177,6 +177,15 @@ public class NetworkUtils { */ public native static int bindSocketToNetwork(int socketfd, int netId); + /** + * Protect {@code fd} from VPN connections. After protecting, data sent through + * this socket will go directly to the underlying network, so its traffic will not be + * forwarded through the VPN. + */ + public static boolean protectFromVpn(FileDescriptor fd) { + return protectFromVpn(fd.getInt$()); + } + /** * Protect {@code socketfd} from VPN connections. After protecting, data sent through * this socket will go directly to the underlying network, so its traffic will not be From d687dc5da9a3e65db9de75d05425bd29e0ea2be0 Mon Sep 17 00:00:00 2001 From: Erik Kline Date: Wed, 18 Mar 2015 08:08:57 +0900 Subject: [PATCH 5/7] Fix missing printf argument. Change-Id: Ifd1eebfbcefa06570882da54a1c410eabf26bce7 --- core/jni/android_net_NetUtils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp index 2ba8e8c16e..e97d61e54c 100644 --- a/core/jni/android_net_NetUtils.cpp +++ b/core/jni/android_net_NetUtils.cpp @@ -118,7 +118,7 @@ static jboolean android_net_utils_getDhcpResults(JNIEnv* env, jobject clazz, jst result = ::dhcp_get_results(nameStr, ipaddr, gateway, &prefixLength, dns, server, &lease, vendorInfo, domains, mtu); if (result != 0) { - ALOGD("dhcp_get_results failed : %s (%s)", nameStr); + ALOGD("dhcp_get_results failed : %s (%s)", nameStr, ::dhcp_get_errmsg()); } env->ReleaseStringUTFChars(ifname, nameStr); From ba9c42f6614f0310ccc3d06d8ed551821205d6fc Mon Sep 17 00:00:00 2001 From: Paul Jensen Date: Wed, 18 Mar 2015 09:33:07 -0400 Subject: [PATCH 6/7] Make NetworkCapabilities.NOT_VPN javadoc visible. Also adjust wording to be more suitable for NetworkRequests and NetworkAgents. Change-Id: I1cc93cb20779cf02d6ffa0fa11ad2916c199b365 --- core/java/android/net/NetworkCapabilities.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/java/android/net/NetworkCapabilities.java b/core/java/android/net/NetworkCapabilities.java index a7f9c5bcc0..8c8bfab9c7 100644 --- a/core/java/android/net/NetworkCapabilities.java +++ b/core/java/android/net/NetworkCapabilities.java @@ -148,9 +148,9 @@ public final class NetworkCapabilities implements Parcelable { */ public static final int NET_CAPABILITY_TRUSTED = 14; - /* + /** * Indicates that this network is not a VPN. This capability is set by default and should be - * explicitly cleared when creating VPN networks. + * explicitly cleared for VPN networks. */ public static final int NET_CAPABILITY_NOT_VPN = 15; From 8357dfd52091096de787a931c058991fa6d6471a Mon Sep 17 00:00:00 2001 From: Paul Jensen Date: Wed, 18 Mar 2015 12:29:13 -0400 Subject: [PATCH 7/7] Remove dead code, mostly DataStateTracker. (cherry picked from AOSP commit 9edb1fc511f5df7e3eb8cc68c4e37608e9ca507b) Change-Id: I18c44cd08dfb51e02a96d0b726e9af1db21e3058 --- .../java/android/net/ConnectivityManager.java | 33 -- .../android/net/IConnectivityManager.aidl | 4 - .../android/server/ConnectivityService.java | 294 ------------------ .../server/ConnectivityServiceTest.java | 1 - 4 files changed, 332 deletions(-) diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java index 3b0d567ce1..a00246fd99 100644 --- a/core/java/android/net/ConnectivityManager.java +++ b/core/java/android/net/ConnectivityManager.java @@ -1792,25 +1792,6 @@ public class ConnectivityManager { } } - /** - * Sets a secondary requirement bit for the given networkType. - * This requirement bit is generally under the control of the carrier - * or its agents and is not directly controlled by the user. - * - * @param networkType The network who's dependence has changed - * @param met Boolean - true if network use is OK, false if not - * - *

This method requires the call to hold the permission - * {@link android.Manifest.permission#CONNECTIVITY_INTERNAL}. - * {@hide} - */ - public void setDataDependency(int networkType, boolean met) { - try { - mService.setDataDependency(networkType, met); - } catch (RemoteException e) { - } - } - /** * Returns true if the hardware supports the given network type * else it returns false. This doesn't indicate we have coverage @@ -1891,20 +1872,6 @@ public class ConnectivityManager { } } - /** - * Supply the backend messenger for a network tracker - * - * @param networkType NetworkType to set - * @param messenger {@link Messenger} - * {@hide} - */ - public void supplyMessenger(int networkType, Messenger messenger) { - try { - mService.supplyMessenger(networkType, messenger); - } catch (RemoteException e) { - } - } - /** * Check mobile provisioning. * diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl index 46af112d1d..d8852f882c 100644 --- a/core/java/android/net/IConnectivityManager.aidl +++ b/core/java/android/net/IConnectivityManager.aidl @@ -102,8 +102,6 @@ interface IConnectivityManager ProxyInfo getDefaultProxy(); - void setDataDependency(int networkType, boolean met); - boolean prepareVpn(String oldPackage, String newPackage); void setVpnPackageAuthorization(boolean authorized); @@ -120,8 +118,6 @@ interface IConnectivityManager void captivePortalCheckCompleted(in NetworkInfo info, boolean isCaptivePortal); - void supplyMessenger(int networkType, in Messenger messenger); - int findConnectionTypeForIface(in String iface); int checkMobileProvisioning(int suggestedTimeOutMs); diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java index b72b29dbb1..d9ef766f2b 100644 --- a/services/core/java/com/android/server/ConnectivityService.java +++ b/services/core/java/com/android/server/ConnectivityService.java @@ -48,7 +48,6 @@ import android.net.INetworkPolicyManager; import android.net.INetworkStatsService; import android.net.LinkProperties; import android.net.LinkProperties.CompareResult; -import android.net.MobileDataStateTracker; import android.net.Network; import android.net.NetworkAgent; import android.net.NetworkCapabilities; @@ -59,12 +58,10 @@ import android.net.NetworkMisc; import android.net.NetworkQuotaInfo; import android.net.NetworkRequest; import android.net.NetworkState; -import android.net.NetworkStateTracker; import android.net.NetworkUtils; import android.net.Proxy; import android.net.ProxyInfo; import android.net.RouteInfo; -import android.net.SamplingDataTracker; import android.net.UidRange; import android.net.Uri; import android.os.Binder; @@ -153,9 +150,6 @@ public class ConnectivityService extends IConnectivityManager.Stub private static final boolean DBG = true; private static final boolean VDBG = false; - // network sampling debugging - private static final boolean SAMPLE_DBG = false; - private static final boolean LOGD_RULES = false; // TODO: create better separation between radio types and network types @@ -166,33 +160,10 @@ public class ConnectivityService extends IConnectivityManager.Stub private static final String NETWORK_RESTORE_DELAY_PROP_NAME = "android.telephony.apn-restore"; - // Default value if FAIL_FAST_TIME_MS is not set - private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000; - // system property that can override DEFAULT_FAIL_FAST_TIME_MS - private static final String FAIL_FAST_TIME_MS = - "persist.radio.fail_fast_time_ms"; - - private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED = - "android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED"; - - private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0; - // How long to delay to removal of a pending intent based request. // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS private final int mReleasePendingIntentDelayMs; - private PendingIntent mSampleIntervalElapsedIntent; - - // Set network sampling interval at 12 minutes, this way, even if the timers get - // aggregated, it will fire at around 15 minutes, which should allow us to - // aggregate this timer with other timers (specially the socket keep alive timers) - private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 12 * 60); - - // start network sampling a minute after booting ... - private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (SAMPLE_DBG ? 30 : 60); - - AlarmManager mAlarmManager; - private Tethering mTethering; private final PermissionMonitor mPermissionMonitor; @@ -212,13 +183,6 @@ public class ConnectivityService extends IConnectivityManager.Stub /** Set of ifaces that are costly. */ private HashSet mMeteredIfaces = Sets.newHashSet(); - /** - * Sometimes we want to refer to the individual network state - * trackers separately, and sometimes we just want to treat them - * abstractly. - */ - private NetworkStateTracker mNetTrackers[]; - private Context mContext; private int mNetworkPreference; // 0 is full bad, 100 is full good @@ -277,28 +241,11 @@ public class ConnectivityService extends IConnectivityManager.Stub */ private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9; - /** - * used internally to set external dependency met/unmet - * arg1 = ENABLED (met) or DISABLED (unmet) - * arg2 = NetworkType - */ - private static final int EVENT_SET_DEPENDENCY_MET = 10; - /** * used internally to send a sticky broadcast delayed. */ private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11; - /** - * Used internally to disable fail fast of mobile data - */ - private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14; - - /** - * used internally to indicate that data sampling interval is up - */ - private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15; - /** * PAC manager has received new port. */ @@ -419,8 +366,6 @@ public class ConnectivityService extends IConnectivityManager.Stub private DataConnectionStats mDataConnectionStats; - private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0); - TelephonyManager mTelephonyManager; // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp @@ -650,9 +595,6 @@ public class ConnectivityService extends IConnectivityManager.Stub com.android.internal.R.integer.config_networkTransitionTimeout); mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); - mNetTrackers = new NetworkStateTracker[ - ConnectivityManager.MAX_NETWORK_TYPE+1]; - mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1]; // TODO: What is the "correct" way to do determine if this is a wifi only device? @@ -740,23 +682,6 @@ public class ConnectivityService extends IConnectivityManager.Stub mDataConnectionStats = new DataConnectionStats(mContext); mDataConnectionStats.startMonitoring(); - mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE); - - IntentFilter filter = new IntentFilter(); - filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED); - mContext.registerReceiver( - new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) { - mHandler.sendMessage(mHandler.obtainMessage - (EVENT_SAMPLE_INTERVAL_ELAPSED)); - } - } - }, - new IntentFilter(filter)); - mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED); mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE); @@ -782,15 +707,6 @@ public class ConnectivityService extends IConnectivityManager.Stub throw new IllegalStateException("No free netIds"); } - private boolean teardown(NetworkStateTracker netTracker) { - if (netTracker.teardown()) { - netTracker.setTeardownRequested(true); - return true; - } else { - return false; - } - } - private NetworkState getFilteredNetworkState(int networkType, int uid) { NetworkInfo info = null; LinkProperties lp = null; @@ -1350,22 +1266,6 @@ public class ConnectivityService extends IConnectivityManager.Stub return true; } - public void setDataDependency(int networkType, boolean met) { - enforceConnectivityInternalPermission(); - - mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET, - (met ? ENABLED : DISABLED), networkType)); - } - - private void handleSetDependencyMet(int networkType, boolean met) { - if (mNetTrackers[networkType] != null) { - if (DBG) { - log("handleSetDependencyMet(" + networkType + ", " + met + ")"); - } - mNetTrackers[networkType].setDependencyMet(met); - } - } - private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() { @Override public void onUidRulesChanged(int uid, int uidRules) { @@ -1406,21 +1306,6 @@ public class ConnectivityService extends IConnectivityManager.Stub if (LOGD_RULES) { log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")"); } - - // kick off connectivity change broadcast for active network, since - // global background policy change is radical. - // TODO: Dead code; remove. - // - // final int networkType = mActiveDefaultNetwork; - // if (isNetworkTypeValid(networkType)) { - // final NetworkStateTracker tracker = mNetTrackers[networkType]; - // if (tracker != null) { - // final NetworkInfo info = tracker.getNetworkInfo(); - // if (info != null && info.isConnected()) { - // sendConnectedBroadcast(info); - // } - // } - // } } }; @@ -1536,14 +1421,6 @@ public class ConnectivityService extends IConnectivityManager.Stub } void systemReady() { - // start network sampling .. - Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED); - intent.setPackage(mContext.getPackageName()); - - mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext, - SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0); - setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent); - loadGlobalProxy(); synchronized(this) { @@ -2015,66 +1892,6 @@ public class ConnectivityService extends IConnectivityManager.Stub } break; } - case NetworkStateTracker.EVENT_STATE_CHANGED: { - info = (NetworkInfo) msg.obj; - NetworkInfo.State state = info.getState(); - - if (VDBG || (state == NetworkInfo.State.CONNECTED) || - (state == NetworkInfo.State.DISCONNECTED) || - (state == NetworkInfo.State.SUSPENDED)) { - log("ConnectivityChange for " + - info.getTypeName() + ": " + - state + "/" + info.getDetailedState()); - } - - EventLogTags.writeConnectivityStateChanged( - info.getType(), info.getSubtype(), info.getDetailedState().ordinal()); - - if (info.isConnectedToProvisioningNetwork()) { - /** - * TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING - * for now its an in between network, its a network that - * is actually a default network but we don't want it to be - * announced as such to keep background applications from - * trying to use it. It turns out that some still try so we - * take the additional step of clearing any default routes - * to the link that may have incorrectly setup by the lower - * levels. - */ - LinkProperties lp = getLinkPropertiesForType(info.getType()); - if (DBG) { - log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp); - } - - // Clear any default routes setup by the radio so - // any activity by applications trying to use this - // connection will fail until the provisioning network - // is enabled. - /* - for (RouteInfo r : lp.getRoutes()) { - removeRoute(lp, r, TO_DEFAULT_TABLE, - mNetTrackers[info.getType()].getNetwork().netId); - } - */ - } else if (state == NetworkInfo.State.DISCONNECTED) { - } else if (state == NetworkInfo.State.SUSPENDED) { - } else if (state == NetworkInfo.State.CONNECTED) { - // handleConnect(info); - } - notifyLockdownVpn(null); - break; - } - case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: { - info = (NetworkInfo) msg.obj; - // TODO: Temporary allowing network configuration - // change not resetting sockets. - // @see bug/4455071 - /* - handleConnectivityChange(info.getType(), mCurrentLinkProperties[info.getType()], - false); - */ - break; - } } } } @@ -2439,34 +2256,11 @@ public class ConnectivityService extends IConnectivityManager.Stub handleDeprecatedGlobalHttpProxy(); break; } - case EVENT_SET_DEPENDENCY_MET: { - boolean met = (msg.arg1 == ENABLED); - handleSetDependencyMet(msg.arg2, met); - break; - } case EVENT_SEND_STICKY_BROADCAST_INTENT: { Intent intent = (Intent)msg.obj; sendStickyBroadcast(intent); break; } - case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: { - int tag = mEnableFailFastMobileDataTag.get(); - if (msg.arg1 == tag) { - MobileDataStateTracker mobileDst = - (MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE]; - if (mobileDst != null) { - mobileDst.setEnableFailFastMobileData(msg.arg2); - } - } else { - log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1 - + " != tag:" + tag); - } - break; - } - case EVENT_SAMPLE_INTERVAL_ELAPSED: { - handleNetworkSamplingTimeout(); - break; - } case EVENT_PROXY_HAS_CHANGED: { handleApplyDefaultProxy((ProxyInfo)msg.obj); break; @@ -3066,14 +2860,6 @@ public class ConnectivityService extends IConnectivityManager.Stub } } - public void supplyMessenger(int networkType, Messenger messenger) { - enforceConnectivityInternalPermission(); - - if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) { - mNetTrackers[networkType].supplyMessenger(messenger); - } - } - public int findConnectionTypeForIface(String iface) { enforceConnectivityInternalPermission(); @@ -3091,23 +2877,6 @@ public class ConnectivityService extends IConnectivityManager.Stub return ConnectivityManager.TYPE_NONE; } - /** - * Have mobile data fail fast if enabled. - * - * @param enabled DctConstants.ENABLED/DISABLED - */ - private void setEnableFailFastMobileData(int enabled) { - int tag; - - if (enabled == DctConstants.ENABLED) { - tag = mEnableFailFastMobileDataTag.incrementAndGet(); - } else { - tag = mEnableFailFastMobileDataTag.get(); - } - mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag, - enabled)); - } - @Override public int checkMobileProvisioning(int suggestedTimeOutMs) { // TODO: Remove? Any reason to trigger a provisioning check? @@ -3392,69 +3161,6 @@ public class ConnectivityService extends IConnectivityManager.Stub } }; - /* Infrastructure for network sampling */ - - private void handleNetworkSamplingTimeout() { - - if (SAMPLE_DBG) log("Sampling interval elapsed, updating statistics .."); - - // initialize list of interfaces .. - Map mapIfaceToSample = - new HashMap(); - for (NetworkStateTracker tracker : mNetTrackers) { - if (tracker != null) { - String ifaceName = tracker.getNetworkInterfaceName(); - if (ifaceName != null) { - mapIfaceToSample.put(ifaceName, null); - } - } - } - - // Read samples for all interfaces - SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample); - - // process samples for all networks - for (NetworkStateTracker tracker : mNetTrackers) { - if (tracker != null) { - String ifaceName = tracker.getNetworkInterfaceName(); - SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName); - if (ss != null) { - // end the previous sampling cycle - tracker.stopSampling(ss); - // start a new sampling cycle .. - tracker.startSampling(ss); - } - } - } - - if (SAMPLE_DBG) log("Done."); - - int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(), - Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS, - DEFAULT_SAMPLING_INTERVAL_IN_SECONDS); - - if (SAMPLE_DBG) { - log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds"); - } - - setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent); - } - - /** - * Sets a network sampling alarm. - */ - void setAlarm(int timeoutInMilliseconds, PendingIntent intent) { - long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds; - int alarmType; - if (Resources.getSystem().getBoolean( - R.bool.config_networkSamplingWakesDevice)) { - alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP; - } else { - alarmType = AlarmManager.ELAPSED_REALTIME; - } - mAlarmManager.set(alarmType, wakeupTime, intent); - } - private final HashMap mNetworkFactoryInfos = new HashMap(); private final HashMap mNetworkRequests = diff --git a/services/tests/servicestests/src/com/android/server/ConnectivityServiceTest.java b/services/tests/servicestests/src/com/android/server/ConnectivityServiceTest.java index beb353a6cf..c19890075a 100644 --- a/services/tests/servicestests/src/com/android/server/ConnectivityServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/ConnectivityServiceTest.java @@ -20,7 +20,6 @@ import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE; import static android.net.ConnectivityManager.TYPE_MOBILE; import static android.net.ConnectivityManager.TYPE_WIFI; import static android.net.ConnectivityManager.getNetworkTypeName; -import static android.net.NetworkStateTracker.EVENT_STATE_CHANGED; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA;