Merge "Fix CTS test failed on R device"
diff --git a/Tethering/Android.bp b/Tethering/Android.bp
index 73175580..742fd02 100644
--- a/Tethering/Android.bp
+++ b/Tethering/Android.bp
@@ -14,6 +14,10 @@
// limitations under the License.
//
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
java_defaults {
name: "TetheringAndroidLibraryDefaults",
sdk_version: "module_current",
@@ -29,8 +33,7 @@
"androidx.annotation_annotation",
"modules-utils-build",
"netlink-client",
- // TODO: use networkstack-client instead of just including the AIDL interface
- "networkstack-aidl-interfaces-unstable-java",
+ "networkstack-client",
"android.hardware.tetheroffload.config-V1.0-java",
"android.hardware.tetheroffload.control-V1.0-java",
"net-utils-framework-common",
@@ -145,3 +148,10 @@
apex_available: ["com.android.tethering"],
min_sdk_version: "30",
}
+
+sdk {
+ name: "tethering-module-sdk",
+ java_sdk_libs: [
+ "framework-tethering",
+ ],
+}
diff --git a/Tethering/apex/Android.bp b/Tethering/apex/Android.bp
index 7970944..e9deeff 100644
--- a/Tethering/apex/Android.bp
+++ b/Tethering/apex/Android.bp
@@ -14,11 +14,15 @@
// limitations under the License.
//
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
apex {
name: "com.android.tethering",
// TODO: make updatable again once this contains only updatable artifacts (in particular, this
// cannot build as updatable unless service-connectivity builds against stable API).
- // updatable: true,
+ updatable: false,
// min_sdk_version: "30",
java_libs: [
"framework-tethering",
diff --git a/Tethering/bpf_progs/Android.bp b/Tethering/bpf_progs/Android.bp
index b06528b..2b10f89 100644
--- a/Tethering/bpf_progs/Android.bp
+++ b/Tethering/bpf_progs/Android.bp
@@ -17,6 +17,10 @@
//
// struct definitions shared with JNI
//
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
cc_library_headers {
name: "bpf_tethering_headers",
vendor_available: false,
diff --git a/Tethering/bpf_progs/bpf_tethering.h b/Tethering/bpf_progs/bpf_tethering.h
index 10e6bb0..efda228 100644
--- a/Tethering/bpf_progs/bpf_tethering.h
+++ b/Tethering/bpf_progs/bpf_tethering.h
@@ -16,6 +16,11 @@
#pragma once
+#include <linux/if.h>
+#include <linux/if_ether.h>
+#include <linux/in.h>
+#include <linux/in6.h>
+
// Common definitions for BPF code in the tethering mainline module.
// These definitions are available to:
// - The BPF programs in Tethering/bpf_progs/
@@ -41,8 +46,10 @@
ERR(CHECKSUM) \
ERR(NON_TCP_UDP) \
ERR(NON_TCP) \
+ ERR(SHORT_L4_HEADER) \
ERR(SHORT_TCP_HEADER) \
ERR(SHORT_UDP_HEADER) \
+ ERR(UDP_CSUM_ZERO) \
ERR(TRUNCATED_IPV4) \
ERR(_MAX)
@@ -57,3 +64,151 @@
BPF_TETHER_ERRORS
};
#undef ERR
+
+// This header file is shared by eBPF kernel programs (C) and netd (C++) and
+// some of the maps are also accessed directly from Java mainline module code.
+//
+// Hence: explicitly pad all relevant structures and assert that their size
+// is the sum of the sizes of their fields.
+#define STRUCT_SIZE(name, size) _Static_assert(sizeof(name) == (size), "Incorrect struct size.")
+
+
+#define BPF_PATH_TETHER BPF_PATH "tethering/"
+
+#define TETHER_STATS_MAP_PATH BPF_PATH_TETHER "map_offload_tether_stats_map"
+
+typedef uint32_t TetherStatsKey; // upstream ifindex
+
+typedef struct {
+ uint64_t rxPackets;
+ uint64_t rxBytes;
+ uint64_t rxErrors;
+ uint64_t txPackets;
+ uint64_t txBytes;
+ uint64_t txErrors;
+} TetherStatsValue;
+STRUCT_SIZE(TetherStatsValue, 6 * 8); // 48
+
+#define TETHER_LIMIT_MAP_PATH BPF_PATH_TETHER "map_offload_tether_limit_map"
+
+typedef uint32_t TetherLimitKey; // upstream ifindex
+typedef uint64_t TetherLimitValue; // in bytes
+
+#define TETHER_DOWNSTREAM6_TC_PROG_RAWIP_NAME "prog_offload_schedcls_tether_downstream6_rawip"
+#define TETHER_DOWNSTREAM6_TC_PROG_ETHER_NAME "prog_offload_schedcls_tether_downstream6_ether"
+
+#define TETHER_DOWNSTREAM6_TC_PROG_RAWIP_PATH BPF_PATH_TETHER TETHER_DOWNSTREAM6_TC_PROG_RAWIP_NAME
+#define TETHER_DOWNSTREAM6_TC_PROG_ETHER_PATH BPF_PATH_TETHER TETHER_DOWNSTREAM6_TC_PROG_ETHER_NAME
+
+#define TETHER_DOWNSTREAM6_MAP_PATH BPF_PATH_TETHER "map_offload_tether_downstream6_map"
+
+// For now tethering offload only needs to support downstreams that use 6-byte MAC addresses,
+// because all downstream types that are currently supported (WiFi, USB, Bluetooth and
+// Ethernet) have 6-byte MAC addresses.
+
+typedef struct {
+ uint32_t iif; // The input interface index
+ // TODO: extend this to include dstMac
+ struct in6_addr neigh6; // The destination IPv6 address
+} TetherDownstream6Key;
+STRUCT_SIZE(TetherDownstream6Key, 4 + 16); // 20
+
+typedef struct {
+ uint32_t oif; // The output interface to redirect to
+ struct ethhdr macHeader; // includes dst/src mac and ethertype (zeroed iff rawip egress)
+ uint16_t pmtu; // The maximum L3 output path/route mtu
+} Tether6Value;
+STRUCT_SIZE(Tether6Value, 4 + 14 + 2); // 20
+
+#define TETHER_DOWNSTREAM64_MAP_PATH BPF_PATH_TETHER "map_offload_tether_downstream64_map"
+
+typedef struct {
+ uint32_t iif; // The input interface index
+ uint8_t dstMac[ETH_ALEN]; // destination ethernet mac address (zeroed iff rawip ingress)
+ uint16_t l4Proto; // IPPROTO_TCP/UDP/...
+ struct in6_addr src6; // source &
+ struct in6_addr dst6; // destination IPv6 addresses
+ __be16 srcPort; // source &
+ __be16 dstPort; // destination tcp/udp/... ports
+} TetherDownstream64Key;
+STRUCT_SIZE(TetherDownstream64Key, 4 + 6 + 2 + 16 + 16 + 2 + 2); // 48
+
+typedef struct {
+ uint32_t oif; // The output interface to redirect to
+ struct ethhdr macHeader; // includes dst/src mac and ethertype (zeroed iff rawip egress)
+ uint16_t pmtu; // The maximum L3 output path/route mtu
+ struct in_addr src4; // source &
+ struct in_addr dst4; // destination IPv4 addresses
+ __be16 srcPort; // source &
+ __be16 outPort; // destination tcp/udp/... ports
+ uint64_t lastUsed; // Kernel updates on each use with bpf_ktime_get_boot_ns()
+} TetherDownstream64Value;
+STRUCT_SIZE(TetherDownstream64Value, 4 + 14 + 2 + 4 + 4 + 2 + 2 + 8); // 40
+
+#define TETHER_UPSTREAM6_TC_PROG_RAWIP_NAME "prog_offload_schedcls_tether_upstream6_rawip"
+#define TETHER_UPSTREAM6_TC_PROG_ETHER_NAME "prog_offload_schedcls_tether_upstream6_ether"
+
+#define TETHER_UPSTREAM6_TC_PROG_RAWIP_PATH BPF_PATH_TETHER TETHER_UPSTREAM6_TC_PROG_RAWIP_NAME
+#define TETHER_UPSTREAM6_TC_PROG_ETHER_PATH BPF_PATH_TETHER TETHER_UPSTREAM6_TC_PROG_ETHER_NAME
+
+#define TETHER_UPSTREAM6_MAP_PATH BPF_PATH_TETHER "map_offload_tether_upstream6_map"
+
+typedef struct {
+ uint32_t iif; // The input interface index
+ // TODO: extend this to include dstMac and src ip /64 subnet
+} TetherUpstream6Key;
+STRUCT_SIZE(TetherUpstream6Key, 4);
+
+#define TETHER_DOWNSTREAM4_TC_PROG_RAWIP_NAME "prog_offload_schedcls_tether_downstream4_rawip"
+#define TETHER_DOWNSTREAM4_TC_PROG_ETHER_NAME "prog_offload_schedcls_tether_downstream4_ether"
+
+#define TETHER_DOWNSTREAM4_TC_PROG_RAWIP_PATH BPF_PATH_TETHER TETHER_DOWNSTREAM4_TC_PROG_RAWIP_NAME
+#define TETHER_DOWNSTREAM4_TC_PROG_ETHER_PATH BPF_PATH_TETHER TETHER_DOWNSTREAM4_TC_PROG_ETHER_NAME
+
+#define TETHER_DOWNSTREAM4_MAP_PATH BPF_PATH_TETHER "map_offload_tether_downstream4_map"
+
+
+#define TETHER_UPSTREAM4_TC_PROG_RAWIP_NAME "prog_offload_schedcls_tether_upstream4_rawip"
+#define TETHER_UPSTREAM4_TC_PROG_ETHER_NAME "prog_offload_schedcls_tether_upstream4_ether"
+
+#define TETHER_UPSTREAM4_TC_PROG_RAWIP_PATH BPF_PATH_TETHER TETHER_UPSTREAM4_TC_PROG_RAWIP_NAME
+#define TETHER_UPSTREAM4_TC_PROG_ETHER_PATH BPF_PATH_TETHER TETHER_UPSTREAM4_TC_PROG_ETHER_NAME
+
+#define TETHER_UPSTREAM4_MAP_PATH BPF_PATH_TETHER "map_offload_tether_upstream4_map"
+
+typedef struct {
+ uint32_t iif; // The input interface index
+ uint8_t dstMac[ETH_ALEN]; // destination ethernet mac address (zeroed iff rawip ingress)
+ uint16_t l4Proto; // IPPROTO_TCP/UDP/...
+ struct in_addr src4; // source &
+ struct in_addr dst4; // destination IPv4 addresses
+ __be16 srcPort; // source &
+ __be16 dstPort; // destination TCP/UDP/... ports
+} Tether4Key;
+STRUCT_SIZE(Tether4Key, 4 + 6 + 2 + 4 + 4 + 2 + 2); // 24
+
+typedef struct {
+ uint32_t oif; // The output interface to redirect to
+ struct ethhdr macHeader; // includes dst/src mac and ethertype (zeroed iff rawip egress)
+ uint16_t pmtu; // Maximum L3 output path/route mtu
+ struct in6_addr src46; // source & (always IPv4 mapped for downstream)
+ struct in6_addr dst46; // destination IP addresses (may be IPv4 mapped or IPv6 for upstream)
+ __be16 srcPort; // source &
+ __be16 dstPort; // destination tcp/udp/... ports
+ uint64_t last_used; // Kernel updates on each use with bpf_ktime_get_boot_ns()
+} Tether4Value;
+STRUCT_SIZE(Tether4Value, 4 + 14 + 2 + 16 + 16 + 2 + 2 + 8); // 64
+
+#define TETHER_DOWNSTREAM_XDP_PROG_RAWIP_NAME "prog_offload_xdp_tether_downstream_rawip"
+#define TETHER_DOWNSTREAM_XDP_PROG_ETHER_NAME "prog_offload_xdp_tether_downstream_ether"
+
+#define TETHER_DOWNSTREAM_XDP_PROG_RAWIP_PATH BPF_PATH_TETHER TETHER_DOWNSTREAM_XDP_PROG_RAWIP_NAME
+#define TETHER_DOWNSTREAM_XDP_PROG_ETHER_PATH BPF_PATH_TETHER TETHER_DOWNSTREAM_XDP_PROG_ETHER_NAME
+
+#define TETHER_UPSTREAM_XDP_PROG_RAWIP_NAME "prog_offload_xdp_tether_upstream_rawip"
+#define TETHER_UPSTREAM_XDP_PROG_ETHER_NAME "prog_offload_xdp_tether_upstream_ether"
+
+#define TETHER_UPSTREAM_XDP_PROG_RAWIP_PATH BPF_PATH_TETHER TETHER_UPSTREAM_XDP_PROG_RAWIP_NAME
+#define TETHER_UPSTREAM_XDP_PROG_ETHER_PATH BPF_PATH_TETHER TETHER_UPSTREAM_XDP_PROG_ETHER_NAME
+
+#undef STRUCT_SIZE
diff --git a/Tethering/bpf_progs/offload.c b/Tethering/bpf_progs/offload.c
index d4b5246..ea64343 100644
--- a/Tethering/bpf_progs/offload.c
+++ b/Tethering/bpf_progs/offload.c
@@ -27,7 +27,6 @@
#include "bpf_helpers.h"
#include "bpf_net_helpers.h"
#include "bpf_tethering.h"
-#include "netdbpf/bpf_shared.h"
// From kernel:include/net/ip.h
#define IP_DF 0x4000 // Flag: "Don't Fragment"
@@ -68,7 +67,25 @@
#define ETH_IP6_TCP_OFFSET(field) (ETH_HLEN + IP6_TCP_OFFSET(field))
#define ETH_IP6_UDP_OFFSET(field) (ETH_HLEN + IP6_UDP_OFFSET(field))
-// ----- Tethering stats and data limits -----
+// ----- Tethering Error Counters -----
+
+DEFINE_BPF_MAP_GRW(tether_error_map, ARRAY, uint32_t, uint32_t, BPF_TETHER_ERR__MAX,
+ AID_NETWORK_STACK)
+
+#define COUNT_AND_RETURN(counter, ret) do { \
+ uint32_t code = BPF_TETHER_ERR_ ## counter; \
+ uint32_t *count = bpf_tether_error_map_lookup_elem(&code); \
+ if (count) __sync_fetch_and_add(count, 1); \
+ return ret; \
+} while(0)
+
+#define TC_DROP(counter) COUNT_AND_RETURN(counter, TC_ACT_SHOT)
+#define TC_PUNT(counter) COUNT_AND_RETURN(counter, TC_ACT_OK)
+
+#define XDP_DROP(counter) COUNT_AND_RETURN(counter, XDP_DROP)
+#define XDP_PUNT(counter) COUNT_AND_RETURN(counter, XDP_PASS)
+
+// ----- Tethering Data Stats and Limits -----
// Tethering stats, indexed by upstream interface.
DEFINE_BPF_MAP_GRW(tether_stats_map, HASH, TetherStatsKey, TetherStatsValue, 16, AID_NETWORK_STACK)
@@ -83,24 +100,11 @@
AID_NETWORK_STACK)
DEFINE_BPF_MAP_GRW(tether_downstream64_map, HASH, TetherDownstream64Key, TetherDownstream64Value,
- 64, AID_NETWORK_STACK)
+ 1024, AID_NETWORK_STACK)
DEFINE_BPF_MAP_GRW(tether_upstream6_map, HASH, TetherUpstream6Key, Tether6Value, 64,
AID_NETWORK_STACK)
-DEFINE_BPF_MAP_GRW(tether_error_map, ARRAY, __u32, __u32, BPF_TETHER_ERR__MAX,
- AID_NETWORK_STACK)
-
-#define COUNT_AND_RETURN(counter, ret) do { \
- __u32 code = BPF_TETHER_ERR_ ## counter; \
- __u32 *count = bpf_tether_error_map_lookup_elem(&code); \
- if (count) __sync_fetch_and_add(count, 1); \
- return ret; \
-} while(0)
-
-#define DROP(counter) COUNT_AND_RETURN(counter, TC_ACT_SHOT)
-#define PUNT(counter) COUNT_AND_RETURN(counter, TC_ACT_OK)
-
static inline __always_inline int do_forward6(struct __sk_buff* skb, const bool is_ethernet,
const bool downstream) {
const int l2_header_size = is_ethernet ? sizeof(struct ethhdr) : 0;
@@ -122,11 +126,11 @@
if (is_ethernet && (eth->h_proto != htons(ETH_P_IPV6))) return TC_ACT_OK;
// IP version must be 6
- if (ip6->version != 6) PUNT(INVALID_IP_VERSION);
+ if (ip6->version != 6) TC_PUNT(INVALID_IP_VERSION);
// Cannot decrement during forward if already zero or would be zero,
// Let the kernel's stack handle these cases and generate appropriate ICMP errors.
- if (ip6->hop_limit <= 1) PUNT(LOW_TTL);
+ if (ip6->hop_limit <= 1) TC_PUNT(LOW_TTL);
// If hardware offload is running and programming flows based on conntrack entries,
// try not to interfere with it.
@@ -135,27 +139,27 @@
// Make sure we can get at the tcp header
if (data + l2_header_size + sizeof(*ip6) + sizeof(*tcph) > data_end)
- PUNT(INVALID_TCP_HEADER);
+ TC_PUNT(INVALID_TCP_HEADER);
// Do not offload TCP packets with any one of the SYN/FIN/RST flags
- if (tcph->syn || tcph->fin || tcph->rst) PUNT(TCP_CONTROL_PACKET);
+ if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCP_CONTROL_PACKET);
}
// Protect against forwarding packets sourced from ::1 or fe80::/64 or other weirdness.
__be32 src32 = ip6->saddr.s6_addr32[0];
if (src32 != htonl(0x0064ff9b) && // 64:ff9b:/32 incl. XLAT464 WKP
(src32 & htonl(0xe0000000)) != htonl(0x20000000)) // 2000::/3 Global Unicast
- PUNT(NON_GLOBAL_SRC);
+ TC_PUNT(NON_GLOBAL_SRC);
// Protect against forwarding packets destined to ::1 or fe80::/64 or other weirdness.
__be32 dst32 = ip6->daddr.s6_addr32[0];
if (dst32 != htonl(0x0064ff9b) && // 64:ff9b:/32 incl. XLAT464 WKP
(dst32 & htonl(0xe0000000)) != htonl(0x20000000)) // 2000::/3 Global Unicast
- PUNT(NON_GLOBAL_DST);
+ TC_PUNT(NON_GLOBAL_DST);
// In the upstream direction do not forward traffic within the same /64 subnet.
if (!downstream && (src32 == dst32) && (ip6->saddr.s6_addr32[1] == ip6->daddr.s6_addr32[1]))
- PUNT(LOCAL_SRC_DST);
+ TC_PUNT(LOCAL_SRC_DST);
TetherDownstream6Key kd = {
.iif = skb->ifindex,
@@ -177,15 +181,15 @@
TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
// If we don't have anywhere to put stats, then abort...
- if (!stat_v) PUNT(NO_STATS_ENTRY);
+ if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
// If we don't have a limit, then abort...
- if (!limit_v) PUNT(NO_LIMIT_ENTRY);
+ if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
// Required IPv6 minimum mtu is 1280, below that not clear what we should do, abort...
- if (v->pmtu < IPV6_MIN_MTU) PUNT(BELOW_IPV6_MTU);
+ if (v->pmtu < IPV6_MIN_MTU) TC_PUNT(BELOW_IPV6_MTU);
// Approximate handling of TCP/IPv6 overhead for incoming LRO/GRO packets: default
// outbound path mtu of 1500 is not necessarily correct, but worst case we simply
@@ -210,7 +214,7 @@
// a packet we let the core stack deal with things.
// (The core stack needs to handle limits correctly anyway,
// since we don't offload all traffic in both directions)
- if (stat_v->rxBytes + stat_v->txBytes + bytes > *limit_v) PUNT(LIMIT_REACHED);
+ if (stat_v->rxBytes + stat_v->txBytes + bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
if (!is_ethernet) {
// Try to inject an ethernet header, and simply return if we fail.
@@ -218,7 +222,7 @@
// because this is easier and the kernel will strip extraneous ethernet header.
if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
__sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
- PUNT(CHANGE_HEAD_FAILED);
+ TC_PUNT(CHANGE_HEAD_FAILED);
}
// bpf_skb_change_head() invalidates all pointers - reload them
@@ -230,7 +234,7 @@
// I do not believe this can ever happen, but keep the verifier happy...
if (data + sizeof(struct ethhdr) + sizeof(*ip6) > data_end) {
__sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
- DROP(TOO_SHORT);
+ TC_DROP(TOO_SHORT);
}
};
@@ -336,9 +340,9 @@
// ----- IPv4 Support -----
-DEFINE_BPF_MAP_GRW(tether_downstream4_map, HASH, Tether4Key, Tether4Value, 64, AID_NETWORK_STACK)
+DEFINE_BPF_MAP_GRW(tether_downstream4_map, HASH, Tether4Key, Tether4Value, 1024, AID_NETWORK_STACK)
-DEFINE_BPF_MAP_GRW(tether_upstream4_map, HASH, Tether4Key, Tether4Value, 64, AID_NETWORK_STACK)
+DEFINE_BPF_MAP_GRW(tether_upstream4_map, HASH, Tether4Key, Tether4Value, 1024, AID_NETWORK_STACK)
static inline __always_inline int do_forward4(struct __sk_buff* skb, const bool is_ethernet,
const bool downstream, const bool updatetime) {
@@ -361,10 +365,10 @@
if (is_ethernet && (eth->h_proto != htons(ETH_P_IP))) return TC_ACT_OK;
// IP version must be 4
- if (ip->version != 4) PUNT(INVALID_IP_VERSION);
+ if (ip->version != 4) TC_PUNT(INVALID_IP_VERSION);
// We cannot handle IP options, just standard 20 byte == 5 dword minimal IPv4 header
- if (ip->ihl != 5) PUNT(HAS_IP_OPTIONS);
+ if (ip->ihl != 5) TC_PUNT(HAS_IP_OPTIONS);
// Calculate the IPv4 one's complement checksum of the IPv4 header.
__wsum sum4 = 0;
@@ -375,47 +379,91 @@
sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse u32 into range 1 .. 0x1FFFE
sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse any potential carry into u16
// for a correct checksum we should get *a* zero, but sum4 must be positive, ie 0xFFFF
- if (sum4 != 0xFFFF) PUNT(CHECKSUM);
+ if (sum4 != 0xFFFF) TC_PUNT(CHECKSUM);
// Minimum IPv4 total length is the size of the header
- if (ntohs(ip->tot_len) < sizeof(*ip)) PUNT(TRUNCATED_IPV4);
+ if (ntohs(ip->tot_len) < sizeof(*ip)) TC_PUNT(TRUNCATED_IPV4);
// We are incapable of dealing with IPv4 fragments
- if (ip->frag_off & ~htons(IP_DF)) PUNT(IS_IP_FRAG);
+ if (ip->frag_off & ~htons(IP_DF)) TC_PUNT(IS_IP_FRAG);
// Cannot decrement during forward if already zero or would be zero,
// Let the kernel's stack handle these cases and generate appropriate ICMP errors.
- if (ip->ttl <= 1) PUNT(LOW_TTL);
+ if (ip->ttl <= 1) TC_PUNT(LOW_TTL);
// If we cannot update the 'last_used' field due to lack of bpf_ktime_get_boot_ns() helper,
// then it is not safe to offload UDP due to the small conntrack timeouts, as such,
// in such a situation we can only support TCP. This also has the added nice benefit of
// using a separate error counter, and thus making it obvious which version of the program
// is loaded.
- if (!updatetime && ip->protocol != IPPROTO_TCP) PUNT(NON_TCP);
+ if (!updatetime && ip->protocol != IPPROTO_TCP) TC_PUNT(NON_TCP);
// We do not support offloading anything besides IPv4 TCP and UDP, due to need for NAT,
// but no need to check this if !updatetime due to check immediately above.
if (updatetime && (ip->protocol != IPPROTO_TCP) && (ip->protocol != IPPROTO_UDP))
- PUNT(NON_TCP_UDP);
+ TC_PUNT(NON_TCP_UDP);
// We want to make sure that the compiler will, in the !updatetime case, entirely optimize
// out all the non-tcp logic. Also note that at this point is_udp === !is_tcp.
const bool is_tcp = !updatetime || (ip->protocol == IPPROTO_TCP);
+ // This is a bit of a hack to make things easier on the bpf verifier.
+ // (In particular I believe the Linux 4.14 kernel's verifier can get confused later on about
+ // what offsets into the packet are valid and can spuriously reject the program, this is
+ // because it fails to realize that is_tcp && !is_tcp is impossible)
+ //
+ // For both TCP & UDP we'll need to read and modify the src/dst ports, which so happen to
+ // always be in the first 4 bytes of the L4 header. Additionally for UDP we'll need access
+ // to the checksum field which is in bytes 7 and 8. While for TCP we'll need to read the
+ // TCP flags (at offset 13) and access to the checksum field (2 bytes at offset 16).
+ // As such we *always* need access to at least 8 bytes.
+ if (data + l2_header_size + sizeof(*ip) + 8 > data_end) TC_PUNT(SHORT_L4_HEADER);
+
struct tcphdr* tcph = is_tcp ? (void*)(ip + 1) : NULL;
struct udphdr* udph = is_tcp ? NULL : (void*)(ip + 1);
if (is_tcp) {
// Make sure we can get at the tcp header
- if (data + l2_header_size + sizeof(*ip) + sizeof(*tcph) > data_end) PUNT(SHORT_TCP_HEADER);
+ if (data + l2_header_size + sizeof(*ip) + sizeof(*tcph) > data_end)
+ TC_PUNT(SHORT_TCP_HEADER);
// If hardware offload is running and programming flows based on conntrack entries, try not
// to interfere with it, so do not offload TCP packets with any one of the SYN/FIN/RST flags
- if (tcph->syn || tcph->fin || tcph->rst) PUNT(TCP_CONTROL_PACKET);
+ if (tcph->syn || tcph->fin || tcph->rst) TC_PUNT(TCP_CONTROL_PACKET);
} else { // UDP
// Make sure we can get at the udp header
- if (data + l2_header_size + sizeof(*ip) + sizeof(*udph) > data_end) PUNT(SHORT_UDP_HEADER);
+ if (data + l2_header_size + sizeof(*ip) + sizeof(*udph) > data_end)
+ TC_PUNT(SHORT_UDP_HEADER);
+
+ // Skip handling of CHECKSUM_COMPLETE packets with udp checksum zero due to need for
+ // additional updating of skb->csum (this could be fixed up manually with more effort).
+ //
+ // Note that the in-kernel implementation of 'int64_t bpf_csum_update(skb, u32 csum)' is:
+ // if (skb->ip_summed == CHECKSUM_COMPLETE)
+ // return (skb->csum = csum_add(skb->csum, csum));
+ // else
+ // return -ENOTSUPP;
+ //
+ // So this will punt any CHECKSUM_COMPLETE packet with a zero UDP checksum,
+ // and leave all other packets unaffected (since it just at most adds zero to skb->csum).
+ //
+ // In practice this should almost never trigger because most nics do not generate
+ // CHECKSUM_COMPLETE packets on receive - especially so for nics/drivers on a phone.
+ //
+ // Additionally since we're forwarding, in most cases the value of the skb->csum field
+ // shouldn't matter (it's not used by physical nic egress).
+ //
+ // It only matters if we're ingressing through a CHECKSUM_COMPLETE capable nic
+ // and egressing through a virtual interface looping back to the kernel itself
+ // (ie. something like veth) where the CHECKSUM_COMPLETE/skb->csum can get reused
+ // on ingress.
+ //
+ // If we were in the kernel we'd simply probably call
+ // void skb_checksum_complete_unset(struct sk_buff *skb) {
+ // if (skb->ip_summed == CHECKSUM_COMPLETE) skb->ip_summed = CHECKSUM_NONE;
+ // }
+ // here instead. Perhaps there should be a bpf helper for that?
+ if (!udph->check && (bpf_csum_update(skb, 0) >= 0)) TC_PUNT(UDP_CSUM_ZERO);
}
Tether4Key k = {
@@ -439,15 +487,15 @@
TetherStatsValue* stat_v = bpf_tether_stats_map_lookup_elem(&stat_and_limit_k);
// If we don't have anywhere to put stats, then abort...
- if (!stat_v) PUNT(NO_STATS_ENTRY);
+ if (!stat_v) TC_PUNT(NO_STATS_ENTRY);
uint64_t* limit_v = bpf_tether_limit_map_lookup_elem(&stat_and_limit_k);
// If we don't have a limit, then abort...
- if (!limit_v) PUNT(NO_LIMIT_ENTRY);
+ if (!limit_v) TC_PUNT(NO_LIMIT_ENTRY);
// Required IPv4 minimum mtu is 68, below that not clear what we should do, abort...
- if (v->pmtu < 68) PUNT(BELOW_IPV4_MTU);
+ if (v->pmtu < 68) TC_PUNT(BELOW_IPV4_MTU);
// Approximate handling of TCP/IPv4 overhead for incoming LRO/GRO packets: default
// outbound path mtu of 1500 is not necessarily correct, but worst case we simply
@@ -472,9 +520,7 @@
// a packet we let the core stack deal with things.
// (The core stack needs to handle limits correctly anyway,
// since we don't offload all traffic in both directions)
- if (stat_v->rxBytes + stat_v->txBytes + bytes > *limit_v) PUNT(LIMIT_REACHED);
-
- if (!is_tcp) PUNT(NON_TCP); // TEMP HACK: will remove once UDP is supported.
+ if (stat_v->rxBytes + stat_v->txBytes + bytes > *limit_v) TC_PUNT(LIMIT_REACHED);
if (!is_ethernet) {
// Try to inject an ethernet header, and simply return if we fail.
@@ -482,7 +528,7 @@
// because this is easier and the kernel will strip extraneous ethernet header.
if (bpf_skb_change_head(skb, sizeof(struct ethhdr), /*flags*/ 0)) {
__sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
- PUNT(CHANGE_HEAD_FAILED);
+ TC_PUNT(CHANGE_HEAD_FAILED);
}
// bpf_skb_change_head() invalidates all pointers - reload them
@@ -496,7 +542,7 @@
// I do not believe this can ever happen, but keep the verifier happy...
if (data + sizeof(struct ethhdr) + sizeof(*ip) + (is_tcp ? sizeof(*tcph) : sizeof(*udph)) > data_end) {
__sync_fetch_and_add(downstream ? &stat_v->rxErrors : &stat_v->txErrors, 1);
- DROP(TOO_SHORT);
+ TC_DROP(TOO_SHORT);
}
};
@@ -508,26 +554,33 @@
// For a rawip tx interface it will simply be a bunch of zeroes and later stripped.
*eth = v->macHeader;
+ const int l4_offs_csum = is_tcp ? ETH_IP4_TCP_OFFSET(check) : ETH_IP4_UDP_OFFSET(check);
const int sz4 = sizeof(__be32);
+ // UDP 0 is special and stored as FFFF (this flag also causes a csum of 0 to be unmodified)
+ const int l4_flags = is_tcp ? 0 : BPF_F_MARK_MANGLED_0;
const __be32 old_daddr = k.dst4.s_addr;
const __be32 old_saddr = k.src4.s_addr;
const __be32 new_daddr = v->dst46.s6_addr32[3];
const __be32 new_saddr = v->src46.s6_addr32[3];
- bpf_l4_csum_replace(skb, ETH_IP4_TCP_OFFSET(check), old_daddr, new_daddr, sz4 | BPF_F_PSEUDO_HDR);
+ bpf_l4_csum_replace(skb, l4_offs_csum, old_daddr, new_daddr, sz4 | BPF_F_PSEUDO_HDR | l4_flags);
bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_daddr, new_daddr, sz4);
bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(daddr), &new_daddr, sz4, 0);
- bpf_l4_csum_replace(skb, ETH_IP4_TCP_OFFSET(check), old_saddr, new_saddr, sz4 | BPF_F_PSEUDO_HDR);
+ bpf_l4_csum_replace(skb, l4_offs_csum, old_saddr, new_saddr, sz4 | BPF_F_PSEUDO_HDR | l4_flags);
bpf_l3_csum_replace(skb, ETH_IP4_OFFSET(check), old_saddr, new_saddr, sz4);
bpf_skb_store_bytes(skb, ETH_IP4_OFFSET(saddr), &new_saddr, sz4, 0);
const int sz2 = sizeof(__be16);
- bpf_l4_csum_replace(skb, ETH_IP4_TCP_OFFSET(check), k.srcPort, v->srcPort, sz2);
- bpf_skb_store_bytes(skb, ETH_IP4_TCP_OFFSET(source), &v->srcPort, sz2, 0);
+ // The offsets for TCP and UDP ports: source (u16 @ L4 offset 0) & dest (u16 @ L4 offset 2) are
+ // actually the same, so the compiler should just optimize them both down to a constant.
+ bpf_l4_csum_replace(skb, l4_offs_csum, k.srcPort, v->srcPort, sz2 | l4_flags);
+ bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(source) : ETH_IP4_UDP_OFFSET(source),
+ &v->srcPort, sz2, 0);
- bpf_l4_csum_replace(skb, ETH_IP4_TCP_OFFSET(check), k.dstPort, v->dstPort, sz2);
- bpf_skb_store_bytes(skb, ETH_IP4_TCP_OFFSET(dest), &v->dstPort, sz2, 0);
+ bpf_l4_csum_replace(skb, l4_offs_csum, k.dstPort, v->dstPort, sz2 | l4_flags);
+ bpf_skb_store_bytes(skb, is_tcp ? ETH_IP4_TCP_OFFSET(dest) : ETH_IP4_UDP_OFFSET(dest),
+ &v->dstPort, sz2, 0);
// TEMP HACK: lack of TTL decrement
@@ -694,4 +747,4 @@
}
LICENSE("Apache 2.0");
-CRITICAL("netd");
+CRITICAL("tethering");
diff --git a/Tethering/bpf_progs/test.c b/Tethering/bpf_progs/test.c
index c4a8271..3f0df2e 100644
--- a/Tethering/bpf_progs/test.c
+++ b/Tethering/bpf_progs/test.c
@@ -20,7 +20,7 @@
#include "bpf_helpers.h"
#include "bpf_net_helpers.h"
-#include "netdbpf/bpf_shared.h"
+#include "bpf_tethering.h"
// Used only by TetheringPrivilegedTests, not by production code.
DEFINE_BPF_MAP_GRW(tether_downstream6_map, HASH, TetherDownstream6Key, Tether6Value, 16,
diff --git a/Tethering/common/TetheringLib/Android.bp b/Tethering/common/TetheringLib/Android.bp
index a10729d..2631d08 100644
--- a/Tethering/common/TetheringLib/Android.bp
+++ b/Tethering/common/TetheringLib/Android.bp
@@ -13,6 +13,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
java_sdk_library {
name: "framework-tethering",
defaults: ["framework-module-defaults"],
diff --git a/Tethering/src/com/android/networkstack/tethering/BpfMap.java b/Tethering/src/com/android/networkstack/tethering/BpfMap.java
index 9a9376f..e9b4ccf 100644
--- a/Tethering/src/com/android/networkstack/tethering/BpfMap.java
+++ b/Tethering/src/com/android/networkstack/tethering/BpfMap.java
@@ -226,6 +226,20 @@
closeMap(mMapFd);
}
+ /**
+ * Clears the map. The map may already be empty.
+ *
+ * @throws ErrnoException if the map is already closed, if an error occurred during iteration,
+ * or if a non-ENOENT error occurred when deleting a key.
+ */
+ public void clear() throws ErrnoException {
+ K key = getFirstKey();
+ while (key != null) {
+ deleteEntry(key); // ignores ENOENT.
+ key = getFirstKey();
+ }
+ }
+
private static native int closeMap(int fd) throws ErrnoException;
private native int bpfFdGet(String path, int mode) throws ErrnoException, NullPointerException;
diff --git a/Tethering/src/com/android/networkstack/tethering/Tethering.java b/Tethering/src/com/android/networkstack/tethering/Tethering.java
index 385c691..ac5857d 100644
--- a/Tethering/src/com/android/networkstack/tethering/Tethering.java
+++ b/Tethering/src/com/android/networkstack/tethering/Tethering.java
@@ -1689,12 +1689,14 @@
// If this is a Wi-Fi interface, tell WifiManager of any errors
// or the inactive serving state.
if (who.interfaceType() == TETHERING_WIFI) {
- if (who.lastError() != TETHER_ERROR_NO_ERROR) {
- getWifiManager().updateInterfaceIpState(
- who.interfaceName(), IFACE_IP_MODE_CONFIGURATION_ERROR);
+ final WifiManager mgr = getWifiManager();
+ final String iface = who.interfaceName();
+ if (mgr == null) {
+ Log.wtf(TAG, "Skipping WifiManager notification about inactive tethering");
+ } else if (who.lastError() != TETHER_ERROR_NO_ERROR) {
+ mgr.updateInterfaceIpState(iface, IFACE_IP_MODE_CONFIGURATION_ERROR);
} else {
- getWifiManager().updateInterfaceIpState(
- who.interfaceName(), IFACE_IP_MODE_UNSPECIFIED);
+ mgr.updateInterfaceIpState(iface, IFACE_IP_MODE_UNSPECIFIED);
}
}
}
@@ -2421,6 +2423,19 @@
mLog.log(iface + " is not a tetherable iface, ignoring");
return;
}
+
+ final PackageManager pm = mContext.getPackageManager();
+ if ((interfaceType == TETHERING_WIFI || interfaceType == TETHERING_WIGIG)
+ && !pm.hasSystemFeature(PackageManager.FEATURE_WIFI)) {
+ mLog.log(iface + " is not tetherable, because WiFi feature is disabled");
+ return;
+ }
+ if (interfaceType == TETHERING_WIFI_P2P
+ && !pm.hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT)) {
+ mLog.log(iface + " is not tetherable, because WiFi Direct feature is disabled");
+ return;
+ }
+
maybeTrackNewInterfaceLocked(iface, interfaceType);
}
diff --git a/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java b/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java
index 799637c..413b0cb 100644
--- a/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java
+++ b/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java
@@ -33,6 +33,8 @@
import android.text.TextUtils;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.modules.utils.build.SdkLevel;
+import com.android.net.module.util.DeviceConfigUtils;
import java.io.PrintWriter;
import java.util.ArrayList;
@@ -94,6 +96,20 @@
"tether_enable_select_all_prefix_ranges";
/**
+ * Experiment flag to force choosing upstreams automatically.
+ *
+ * This setting is intended to help force-enable the feature on OEM devices that disabled it
+ * via resource overlays, and later noticed issues. To that end, it overrides
+ * config_tether_upstream_automatic when set to true.
+ *
+ * This flag is enabled if !=0 and less than the module APK version: see
+ * {@link DeviceConfigUtils#isFeatureEnabled}. It is also ignored after R, as later devices
+ * should just set config_tether_upstream_automatic to true instead.
+ */
+ public static final String TETHER_FORCE_UPSTREAM_AUTOMATIC_VERSION =
+ "tether_force_upstream_automatic_version";
+
+ /**
* Default value that used to periodic polls tether offload stats from tethering offload HAL
* to make the data warnings work.
*/
@@ -146,7 +162,9 @@
isDunRequired = checkDunRequired(ctx);
- chooseUpstreamAutomatically = getResourceBoolean(
+ final boolean forceAutomaticUpstream = !SdkLevel.isAtLeastS()
+ && isFeatureEnabled(ctx, TETHER_FORCE_UPSTREAM_AUTOMATIC_VERSION);
+ chooseUpstreamAutomatically = forceAutomaticUpstream || getResourceBoolean(
res, R.bool.config_tether_upstream_automatic, false /** defaultValue */);
preferredUpstreamIfaceTypes = getUpstreamIfaceTypes(res, isDunRequired);
@@ -453,6 +471,11 @@
return DeviceConfig.getProperty(NAMESPACE_CONNECTIVITY, name);
}
+ @VisibleForTesting
+ protected boolean isFeatureEnabled(Context ctx, String featureVersionFlag) {
+ return DeviceConfigUtils.isFeatureEnabled(ctx, NAMESPACE_CONNECTIVITY, featureVersionFlag);
+ }
+
private Resources getResources(Context ctx, int subId) {
if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
return getResourcesForSubIdWrapper(ctx, subId);
diff --git a/Tethering/tests/Android.bp b/Tethering/tests/Android.bp
index 731144c..8f31c57 100644
--- a/Tethering/tests/Android.bp
+++ b/Tethering/tests/Android.bp
@@ -14,6 +14,10 @@
// limitations under the License.
//
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
filegroup {
name: "TetheringTestsJarJarRules",
srcs: ["jarjar-rules.txt"],
diff --git a/Tethering/tests/integration/Android.bp b/Tethering/tests/integration/Android.bp
index f456273..f63df2c 100644
--- a/Tethering/tests/integration/Android.bp
+++ b/Tethering/tests/integration/Android.bp
@@ -13,6 +13,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
java_defaults {
name: "TetheringIntegrationTestsDefaults",
srcs: [
diff --git a/Tethering/tests/mts/Android.bp b/Tethering/tests/mts/Android.bp
index f925b0a..20a5f18 100644
--- a/Tethering/tests/mts/Android.bp
+++ b/Tethering/tests/mts/Android.bp
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
android_test {
// This tests for functionality that is not required for devices that
// don't use Tethering mainline module.
diff --git a/Tethering/tests/privileged/Android.bp b/Tethering/tests/privileged/Android.bp
index 9217345..75fdd6e 100644
--- a/Tethering/tests/privileged/Android.bp
+++ b/Tethering/tests/privileged/Android.bp
@@ -14,6 +14,10 @@
// limitations under the License.
//
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
java_defaults {
name: "TetheringPrivilegedTestsJniDefaults",
jni_libs: [
diff --git a/Tethering/tests/privileged/src/com/android/networkstack/tethering/BpfMapTest.java b/Tethering/tests/privileged/src/com/android/networkstack/tethering/BpfMapTest.java
index cceaa8c..62302c3 100644
--- a/Tethering/tests/privileged/src/com/android/networkstack/tethering/BpfMapTest.java
+++ b/Tethering/tests/privileged/src/com/android/networkstack/tethering/BpfMapTest.java
@@ -312,6 +312,32 @@
}
@Test
+ public void testClear() throws Exception {
+ // Clear an empty map.
+ assertTrue(mTestMap.isEmpty());
+ mTestMap.clear();
+
+ // Clear a map with some data in it.
+ final ArrayMap<TetherDownstream6Key, Tether6Value> resultMap =
+ new ArrayMap<>(mTestData);
+ for (int i = 0; i < resultMap.size(); i++) {
+ mTestMap.insertEntry(resultMap.keyAt(i), resultMap.valueAt(i));
+ }
+ assertFalse(mTestMap.isEmpty());
+ mTestMap.clear();
+ assertTrue(mTestMap.isEmpty());
+
+ // Clearing an already-closed map throws.
+ mTestMap.close();
+ try {
+ mTestMap.clear();
+ fail("clearing already-closed map should throw");
+ } catch (ErrnoException expected) {
+ assertEquals(OsConstants.EBADF, expected.errno);
+ }
+ }
+
+ @Test
public void testInsertOverflow() throws Exception {
final ArrayMap<TetherDownstream6Key, Tether6Value> testData =
new ArrayMap<>();
diff --git a/Tethering/tests/unit/Android.bp b/Tethering/tests/unit/Android.bp
index 6c479a0..d469b37 100644
--- a/Tethering/tests/unit/Android.bp
+++ b/Tethering/tests/unit/Android.bp
@@ -15,6 +15,10 @@
//
// Tests in this folder are included both in unit tests and CTS.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
java_library {
name: "TetheringCommonTests",
srcs: [
diff --git a/Tethering/tests/unit/src/com/android/networkstack/tethering/EntitlementManagerTest.java b/Tethering/tests/unit/src/com/android/networkstack/tethering/EntitlementManagerTest.java
index 354e753..8cfa7d0 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/EntitlementManagerTest.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/EntitlementManagerTest.java
@@ -53,6 +53,8 @@
import android.content.Context;
import android.content.Intent;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.util.SharedLog;
import android.os.Bundle;
@@ -87,11 +89,13 @@
private static final String[] PROVISIONING_APP_NAME = {"some", "app"};
private static final String PROVISIONING_NO_UI_APP_NAME = "no_ui_app";
private static final String PROVISIONING_APP_RESPONSE = "app_response";
+ private static final String TEST_PACKAGE_NAME = "com.android.tethering.test";
@Mock private CarrierConfigManager mCarrierConfigManager;
@Mock private Context mContext;
@Mock private Resources mResources;
@Mock private SharedLog mLog;
+ @Mock private PackageManager mPm;
@Mock private EntitlementManager.OnUiEntitlementFailedListener mEntitlementFailedListener;
// Like so many Android system APIs, these cannot be mocked because it is marked final.
@@ -182,7 +186,7 @@
}
@Before
- public void setUp() {
+ public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mMockingSession = mockitoSession()
.initMocks(this)
@@ -196,6 +200,9 @@
eq(EntitlementManager.DISABLE_PROVISIONING_SYSPROP_KEY), anyBoolean()));
doReturn(null).when(
() -> DeviceConfig.getProperty(eq(NAMESPACE_CONNECTIVITY), anyString()));
+ doReturn(mPm).when(mContext).getPackageManager();
+ doReturn(TEST_PACKAGE_NAME).when(mContext).getPackageName();
+ doReturn(new PackageInfo()).when(mPm).getPackageInfo(anyString(), anyInt());
when(mResources.getStringArray(R.array.config_tether_dhcp_range))
.thenReturn(new String[0]);
diff --git a/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringConfigurationTest.java b/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringConfigurationTest.java
index 237e2c2..1f4e371 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringConfigurationTest.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringConfigurationTest.java
@@ -30,12 +30,16 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import android.content.Context;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.util.SharedLog;
+import android.os.Build;
import android.provider.DeviceConfig;
import android.telephony.TelephonyManager;
@@ -43,9 +47,14 @@
import androidx.test.runner.AndroidJUnit4;
import com.android.internal.util.test.BroadcastInterceptingContext;
+import com.android.net.module.util.DeviceConfigUtils;
+import com.android.testutils.DevSdkIgnoreRule;
+import com.android.testutils.DevSdkIgnoreRule.IgnoreAfter;
+import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
import org.junit.After;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -60,13 +69,18 @@
public class TetheringConfigurationTest {
private final SharedLog mLog = new SharedLog("TetheringConfigurationTest");
+ @Rule public final DevSdkIgnoreRule mIgnoreRule = new DevSdkIgnoreRule();
+
private static final String[] PROVISIONING_APP_NAME = {"some", "app"};
private static final String PROVISIONING_NO_UI_APP_NAME = "no_ui_app";
private static final String PROVISIONING_APP_RESPONSE = "app_response";
+ private static final String TEST_PACKAGE_NAME = "com.android.tethering.test";
+ private static final long TEST_PACKAGE_VERSION = 1234L;
@Mock private Context mContext;
@Mock private TelephonyManager mTelephonyManager;
@Mock private Resources mResources;
@Mock private Resources mResourcesForSubId;
+ @Mock private PackageManager mPackageManager;
private Context mMockContext;
private boolean mHasTelephonyManager;
private boolean mEnableLegacyDhcpServer;
@@ -100,6 +114,16 @@
}
return super.getSystemService(name);
}
+
+ @Override
+ public PackageManager getPackageManager() {
+ return mPackageManager;
+ }
+
+ @Override
+ public String getPackageName() {
+ return TEST_PACKAGE_NAME;
+ }
}
@Before
@@ -110,9 +134,15 @@
.mockStatic(DeviceConfig.class)
.strictness(Strictness.WARN)
.startMocking();
+ DeviceConfigUtils.resetPackageVersionCacheForTest();
doReturn(null).when(
() -> DeviceConfig.getProperty(eq(NAMESPACE_CONNECTIVITY),
eq(TetheringConfiguration.TETHER_ENABLE_LEGACY_DHCP_SERVER)));
+ setTetherForceUpstreamAutomaticFlagVersion(null);
+
+ final PackageInfo pi = new PackageInfo();
+ pi.setLongVersionCode(TEST_PACKAGE_VERSION);
+ doReturn(pi).when(mPackageManager).getPackageInfo(eq(TEST_PACKAGE_NAME), anyInt());
when(mResources.getStringArray(R.array.config_tether_dhcp_range)).thenReturn(
new String[0]);
@@ -141,6 +171,7 @@
@After
public void tearDown() throws Exception {
mMockingSession.finishMocking();
+ DeviceConfigUtils.resetPackageVersionCacheForTest();
}
private TetheringConfiguration getTetheringConfiguration(int... legacyTetherUpstreamTypes) {
@@ -455,4 +486,52 @@
mMockContext, mLog, INVALID_SUBSCRIPTION_ID);
assertTrue(testEnable.isSelectAllPrefixRangeEnabled());
}
+
+ @Test
+ public void testChooseUpstreamAutomatically() throws Exception {
+ when(mResources.getBoolean(R.bool.config_tether_upstream_automatic))
+ .thenReturn(true);
+ assertChooseUpstreamAutomaticallyIs(true);
+
+ when(mResources.getBoolean(R.bool.config_tether_upstream_automatic))
+ .thenReturn(false);
+ assertChooseUpstreamAutomaticallyIs(false);
+ }
+
+ // The flag override only works on R-
+ @Test @IgnoreAfter(Build.VERSION_CODES.R)
+ public void testChooseUpstreamAutomatically_FlagOverride() throws Exception {
+ when(mResources.getBoolean(R.bool.config_tether_upstream_automatic))
+ .thenReturn(false);
+ setTetherForceUpstreamAutomaticFlagVersion(TEST_PACKAGE_VERSION - 1);
+ assertTrue(DeviceConfigUtils.isFeatureEnabled(mMockContext, NAMESPACE_CONNECTIVITY,
+ TetheringConfiguration.TETHER_FORCE_UPSTREAM_AUTOMATIC_VERSION));
+
+ assertChooseUpstreamAutomaticallyIs(true);
+
+ setTetherForceUpstreamAutomaticFlagVersion(0L);
+ assertChooseUpstreamAutomaticallyIs(false);
+
+ setTetherForceUpstreamAutomaticFlagVersion(Long.MAX_VALUE);
+ assertChooseUpstreamAutomaticallyIs(false);
+ }
+
+ @Test @IgnoreUpTo(Build.VERSION_CODES.R)
+ public void testChooseUpstreamAutomatically_FlagOverrideAfterR() throws Exception {
+ when(mResources.getBoolean(R.bool.config_tether_upstream_automatic))
+ .thenReturn(false);
+ setTetherForceUpstreamAutomaticFlagVersion(TEST_PACKAGE_VERSION - 1);
+ assertChooseUpstreamAutomaticallyIs(false);
+ }
+
+ private void setTetherForceUpstreamAutomaticFlagVersion(Long version) {
+ doReturn(version == null ? null : Long.toString(version)).when(
+ () -> DeviceConfig.getProperty(eq(NAMESPACE_CONNECTIVITY),
+ eq(TetheringConfiguration.TETHER_FORCE_UPSTREAM_AUTOMATIC_VERSION)));
+ }
+
+ private void assertChooseUpstreamAutomaticallyIs(boolean value) {
+ assertEquals(value, new TetheringConfiguration(mMockContext, mLog, INVALID_SUBSCRIPTION_ID)
+ .chooseUpstreamAutomatically);
+ }
}
diff --git a/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java b/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java
index f4b3749..c5a43b7 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java
@@ -358,6 +358,11 @@
}
@Override
+ protected boolean isFeatureEnabled(Context ctx, String featureVersionFlag) {
+ return false;
+ }
+
+ @Override
protected Resources getResourcesForSubIdWrapper(Context ctx, int subId) {
return mResources;
}
@@ -586,6 +591,9 @@
ArgumentCaptor.forClass(SoftApCallback.class);
verify(mWifiManager).registerSoftApCallback(any(), softApCallbackCaptor.capture());
mSoftApCallback = softApCallbackCaptor.getValue();
+
+ when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_WIFI)).thenReturn(true);
+ when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT)).thenReturn(true);
}
private void setTetheringSupported(final boolean supported) {
diff --git a/tests/cts/hostside/Android.bp b/tests/cts/hostside/Android.bp
index 47b114b..3185f7e 100644
--- a/tests/cts/hostside/Android.bp
+++ b/tests/cts/hostside/Android.bp
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
java_test_host {
name: "CtsHostsideNetworkTests",
defaults: ["cts_defaults"],
diff --git a/tests/cts/hostside/TEST_MAPPING b/tests/cts/hostside/TEST_MAPPING
new file mode 100644
index 0000000..02d2d6e
--- /dev/null
+++ b/tests/cts/hostside/TEST_MAPPING
@@ -0,0 +1,18 @@
+{
+ "presubmit": [
+ {
+ "name": "CtsHostsideNetworkTests",
+ "options": [
+ {
+ "include-filter": "com.android.cts.net.HostsideRestrictBackgroundNetworkTests"
+ },
+ {
+ "exclude-annotation": "androidx.test.filters.FlakyTest"
+ },
+ {
+ "exclude-annotation": "android.platform.test.annotations.FlakyTest"
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/tests/cts/hostside/aidl/Android.bp b/tests/cts/hostside/aidl/Android.bp
index 320a1fa..2751f6f 100644
--- a/tests/cts/hostside/aidl/Android.bp
+++ b/tests/cts/hostside/aidl/Android.bp
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
java_test_helper_library {
name: "CtsHostsideNetworkTestsAidl",
sdk_version: "current",
diff --git a/tests/cts/hostside/app/Android.bp b/tests/cts/hostside/app/Android.bp
index 5fb28e2..f351b47 100644
--- a/tests/cts/hostside/app/Android.bp
+++ b/tests/cts/hostside/app/Android.bp
@@ -14,6 +14,10 @@
// limitations under the License.
//
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
android_test_helper_app {
name: "CtsHostsideNetworkTestsApp",
defaults: ["cts_support_defaults"],
diff --git a/tests/cts/hostside/app2/Android.bp b/tests/cts/hostside/app2/Android.bp
index 8e27931..b448459 100644
--- a/tests/cts/hostside/app2/Android.bp
+++ b/tests/cts/hostside/app2/Android.bp
@@ -14,6 +14,10 @@
// limitations under the License.
//
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
android_test_helper_app {
name: "CtsHostsideNetworkTestsApp2",
defaults: ["cts_support_defaults"],
diff --git a/tests/cts/hostside/certs/Android.bp b/tests/cts/hostside/certs/Android.bp
index ab4cf34..60b5476 100644
--- a/tests/cts/hostside/certs/Android.bp
+++ b/tests/cts/hostside/certs/Android.bp
@@ -1,3 +1,7 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
android_app_certificate {
name: "cts-net-app",
certificate: "cts-net-app",
diff --git a/tests/cts/net/Android.bp b/tests/cts/net/Android.bp
index 528171a..bbfb2c1 100644
--- a/tests/cts/net/Android.bp
+++ b/tests/cts/net/Android.bp
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
java_defaults {
name: "CtsNetTestCasesDefaults",
defaults: ["cts_defaults"],
@@ -37,6 +41,7 @@
],
jarjar_rules: "jarjar-rules-shared.txt",
static_libs: [
+ "bouncycastle-unbundled",
"FrameworksNetCommonTests",
"TestNetworkStackLib",
"core-tests-support",
@@ -44,6 +49,7 @@
"ctstestrunner-axt",
"junit",
"junit-params",
+ "modules-utils-build",
"net-utils-framework-common",
"truth-prebuilt",
],
diff --git a/tests/cts/net/api23Test/Android.bp b/tests/cts/net/api23Test/Android.bp
index e43a5e8..5b37294 100644
--- a/tests/cts/net/api23Test/Android.bp
+++ b/tests/cts/net/api23Test/Android.bp
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
android_test {
name: "CtsNetApi23TestCases",
defaults: ["cts_defaults"],
diff --git a/tests/cts/net/appForApi23/Android.bp b/tests/cts/net/appForApi23/Android.bp
index cec6d7f..b39690f 100644
--- a/tests/cts/net/appForApi23/Android.bp
+++ b/tests/cts/net/appForApi23/Android.bp
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
android_test {
name: "CtsNetTestAppForApi23",
defaults: ["cts_defaults"],
diff --git a/tests/cts/net/jni/Android.bp b/tests/cts/net/jni/Android.bp
index 3953aeb..13f38d7 100644
--- a/tests/cts/net/jni/Android.bp
+++ b/tests/cts/net/jni/Android.bp
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
cc_library_shared {
name: "libnativedns_jni",
diff --git a/tests/cts/net/native/dns/Android.bp b/tests/cts/net/native/dns/Android.bp
index 6defd35..1bc5a86 100644
--- a/tests/cts/net/native/dns/Android.bp
+++ b/tests/cts/net/native/dns/Android.bp
@@ -1,3 +1,7 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
cc_defaults {
name: "dns_async_defaults",
diff --git a/tests/cts/net/native/qtaguid/Android.bp b/tests/cts/net/native/qtaguid/Android.bp
index 4861651..68bb14d 100644
--- a/tests/cts/net/native/qtaguid/Android.bp
+++ b/tests/cts/net/native/qtaguid/Android.bp
@@ -14,6 +14,10 @@
// Build the unit tests.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
cc_test {
name: "CtsNativeNetTestCases",
diff --git a/tests/cts/net/src/android/net/cts/CaptivePortalTest.kt b/tests/cts/net/src/android/net/cts/CaptivePortalTest.kt
index eb5048f..a889c41 100644
--- a/tests/cts/net/src/android/net/cts/CaptivePortalTest.kt
+++ b/tests/cts/net/src/android/net/cts/CaptivePortalTest.kt
@@ -26,6 +26,9 @@
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL
+import android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET
+import android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED
+import android.net.NetworkCapabilities.TRANSPORT_CELLULAR
import android.net.NetworkCapabilities.TRANSPORT_WIFI
import android.net.NetworkRequest
import android.net.Uri
@@ -44,8 +47,10 @@
import android.text.TextUtils
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.runner.AndroidJUnit4
+import com.android.testutils.RecorderCallback
import com.android.testutils.TestHttpServer
import com.android.testutils.TestHttpServer.Request
+import com.android.testutils.TestableNetworkCallback
import com.android.testutils.isDevSdkInRange
import com.android.testutils.runAsShell
import fi.iki.elonen.NanoHTTPD.Response.Status
@@ -124,7 +129,20 @@
assumeTrue(pm.hasSystemFeature(FEATURE_TELEPHONY))
assumeTrue(pm.hasSystemFeature(FEATURE_WIFI))
utils.ensureWifiConnected()
- utils.connectToCell()
+ val cellNetwork = utils.connectToCell()
+
+ // Verify cell network is validated
+ val cellReq = NetworkRequest.Builder()
+ .addTransportType(TRANSPORT_CELLULAR)
+ .addCapability(NET_CAPABILITY_INTERNET)
+ .build()
+ val cellCb = TestableNetworkCallback(timeoutMs = TEST_TIMEOUT_MS)
+ cm.registerNetworkCallback(cellReq, cellCb)
+ val cb = cellCb.eventuallyExpectOrNull<RecorderCallback.CallbackEntry.CapabilitiesChanged> {
+ it.network == cellNetwork && it.caps.hasCapability(NET_CAPABILITY_VALIDATED)
+ }
+ assertNotNull(cb, "Mobile network $cellNetwork has no access to the internet. " +
+ "Check the mobile data connection.")
// Have network validation use a local server that serves a HTTPS error / HTTP redirect
server.addResponse(Request(TEST_PORTAL_URL_PATH), Status.OK,
@@ -135,7 +153,8 @@
setHttpsUrlDeviceConfig(makeUrl(TEST_HTTPS_URL_PATH))
setHttpUrlDeviceConfig(makeUrl(TEST_HTTP_URL_PATH))
// URL expiration needs to be in the next 10 minutes
- setUrlExpirationDeviceConfig(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(9))
+ assertTrue(WIFI_CONNECT_TIMEOUT_MS < TimeUnit.MINUTES.toMillis(10))
+ setUrlExpirationDeviceConfig(System.currentTimeMillis() + WIFI_CONNECT_TIMEOUT_MS)
// Wait for a captive portal to be detected on the network
val wifiNetworkFuture = CompletableFuture<Network>()
diff --git a/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
index 0b5bd42..fad688b 100644
--- a/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -576,17 +576,23 @@
// Create a ConnectivityActionReceiver that has an IntentFilter for our locally defined
// action, NETWORK_CALLBACK_ACTION.
- IntentFilter filter = new IntentFilter();
+ final IntentFilter filter = new IntentFilter();
filter.addAction(NETWORK_CALLBACK_ACTION);
- ConnectivityActionReceiver receiver = new ConnectivityActionReceiver(
+ final ConnectivityActionReceiver receiver = new ConnectivityActionReceiver(
mCm, ConnectivityManager.TYPE_WIFI, NetworkInfo.State.CONNECTED);
mContext.registerReceiver(receiver, filter);
// Create a broadcast PendingIntent for NETWORK_CALLBACK_ACTION.
- Intent intent = new Intent(NETWORK_CALLBACK_ACTION);
- PendingIntent pendingIntent = PendingIntent.getBroadcast(
- mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
+ final Intent intent = new Intent(NETWORK_CALLBACK_ACTION)
+ .setPackage(mContext.getPackageName());
+ // While ConnectivityService would put extra info such as network or request id before
+ // broadcasting the inner intent. The MUTABLE flag needs to be added accordingly.
+ // TODO: replace with PendingIntent.FLAG_MUTABLE when this code compiles against S+ or
+ // shims.
+ final int pendingIntentFlagMutable = 1 << 25;
+ final PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0 /*requestCode*/,
+ intent, PendingIntent.FLAG_CANCEL_CURRENT | pendingIntentFlagMutable);
// We will register for a WIFI network being available or lost.
mCm.registerNetworkCallback(makeWifiNetworkRequest(), pendingIntent);
@@ -1572,11 +1578,12 @@
public void testRequestBackgroundNetwork() throws Exception {
// Create a tun interface. Use the returned interface name as the specifier to create
// a test network request.
- final TestNetworkInterface testNetworkInterface = runWithShellPermissionIdentity(() -> {
- final TestNetworkManager tnm =
- mContext.getSystemService(TestNetworkManager.class);
- return tnm.createTunInterface(new LinkAddress[]{TEST_LINKADDR});
- }, android.Manifest.permission.MANAGE_TEST_NETWORKS,
+ final TestNetworkManager tnm = runWithShellPermissionIdentity(() ->
+ mContext.getSystemService(TestNetworkManager.class),
+ android.Manifest.permission.MANAGE_TEST_NETWORKS);
+ final TestNetworkInterface testNetworkInterface = runWithShellPermissionIdentity(() ->
+ tnm.createTunInterface(new LinkAddress[]{TEST_LINKADDR}),
+ android.Manifest.permission.MANAGE_TEST_NETWORKS,
android.Manifest.permission.NETWORK_SETTINGS);
assertNotNull(testNetworkInterface);
@@ -1594,24 +1601,23 @@
assertThrows(SecurityException.class,
() -> mCm.requestBackgroundNetwork(testRequest, null, callback));
+ Network testNetwork = null;
try {
// Request background test network via Shell identity which has NETWORK_SETTINGS
// permission granted.
runWithShellPermissionIdentity(
() -> mCm.requestBackgroundNetwork(testRequest, null, callback),
- android.Manifest.permission.NETWORK_SETTINGS);
+ new String[] { android.Manifest.permission.NETWORK_SETTINGS });
// Register the test network agent which has no foreground request associated to it.
// And verify it can satisfy the background network request just fired.
final Binder binder = new Binder();
- runWithShellPermissionIdentity(() -> {
- final TestNetworkManager tnm =
- mContext.getSystemService(TestNetworkManager.class);
- tnm.setupTestNetwork(testNetworkInterface.getInterfaceName(), binder);
- }, android.Manifest.permission.MANAGE_TEST_NETWORKS,
- android.Manifest.permission.NETWORK_SETTINGS);
+ runWithShellPermissionIdentity(() ->
+ tnm.setupTestNetwork(testNetworkInterface.getInterfaceName(), binder),
+ new String[] { android.Manifest.permission.MANAGE_TEST_NETWORKS,
+ android.Manifest.permission.NETWORK_SETTINGS });
waitForAvailable(callback);
- final Network testNetwork = callback.getLastAvailableNetwork();
+ testNetwork = callback.getLastAvailableNetwork();
assertNotNull(testNetwork);
// The test network that has just connected is a foreground network,
@@ -1627,6 +1633,16 @@
assertFalse("expected background network, but got " + nc,
nc.hasCapability(NET_CAPABILITY_FOREGROUND));
} finally {
+ final Network n = testNetwork;
+ runWithShellPermissionIdentity(() -> {
+ if (null != n) {
+ tnm.teardownTestNetwork(n);
+ callback.eventuallyExpect(CallbackEntry.LOST,
+ NETWORK_CALLBACK_TIMEOUT_MS,
+ lost -> n.equals(lost.getNetwork()));
+ }
+ testNetworkInterface.getFileDescriptor().close();
+ }, new String[] { android.Manifest.permission.MANAGE_TEST_NETWORKS });
mCm.unregisterNetworkCallback(callback);
}
}
diff --git a/tests/cts/net/src/android/net/cts/Ikev2VpnTest.java b/tests/cts/net/src/android/net/cts/Ikev2VpnTest.java
index 8f2d93d..c6d8d65 100644
--- a/tests/cts/net/src/android/net/cts/Ikev2VpnTest.java
+++ b/tests/cts/net/src/android/net/cts/Ikev2VpnTest.java
@@ -55,10 +55,10 @@
import androidx.test.InstrumentationRegistry;
import com.android.internal.util.HexDump;
-import com.android.internal.org.bouncycastle.x509.X509V1CertificateGenerator;
import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
import com.android.testutils.DevSdkIgnoreRunner;
+import org.bouncycastle.x509.X509V1CertificateGenerator;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
diff --git a/tests/cts/net/src/android/net/cts/NetworkAgentTest.kt b/tests/cts/net/src/android/net/cts/NetworkAgentTest.kt
index aea33ca..1046b50 100644
--- a/tests/cts/net/src/android/net/cts/NetworkAgentTest.kt
+++ b/tests/cts/net/src/android/net/cts/NetworkAgentTest.kt
@@ -35,6 +35,7 @@
import android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED
import android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING
import android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
+import android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED
import android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN
import android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED
import android.net.NetworkCapabilities.NET_CAPABILITY_TRUSTED
@@ -67,6 +68,7 @@
import androidx.test.InstrumentationRegistry
import com.android.connectivity.aidl.INetworkAgent
import com.android.connectivity.aidl.INetworkAgentRegistry
+import com.android.modules.utils.build.SdkLevel
import com.android.net.module.util.ArrayTrackRecord
import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
import com.android.testutils.DevSdkIgnoreRunner
@@ -321,6 +323,9 @@
addCapability(NET_CAPABILITY_NOT_SUSPENDED)
addCapability(NET_CAPABILITY_NOT_ROAMING)
addCapability(NET_CAPABILITY_NOT_VPN)
+ if (SdkLevel.isAtLeastS()) {
+ addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
+ }
if (null != name) {
setNetworkSpecifier(StringNetworkSpecifier(name))
}
@@ -558,6 +563,9 @@
addTransportType(TRANSPORT_VPN)
removeCapability(NET_CAPABILITY_NOT_VPN)
setTransportInfo(VpnTransportInfo(VpnManager.TYPE_VPN_SERVICE))
+ if (SdkLevel.isAtLeastS()) {
+ addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
+ }
}
val defaultNetwork = mCM.activeNetwork
assertNotNull(defaultNetwork)
diff --git a/tests/cts/net/src/android/net/cts/NetworkRequestTest.java b/tests/cts/net/src/android/net/cts/NetworkRequestTest.java
index d118c8a..31dc64d 100644
--- a/tests/cts/net/src/android/net/cts/NetworkRequestTest.java
+++ b/tests/cts/net/src/android/net/cts/NetworkRequestTest.java
@@ -16,8 +16,13 @@
package android.net.cts;
+import static android.net.NetworkCapabilities.NET_CAPABILITY_DUN;
+import static android.net.NetworkCapabilities.NET_CAPABILITY_FOTA;
import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
import static android.net.NetworkCapabilities.NET_CAPABILITY_MMS;
+import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
+import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
+import static android.net.NetworkCapabilities.NET_CAPABILITY_SUPL;
import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
import static android.net.NetworkCapabilities.TRANSPORT_BLUETOOTH;
import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
@@ -29,6 +34,7 @@
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import android.annotation.NonNull;
import android.net.MacAddress;
import android.net.MatchAllNetworkSpecifier;
import android.net.NetworkCapabilities;
@@ -43,6 +49,7 @@
import androidx.test.runner.AndroidJUnit4;
+import com.android.modules.utils.build.SdkLevel;
import com.android.testutils.DevSdkIgnoreRule;
import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
@@ -152,29 +159,44 @@
.getRequestorPackageName());
}
+ private void addNotVcnManagedCapability(@NonNull NetworkCapabilities nc) {
+ if (SdkLevel.isAtLeastS()) {
+ nc.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
+ }
+ }
+
@Test
@IgnoreUpTo(Build.VERSION_CODES.Q)
public void testCanBeSatisfiedBy() {
final LocalNetworkSpecifier specifier1 = new LocalNetworkSpecifier(1234 /* id */);
final LocalNetworkSpecifier specifier2 = new LocalNetworkSpecifier(5678 /* id */);
+ // Some requests are adding NOT_VCN_MANAGED capability automatically. Add it to the
+ // capabilities below for bypassing the check.
final NetworkCapabilities capCellularMmsInternet = new NetworkCapabilities()
.addTransportType(TRANSPORT_CELLULAR)
.addCapability(NET_CAPABILITY_MMS)
.addCapability(NET_CAPABILITY_INTERNET);
+ addNotVcnManagedCapability(capCellularMmsInternet);
final NetworkCapabilities capCellularVpnMmsInternet =
new NetworkCapabilities(capCellularMmsInternet).addTransportType(TRANSPORT_VPN);
+ addNotVcnManagedCapability(capCellularVpnMmsInternet);
final NetworkCapabilities capCellularMmsInternetSpecifier1 =
new NetworkCapabilities(capCellularMmsInternet).setNetworkSpecifier(specifier1);
+ addNotVcnManagedCapability(capCellularMmsInternetSpecifier1);
final NetworkCapabilities capVpnInternetSpecifier1 = new NetworkCapabilities()
.addCapability(NET_CAPABILITY_INTERNET)
.addTransportType(TRANSPORT_VPN)
.setNetworkSpecifier(specifier1);
+ addNotVcnManagedCapability(capVpnInternetSpecifier1);
final NetworkCapabilities capCellularMmsInternetMatchallspecifier =
new NetworkCapabilities(capCellularMmsInternet)
- .setNetworkSpecifier(new MatchAllNetworkSpecifier());
+ .setNetworkSpecifier(new MatchAllNetworkSpecifier());
+ addNotVcnManagedCapability(capCellularMmsInternetMatchallspecifier);
final NetworkCapabilities capCellularMmsInternetSpecifier2 =
- new NetworkCapabilities(capCellularMmsInternet).setNetworkSpecifier(specifier2);
+ new NetworkCapabilities(capCellularMmsInternet)
+ .setNetworkSpecifier(specifier2);
+ addNotVcnManagedCapability(capCellularMmsInternetSpecifier2);
final NetworkRequest requestCellularInternetSpecifier1 = new NetworkRequest.Builder()
.addTransportType(TRANSPORT_CELLULAR)
@@ -239,7 +261,8 @@
final NetworkCapabilities capCellInternetBWSpecifier1Signal =
new NetworkCapabilities.Builder(capCellInternetBWSpecifier1)
- .setSignalStrength(-123).build();
+ .setSignalStrength(-123).build();
+ addNotVcnManagedCapability(capCellInternetBWSpecifier1Signal);
assertCorrectlySatisfies(true, requestCombination,
capCellInternetBWSpecifier1Signal);
@@ -273,4 +296,75 @@
assertEquals(Process.INVALID_UID, new NetworkRequest.Builder()
.clearCapabilities().build().getRequestorUid());
}
+
+ // TODO: 1. Refactor test cases with helper method.
+ // 2. Test capability that does not yet exist.
+ @Test @IgnoreUpTo(Build.VERSION_CODES.R)
+ public void testBypassingVcnForNonInternetRequest() {
+ // Make an empty request. Verify the NOT_VCN_MANAGED is added.
+ final NetworkRequest emptyRequest = new NetworkRequest.Builder().build();
+ assertTrue(emptyRequest.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED));
+
+ // Make a request explicitly add NOT_VCN_MANAGED. Verify the NOT_VCN_MANAGED is preserved.
+ final NetworkRequest mmsAddNotVcnRequest = new NetworkRequest.Builder()
+ .addCapability(NET_CAPABILITY_MMS)
+ .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
+ .build();
+ assertTrue(mmsAddNotVcnRequest.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED));
+
+ // Similar to above, but the opposite order.
+ final NetworkRequest mmsAddNotVcnRequest2 = new NetworkRequest.Builder()
+ .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
+ .addCapability(NET_CAPABILITY_MMS)
+ .build();
+ assertTrue(mmsAddNotVcnRequest2.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED));
+
+ // Make a request explicitly remove NOT_VCN_MANAGED. Verify the NOT_VCN_MANAGED is removed.
+ final NetworkRequest removeNotVcnRequest = new NetworkRequest.Builder()
+ .removeCapability(NET_CAPABILITY_NOT_VCN_MANAGED).build();
+ assertFalse(removeNotVcnRequest.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED));
+
+ // Make a request add some capability inside VCN supported capabilities.
+ // Verify the NOT_VCN_MANAGED is added.
+ final NetworkRequest notRoamRequest = new NetworkRequest.Builder()
+ .addCapability(NET_CAPABILITY_NOT_ROAMING).build();
+ assertTrue(notRoamRequest.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED));
+
+ // Make a internet request. Verify the NOT_VCN_MANAGED is added.
+ final NetworkRequest internetRequest = new NetworkRequest.Builder()
+ .addCapability(NET_CAPABILITY_INTERNET).build();
+ assertTrue(internetRequest.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED));
+
+ // Make a internet request which explicitly removed NOT_VCN_MANAGED.
+ // Verify the NOT_VCN_MANAGED is removed.
+ final NetworkRequest internetRemoveNotVcnRequest = new NetworkRequest.Builder()
+ .addCapability(NET_CAPABILITY_INTERNET)
+ .removeCapability(NET_CAPABILITY_NOT_VCN_MANAGED).build();
+ assertFalse(internetRemoveNotVcnRequest.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED));
+
+ // Make a normal MMS request. Verify the request could bypass VCN.
+ final NetworkRequest mmsRequest =
+ new NetworkRequest.Builder().addCapability(NET_CAPABILITY_MMS).build();
+ assertFalse(mmsRequest.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED));
+
+ // Make a SUPL request along with internet. Verify NOT_VCN_MANAGED is not added since
+ // SUPL is not in the supported list.
+ final NetworkRequest suplWithInternetRequest = new NetworkRequest.Builder()
+ .addCapability(NET_CAPABILITY_SUPL)
+ .addCapability(NET_CAPABILITY_INTERNET).build();
+ assertFalse(suplWithInternetRequest.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED));
+
+ // Make a FOTA request with explicitly add NOT_VCN_MANAGED capability. Verify
+ // NOT_VCN_MANAGED is preserved.
+ final NetworkRequest fotaRequest = new NetworkRequest.Builder()
+ .addCapability(NET_CAPABILITY_FOTA)
+ .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED).build();
+ assertTrue(fotaRequest.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED));
+
+ // Make a DUN request, which is in {@code VCN_SUPPORTED_CAPABILITIES}.
+ // Verify NOT_VCN_MANAGED is preserved.
+ final NetworkRequest dunRequest = new NetworkRequest.Builder()
+ .addCapability(NET_CAPABILITY_DUN).build();
+ assertTrue(dunRequest.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED));
+ }
}
diff --git a/tests/cts/net/util/Android.bp b/tests/cts/net/util/Android.bp
index c36d976..88a2068 100644
--- a/tests/cts/net/util/Android.bp
+++ b/tests/cts/net/util/Android.bp
@@ -15,6 +15,10 @@
//
// Common utilities for cts net tests.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
java_library {
name: "cts-net-utils",
srcs: ["java/**/*.java", "java/**/*.kt"],
@@ -23,4 +27,4 @@
"junit",
"net-tests-utils",
],
-}
\ No newline at end of file
+}
diff --git a/tests/cts/tethering/Android.bp b/tests/cts/tethering/Android.bp
index b1d4a60..824c874 100644
--- a/tests/cts/tethering/Android.bp
+++ b/tests/cts/tethering/Android.bp
@@ -12,6 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
android_test {
name: "CtsTetheringTest",
defaults: ["cts_defaults"],