Merge history of ConnectivityT

Renamed files/directories:
ConnectivityT/service/Android.bp --> service-t/Sources.bp
ConnectivityT/framework-t/Android.bp --> framework-t/Sources.bp
ConnectivityT/framework-t/aidl-export --> framework/aidl-export
ConnectivityT/service --> service-t
ConnectivityT/framework-t --> framework-t
ConnectivityT/tests --> tests
ConnectivityT/OWNERS --> (removed)

BUG: 222234190
TEST: TH
Merged-In: I1fe5091361c7766dc7b6b4fb8c7b62d403e950bb
Change-Id: Ib592434ff50c06e25894f6ed7d7e3e8e1e3ea67b
This commit is contained in:
Remi NGUYEN VAN 2022-03-24 14:19:13 +00:00
commit 3464805acc
85 changed files with 26565 additions and 0 deletions

205
framework-t/Sources.bp Normal file
View file

@ -0,0 +1,205 @@
//
// Copyright (C) 2021 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 {
// See: http://go/android-license-faq
default_applicable_licenses: ["Android-Apache-2.0"],
}
// NetworkStats related libraries.
filegroup {
name: "framework-connectivity-netstats-internal-sources",
srcs: [
"src/android/app/usage/*.java",
"src/android/net/DataUsageRequest.*",
"src/android/net/INetworkStatsService.aidl",
"src/android/net/INetworkStatsSession.aidl",
"src/android/net/NetworkIdentity.java",
"src/android/net/NetworkIdentitySet.java",
"src/android/net/NetworkStateSnapshot.*",
"src/android/net/NetworkStats.*",
"src/android/net/NetworkStatsAccess.*",
"src/android/net/NetworkStatsCollection.*",
"src/android/net/NetworkStatsHistory.*",
"src/android/net/NetworkTemplate.*",
"src/android/net/TrafficStats.java",
"src/android/net/UnderlyingNetworkInfo.*",
"src/android/net/netstats/**/*.*",
],
path: "src",
visibility: [
"//visibility:private",
],
}
filegroup {
name: "framework-connectivity-netstats-aidl-export-sources",
srcs: [
"aidl-export/android/net/NetworkStats.aidl",
"aidl-export/android/net/NetworkTemplate.aidl",
],
path: "aidl-export",
visibility: [
"//visibility:private",
],
}
filegroup {
name: "framework-connectivity-netstats-sources",
srcs: [
":framework-connectivity-netstats-internal-sources",
":framework-connectivity-netstats-aidl-export-sources",
],
visibility: [
"//visibility:private",
],
}
// Nsd related libraries.
filegroup {
name: "framework-connectivity-nsd-internal-sources",
srcs: [
"src/android/net/nsd/*.aidl",
"src/android/net/nsd/*.java",
],
path: "src",
visibility: [
"//visibility:private",
],
}
filegroup {
name: "framework-connectivity-nsd-aidl-export-sources",
srcs: [
"aidl-export/android/net/nsd/*.aidl",
],
path: "aidl-export",
visibility: [
"//visibility:private",
],
}
filegroup {
name: "framework-connectivity-nsd-sources",
srcs: [
":framework-connectivity-nsd-internal-sources",
":framework-connectivity-nsd-aidl-export-sources",
],
visibility: [
"//visibility:private",
],
}
// IpSec related libraries.
filegroup {
name: "framework-connectivity-ipsec-sources",
srcs: [
"src/android/net/IIpSecService.aidl",
"src/android/net/IpSec*.*",
],
path: "src",
visibility: [
"//visibility:private",
],
}
// Ethernet related libraries.
filegroup {
name: "framework-connectivity-ethernet-sources",
srcs: [
"src/android/net/EthernetManager.java",
"src/android/net/EthernetNetworkManagementException.java",
"src/android/net/EthernetNetworkManagementException.aidl",
"src/android/net/EthernetNetworkSpecifier.java",
"src/android/net/EthernetNetworkUpdateRequest.java",
"src/android/net/EthernetNetworkUpdateRequest.aidl",
"src/android/net/IEthernetManager.aidl",
"src/android/net/IEthernetServiceListener.aidl",
"src/android/net/INetworkInterfaceOutcomeReceiver.aidl",
"src/android/net/ITetheredInterfaceCallback.aidl",
],
path: "src",
visibility: [
"//visibility:private",
],
}
// Connectivity-T common libraries.
filegroup {
name: "framework-connectivity-tiramisu-internal-sources",
srcs: [
"src/android/net/ConnectivityFrameworkInitializerTiramisu.java",
],
path: "src",
visibility: [
"//visibility:private",
],
}
// TODO: remove this empty filegroup.
filegroup {
name: "framework-connectivity-tiramisu-sources",
srcs: [],
visibility: ["//frameworks/base"],
}
filegroup {
name: "framework-connectivity-tiramisu-updatable-sources",
srcs: [
":framework-connectivity-ethernet-sources",
":framework-connectivity-ipsec-sources",
":framework-connectivity-netstats-sources",
":framework-connectivity-nsd-sources",
":framework-connectivity-tiramisu-internal-sources",
],
visibility: [
"//frameworks/base",
"//packages/modules/Connectivity:__subpackages__",
],
}
cc_library_shared {
name: "libframework-connectivity-tiramisu-jni",
min_sdk_version: "30",
cflags: [
"-Wall",
"-Werror",
"-Wno-unused-parameter",
// Don't warn about S API usage even with
// min_sdk 30: the library is only loaded
// on S+ devices
"-Wno-unguarded-availability",
"-Wthread-safety",
],
srcs: [
"jni/android_net_TrafficStats.cpp",
"jni/onload.cpp",
],
shared_libs: [
"libandroid",
"liblog",
"libnativehelper",
],
stl: "none",
apex_available: [
"com.android.tethering",
],
}

View file

@ -0,0 +1,46 @@
/*
* Copyright (C) 2022 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.
*/
#include <android/file_descriptor_jni.h>
#include <android/multinetwork.h>
#include <nativehelper/JNIHelp.h>
namespace android {
static jint tagSocketFd(JNIEnv* env, jclass, jobject fileDescriptor, jint tag, jint uid) {
int fd = AFileDescriptor_getFd(env, fileDescriptor);
if (fd == -1) return -EBADF;
return android_tag_socket_with_uid(fd, tag, uid);
}
static jint untagSocketFd(JNIEnv* env, jclass, jobject fileDescriptor) {
int fd = AFileDescriptor_getFd(env, fileDescriptor);
if (fd == -1) return -EBADF;
return android_untag_socket(fd);
}
static const JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
{ "native_tagSocketFd", "(Ljava/io/FileDescriptor;II)I", (void*) tagSocketFd },
{ "native_untagSocketFd", "(Ljava/io/FileDescriptor;)I", (void*) untagSocketFd },
};
int register_android_net_TrafficStats(JNIEnv* env) {
return jniRegisterNativeMethods(env, "android/net/TrafficStats", gMethods, NELEM(gMethods));
}
}; // namespace android

View file

@ -0,0 +1,39 @@
/*
* Copyright (C) 2022 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.
*/
#define LOG_TAG "FrameworkConnectivityJNI"
#include <log/log.h>
#include <nativehelper/JNIHelp.h>
namespace android {
int register_android_net_TrafficStats(JNIEnv* env);
extern "C" jint JNI_OnLoad(JavaVM* vm, void*) {
JNIEnv *env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "ERROR: GetEnv failed");
return JNI_ERR;
}
if (register_android_net_TrafficStats(env) < 0) return JNI_ERR;
return JNI_VERSION_1_6;
}
}; // namespace android

View file

@ -0,0 +1,744 @@
/**
* 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.app.usage;
import android.annotation.IntDef;
import android.annotation.Nullable;
import android.content.Context;
import android.net.INetworkStatsService;
import android.net.INetworkStatsSession;
import android.net.NetworkStatsHistory;
import android.net.NetworkTemplate;
import android.net.TrafficStats;
import android.os.RemoteException;
import android.util.Log;
import com.android.net.module.util.CollectionUtils;
import dalvik.system.CloseGuard;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
/**
* Class providing enumeration over buckets of network usage statistics. {@link NetworkStats} objects
* are returned as results to various queries in {@link NetworkStatsManager}.
*/
public final class NetworkStats implements AutoCloseable {
private final static String TAG = "NetworkStats";
private final CloseGuard mCloseGuard = CloseGuard.get();
/**
* Start timestamp of stats collected
*/
private final long mStartTimeStamp;
/**
* End timestamp of stats collected
*/
private final long mEndTimeStamp;
/**
* Non-null array indicates the query enumerates over uids.
*/
private int[] mUids;
/**
* Index of the current uid in mUids when doing uid enumeration or a single uid value,
* depending on query type.
*/
private int mUidOrUidIndex;
/**
* Tag id in case if was specified in the query.
*/
private int mTag = android.net.NetworkStats.TAG_NONE;
/**
* State in case it was not specified in the query.
*/
private int mState = Bucket.STATE_ALL;
/**
* The session while the query requires it, null if all the stats have been collected or close()
* has been called.
*/
private INetworkStatsSession mSession;
private NetworkTemplate mTemplate;
/**
* Results of a summary query.
*/
private android.net.NetworkStats mSummary = null;
/**
* Results of detail queries.
*/
private NetworkStatsHistory mHistory = null;
/**
* Where we are in enumerating over the current result.
*/
private int mEnumerationIndex = 0;
/**
* Recycling entry objects to prevent heap fragmentation.
*/
private android.net.NetworkStats.Entry mRecycledSummaryEntry = null;
private NetworkStatsHistory.Entry mRecycledHistoryEntry = null;
/** @hide */
NetworkStats(Context context, NetworkTemplate template, int flags, long startTimestamp,
long endTimestamp, INetworkStatsService statsService)
throws RemoteException, SecurityException {
// Open network stats session
mSession = statsService.openSessionForUsageStats(flags, context.getOpPackageName());
mCloseGuard.open("close");
mTemplate = template;
mStartTimeStamp = startTimestamp;
mEndTimeStamp = endTimestamp;
}
@Override
protected void finalize() throws Throwable {
try {
if (mCloseGuard != null) {
mCloseGuard.warnIfOpen();
}
close();
} finally {
super.finalize();
}
}
// -------------------------BEGINNING OF PUBLIC API-----------------------------------
/**
* Buckets are the smallest elements of a query result. As some dimensions of a result may be
* aggregated (e.g. time or state) some values may be equal across all buckets.
*/
public static class Bucket {
/** @hide */
@IntDef(prefix = { "STATE_" }, value = {
STATE_ALL,
STATE_DEFAULT,
STATE_FOREGROUND
})
@Retention(RetentionPolicy.SOURCE)
public @interface State {}
/**
* Combined usage across all states.
*/
public static final int STATE_ALL = -1;
/**
* Usage not accounted for in any other state.
*/
public static final int STATE_DEFAULT = 0x1;
/**
* Foreground usage.
*/
public static final int STATE_FOREGROUND = 0x2;
/**
* Special UID value for aggregate/unspecified.
*/
public static final int UID_ALL = android.net.NetworkStats.UID_ALL;
/**
* Special UID value for removed apps.
*/
public static final int UID_REMOVED = TrafficStats.UID_REMOVED;
/**
* Special UID value for data usage by tethering.
*/
public static final int UID_TETHERING = TrafficStats.UID_TETHERING;
/** @hide */
@IntDef(prefix = { "METERED_" }, value = {
METERED_ALL,
METERED_NO,
METERED_YES
})
@Retention(RetentionPolicy.SOURCE)
public @interface Metered {}
/**
* Combined usage across all metered states. Covers metered and unmetered usage.
*/
public static final int METERED_ALL = -1;
/**
* Usage that occurs on an unmetered network.
*/
public static final int METERED_NO = 0x1;
/**
* Usage that occurs on a metered network.
*
* <p>A network is classified as metered when the user is sensitive to heavy data usage on
* that connection.
*/
public static final int METERED_YES = 0x2;
/** @hide */
@IntDef(prefix = { "ROAMING_" }, value = {
ROAMING_ALL,
ROAMING_NO,
ROAMING_YES
})
@Retention(RetentionPolicy.SOURCE)
public @interface Roaming {}
/**
* Combined usage across all roaming states. Covers both roaming and non-roaming usage.
*/
public static final int ROAMING_ALL = -1;
/**
* Usage that occurs on a home, non-roaming network.
*
* <p>Any cellular usage in this bucket was incurred while the device was connected to a
* tower owned or operated by the user's wireless carrier, or a tower that the user's
* wireless carrier has indicated should be treated as a home network regardless.
*
* <p>This is also the default value for network types that do not support roaming.
*/
public static final int ROAMING_NO = 0x1;
/**
* Usage that occurs on a roaming network.
*
* <p>Any cellular usage in this bucket as incurred while the device was roaming on another
* carrier's network, for which additional charges may apply.
*/
public static final int ROAMING_YES = 0x2;
/** @hide */
@IntDef(prefix = { "DEFAULT_NETWORK_" }, value = {
DEFAULT_NETWORK_ALL,
DEFAULT_NETWORK_NO,
DEFAULT_NETWORK_YES
})
@Retention(RetentionPolicy.SOURCE)
public @interface DefaultNetworkStatus {}
/**
* Combined usage for this network regardless of default network status.
*/
public static final int DEFAULT_NETWORK_ALL = -1;
/**
* Usage that occurs while this network is not a default network.
*
* <p>This implies that the app responsible for this usage requested that it occur on a
* specific network different from the one(s) the system would have selected for it.
*/
public static final int DEFAULT_NETWORK_NO = 0x1;
/**
* Usage that occurs while this network is a default network.
*
* <p>This implies that the app either did not select a specific network for this usage,
* or it selected a network that the system could have selected for app traffic.
*/
public static final int DEFAULT_NETWORK_YES = 0x2;
/**
* Special TAG value for total data across all tags
*/
public static final int TAG_NONE = android.net.NetworkStats.TAG_NONE;
private int mUid;
private int mTag;
private int mState;
private int mDefaultNetworkStatus;
private int mMetered;
private int mRoaming;
private long mBeginTimeStamp;
private long mEndTimeStamp;
private long mRxBytes;
private long mRxPackets;
private long mTxBytes;
private long mTxPackets;
private static int convertSet(@State int state) {
switch (state) {
case STATE_ALL: return android.net.NetworkStats.SET_ALL;
case STATE_DEFAULT: return android.net.NetworkStats.SET_DEFAULT;
case STATE_FOREGROUND: return android.net.NetworkStats.SET_FOREGROUND;
}
return 0;
}
private static @State int convertState(int networkStatsSet) {
switch (networkStatsSet) {
case android.net.NetworkStats.SET_ALL : return STATE_ALL;
case android.net.NetworkStats.SET_DEFAULT : return STATE_DEFAULT;
case android.net.NetworkStats.SET_FOREGROUND : return STATE_FOREGROUND;
}
return 0;
}
private static int convertUid(int uid) {
switch (uid) {
case TrafficStats.UID_REMOVED: return UID_REMOVED;
case TrafficStats.UID_TETHERING: return UID_TETHERING;
}
return uid;
}
private static int convertTag(int tag) {
switch (tag) {
case android.net.NetworkStats.TAG_NONE: return TAG_NONE;
}
return tag;
}
private static @Metered int convertMetered(int metered) {
switch (metered) {
case android.net.NetworkStats.METERED_ALL : return METERED_ALL;
case android.net.NetworkStats.METERED_NO: return METERED_NO;
case android.net.NetworkStats.METERED_YES: return METERED_YES;
}
return 0;
}
private static @Roaming int convertRoaming(int roaming) {
switch (roaming) {
case android.net.NetworkStats.ROAMING_ALL : return ROAMING_ALL;
case android.net.NetworkStats.ROAMING_NO: return ROAMING_NO;
case android.net.NetworkStats.ROAMING_YES: return ROAMING_YES;
}
return 0;
}
private static @DefaultNetworkStatus int convertDefaultNetworkStatus(
int defaultNetworkStatus) {
switch (defaultNetworkStatus) {
case android.net.NetworkStats.DEFAULT_NETWORK_ALL : return DEFAULT_NETWORK_ALL;
case android.net.NetworkStats.DEFAULT_NETWORK_NO: return DEFAULT_NETWORK_NO;
case android.net.NetworkStats.DEFAULT_NETWORK_YES: return DEFAULT_NETWORK_YES;
}
return 0;
}
public Bucket() {
}
/**
* Key of the bucket. Usually an app uid or one of the following special values:<p />
* <ul>
* <li>{@link #UID_REMOVED}</li>
* <li>{@link #UID_TETHERING}</li>
* <li>{@link android.os.Process#SYSTEM_UID}</li>
* </ul>
* @return Bucket key.
*/
public int getUid() {
return mUid;
}
/**
* Tag of the bucket.<p />
* @return Bucket tag.
*/
public int getTag() {
return mTag;
}
/**
* Usage state. One of the following values:<p/>
* <ul>
* <li>{@link #STATE_ALL}</li>
* <li>{@link #STATE_DEFAULT}</li>
* <li>{@link #STATE_FOREGROUND}</li>
* </ul>
* @return Usage state.
*/
public @State int getState() {
return mState;
}
/**
* Metered state. One of the following values:<p/>
* <ul>
* <li>{@link #METERED_ALL}</li>
* <li>{@link #METERED_NO}</li>
* <li>{@link #METERED_YES}</li>
* </ul>
* <p>A network is classified as metered when the user is sensitive to heavy data usage on
* that connection. Apps may warn before using these networks for large downloads. The
* metered state can be set by the user within data usage network restrictions.
*/
public @Metered int getMetered() {
return mMetered;
}
/**
* Roaming state. One of the following values:<p/>
* <ul>
* <li>{@link #ROAMING_ALL}</li>
* <li>{@link #ROAMING_NO}</li>
* <li>{@link #ROAMING_YES}</li>
* </ul>
*/
public @Roaming int getRoaming() {
return mRoaming;
}
/**
* Default network status. One of the following values:<p/>
* <ul>
* <li>{@link #DEFAULT_NETWORK_ALL}</li>
* <li>{@link #DEFAULT_NETWORK_NO}</li>
* <li>{@link #DEFAULT_NETWORK_YES}</li>
* </ul>
*/
public @DefaultNetworkStatus int getDefaultNetworkStatus() {
return mDefaultNetworkStatus;
}
/**
* Start timestamp of the bucket's time interval. Defined in terms of "Unix time", see
* {@link java.lang.System#currentTimeMillis}.
* @return Start of interval.
*/
public long getStartTimeStamp() {
return mBeginTimeStamp;
}
/**
* End timestamp of the bucket's time interval. Defined in terms of "Unix time", see
* {@link java.lang.System#currentTimeMillis}.
* @return End of interval.
*/
public long getEndTimeStamp() {
return mEndTimeStamp;
}
/**
* Number of bytes received during the bucket's time interval. Statistics are measured at
* the network layer, so they include both TCP and UDP usage.
* @return Number of bytes.
*/
public long getRxBytes() {
return mRxBytes;
}
/**
* Number of bytes transmitted during the bucket's time interval. Statistics are measured at
* the network layer, so they include both TCP and UDP usage.
* @return Number of bytes.
*/
public long getTxBytes() {
return mTxBytes;
}
/**
* Number of packets received during the bucket's time interval. Statistics are measured at
* the network layer, so they include both TCP and UDP usage.
* @return Number of packets.
*/
public long getRxPackets() {
return mRxPackets;
}
/**
* Number of packets transmitted during the bucket's time interval. Statistics are measured
* at the network layer, so they include both TCP and UDP usage.
* @return Number of packets.
*/
public long getTxPackets() {
return mTxPackets;
}
}
/**
* Fills the recycled bucket with data of the next bin in the enumeration.
* @param bucketOut Bucket to be filled with data. If null, the method does
* nothing and returning false.
* @return true if successfully filled the bucket, false otherwise.
*/
public boolean getNextBucket(@Nullable Bucket bucketOut) {
if (mSummary != null) {
return getNextSummaryBucket(bucketOut);
} else {
return getNextHistoryBucket(bucketOut);
}
}
/**
* Check if it is possible to ask for a next bucket in the enumeration.
* @return true if there is at least one more bucket.
*/
public boolean hasNextBucket() {
if (mSummary != null) {
return mEnumerationIndex < mSummary.size();
} else if (mHistory != null) {
return mEnumerationIndex < mHistory.size()
|| hasNextUid();
}
return false;
}
/**
* Closes the enumeration. Call this method before this object gets out of scope.
*/
@Override
public void close() {
if (mSession != null) {
try {
mSession.close();
} catch (RemoteException e) {
Log.w(TAG, e);
// Otherwise, meh
}
}
mSession = null;
if (mCloseGuard != null) {
mCloseGuard.close();
}
}
// -------------------------END OF PUBLIC API-----------------------------------
/**
* Collects device summary results into a Bucket.
* @throws RemoteException
*/
Bucket getDeviceSummaryForNetwork() throws RemoteException {
mSummary = mSession.getDeviceSummaryForNetwork(mTemplate, mStartTimeStamp, mEndTimeStamp);
// Setting enumeration index beyond end to avoid accidental enumeration over data that does
// not belong to the calling user.
mEnumerationIndex = mSummary.size();
return getSummaryAggregate();
}
/**
* Collects summary results and sets summary enumeration mode.
* @throws RemoteException
*/
void startSummaryEnumeration() throws RemoteException {
mSummary = mSession.getSummaryForAllUid(mTemplate, mStartTimeStamp, mEndTimeStamp,
false /* includeTags */);
mEnumerationIndex = 0;
}
/**
* Collects tagged summary results and sets summary enumeration mode.
* @throws RemoteException
*/
void startTaggedSummaryEnumeration() throws RemoteException {
mSummary = mSession.getTaggedSummaryForAllUid(mTemplate, mStartTimeStamp, mEndTimeStamp);
mEnumerationIndex = 0;
}
/**
* Collects history results for uid and resets history enumeration index.
*/
void startHistoryUidEnumeration(int uid, int tag, int state) {
mHistory = null;
try {
mHistory = mSession.getHistoryIntervalForUid(mTemplate, uid,
Bucket.convertSet(state), tag, NetworkStatsHistory.FIELD_ALL,
mStartTimeStamp, mEndTimeStamp);
setSingleUidTagState(uid, tag, state);
} catch (RemoteException e) {
Log.w(TAG, e);
// Leaving mHistory null
}
mEnumerationIndex = 0;
}
/**
* Collects history results for network and resets history enumeration index.
*/
void startHistoryDeviceEnumeration() {
try {
mHistory = mSession.getHistoryIntervalForNetwork(
mTemplate, NetworkStatsHistory.FIELD_ALL, mStartTimeStamp, mEndTimeStamp);
} catch (RemoteException e) {
Log.w(TAG, e);
mHistory = null;
}
mEnumerationIndex = 0;
}
/**
* Starts uid enumeration for current user.
* @throws RemoteException
*/
void startUserUidEnumeration() throws RemoteException {
// TODO: getRelevantUids should be sensitive to time interval. When that's done,
// the filtering logic below can be removed.
int[] uids = mSession.getRelevantUids();
// Filtering of uids with empty history.
final ArrayList<Integer> filteredUids = new ArrayList<>();
for (int uid : uids) {
try {
NetworkStatsHistory history = mSession.getHistoryIntervalForUid(mTemplate, uid,
android.net.NetworkStats.SET_ALL, android.net.NetworkStats.TAG_NONE,
NetworkStatsHistory.FIELD_ALL, mStartTimeStamp, mEndTimeStamp);
if (history != null && history.size() > 0) {
filteredUids.add(uid);
}
} catch (RemoteException e) {
Log.w(TAG, "Error while getting history of uid " + uid, e);
}
}
mUids = CollectionUtils.toIntArray(filteredUids);
mUidOrUidIndex = -1;
stepHistory();
}
/**
* Steps to next uid in enumeration and collects history for that.
*/
private void stepHistory(){
if (hasNextUid()) {
stepUid();
mHistory = null;
try {
mHistory = mSession.getHistoryIntervalForUid(mTemplate, getUid(),
android.net.NetworkStats.SET_ALL, android.net.NetworkStats.TAG_NONE,
NetworkStatsHistory.FIELD_ALL, mStartTimeStamp, mEndTimeStamp);
} catch (RemoteException e) {
Log.w(TAG, e);
// Leaving mHistory null
}
mEnumerationIndex = 0;
}
}
private void fillBucketFromSummaryEntry(Bucket bucketOut) {
bucketOut.mUid = Bucket.convertUid(mRecycledSummaryEntry.uid);
bucketOut.mTag = Bucket.convertTag(mRecycledSummaryEntry.tag);
bucketOut.mState = Bucket.convertState(mRecycledSummaryEntry.set);
bucketOut.mDefaultNetworkStatus = Bucket.convertDefaultNetworkStatus(
mRecycledSummaryEntry.defaultNetwork);
bucketOut.mMetered = Bucket.convertMetered(mRecycledSummaryEntry.metered);
bucketOut.mRoaming = Bucket.convertRoaming(mRecycledSummaryEntry.roaming);
bucketOut.mBeginTimeStamp = mStartTimeStamp;
bucketOut.mEndTimeStamp = mEndTimeStamp;
bucketOut.mRxBytes = mRecycledSummaryEntry.rxBytes;
bucketOut.mRxPackets = mRecycledSummaryEntry.rxPackets;
bucketOut.mTxBytes = mRecycledSummaryEntry.txBytes;
bucketOut.mTxPackets = mRecycledSummaryEntry.txPackets;
}
/**
* Getting the next item in summary enumeration.
* @param bucketOut Next item will be set here.
* @return true if a next item could be set.
*/
private boolean getNextSummaryBucket(@Nullable Bucket bucketOut) {
if (bucketOut != null && mEnumerationIndex < mSummary.size()) {
mRecycledSummaryEntry = mSummary.getValues(mEnumerationIndex++, mRecycledSummaryEntry);
fillBucketFromSummaryEntry(bucketOut);
return true;
}
return false;
}
Bucket getSummaryAggregate() {
if (mSummary == null) {
return null;
}
Bucket bucket = new Bucket();
if (mRecycledSummaryEntry == null) {
mRecycledSummaryEntry = new android.net.NetworkStats.Entry();
}
mSummary.getTotal(mRecycledSummaryEntry);
fillBucketFromSummaryEntry(bucket);
return bucket;
}
/**
* Getting the next item in a history enumeration.
* @param bucketOut Next item will be set here.
* @return true if a next item could be set.
*/
private boolean getNextHistoryBucket(@Nullable Bucket bucketOut) {
if (bucketOut != null && mHistory != null) {
if (mEnumerationIndex < mHistory.size()) {
mRecycledHistoryEntry = mHistory.getValues(mEnumerationIndex++,
mRecycledHistoryEntry);
bucketOut.mUid = Bucket.convertUid(getUid());
bucketOut.mTag = Bucket.convertTag(mTag);
bucketOut.mState = mState;
bucketOut.mDefaultNetworkStatus = Bucket.DEFAULT_NETWORK_ALL;
bucketOut.mMetered = Bucket.METERED_ALL;
bucketOut.mRoaming = Bucket.ROAMING_ALL;
bucketOut.mBeginTimeStamp = mRecycledHistoryEntry.bucketStart;
bucketOut.mEndTimeStamp = mRecycledHistoryEntry.bucketStart +
mRecycledHistoryEntry.bucketDuration;
bucketOut.mRxBytes = mRecycledHistoryEntry.rxBytes;
bucketOut.mRxPackets = mRecycledHistoryEntry.rxPackets;
bucketOut.mTxBytes = mRecycledHistoryEntry.txBytes;
bucketOut.mTxPackets = mRecycledHistoryEntry.txPackets;
return true;
} else if (hasNextUid()) {
stepHistory();
return getNextHistoryBucket(bucketOut);
}
}
return false;
}
// ------------------ UID LOGIC------------------------
private boolean isUidEnumeration() {
return mUids != null;
}
private boolean hasNextUid() {
return isUidEnumeration() && (mUidOrUidIndex + 1) < mUids.length;
}
private int getUid() {
// Check if uid enumeration.
if (isUidEnumeration()) {
if (mUidOrUidIndex < 0 || mUidOrUidIndex >= mUids.length) {
throw new IndexOutOfBoundsException(
"Index=" + mUidOrUidIndex + " mUids.length=" + mUids.length);
}
return mUids[mUidOrUidIndex];
}
// Single uid mode.
return mUidOrUidIndex;
}
private void setSingleUidTagState(int uid, int tag, int state) {
mUidOrUidIndex = uid;
mTag = tag;
mState = state;
}
private void stepUid() {
if (mUids != null) {
++mUidOrUidIndex;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,82 @@
/*
* Copyright (C) 2021 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.annotation.SystemApi;
import android.app.SystemServiceRegistry;
import android.app.usage.NetworkStatsManager;
import android.content.Context;
import android.net.nsd.INsdManager;
import android.net.nsd.NsdManager;
/**
* Class for performing registration for Connectivity services which are exposed via updatable APIs
* since Android T.
*
* @hide
*/
@SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
public final class ConnectivityFrameworkInitializerTiramisu {
private ConnectivityFrameworkInitializerTiramisu() {}
/**
* Called by {@link SystemServiceRegistry}'s static initializer and registers NetworkStats, nsd,
* ipsec and ethernet services to {@link Context}, so that {@link Context#getSystemService} can
* return them.
*
* @throws IllegalStateException if this is called anywhere besides
* {@link SystemServiceRegistry}.
*/
public static void registerServiceWrappers() {
SystemServiceRegistry.registerContextAwareService(
Context.NSD_SERVICE,
NsdManager.class,
(context, serviceBinder) -> {
INsdManager service = INsdManager.Stub.asInterface(serviceBinder);
return new NsdManager(context, service);
}
);
SystemServiceRegistry.registerContextAwareService(
Context.IPSEC_SERVICE,
IpSecManager.class,
(context, serviceBinder) -> {
IIpSecService service = IIpSecService.Stub.asInterface(serviceBinder);
return new IpSecManager(context, service);
}
);
SystemServiceRegistry.registerContextAwareService(
Context.NETWORK_STATS_SERVICE,
NetworkStatsManager.class,
(context, serviceBinder) -> {
INetworkStatsService service =
INetworkStatsService.Stub.asInterface(serviceBinder);
return new NetworkStatsManager(context, service);
}
);
SystemServiceRegistry.registerContextAwareService(
Context.ETHERNET_SERVICE,
EthernetManager.class,
(context, serviceBinder) -> {
IEthernetManager service = IEthernetManager.Stub.asInterface(serviceBinder);
return new EthernetManager(context, service);
}
);
}
}

View file

@ -0,0 +1,19 @@
/**
* Copyright (c) 2016, 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;
parcelable DataUsageRequest;

View file

@ -0,0 +1,112 @@
/**
* Copyright (C) 2016 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.annotation.Nullable;
import android.net.NetworkTemplate;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Objects;
/**
* Defines a request to register a callbacks. Used to be notified on data usage via
* {@link android.app.usage.NetworkStatsManager#registerDataUsageCallback}.
* If no {@code uid}s are set, callbacks are restricted to device-owners,
* carrier-privileged apps, or system apps.
*
* @hide
*/
public final class DataUsageRequest implements Parcelable {
public static final String PARCELABLE_KEY = "DataUsageRequest";
public static final int REQUEST_ID_UNSET = 0;
/**
* Identifies the request. {@link DataUsageRequest}s should only be constructed by
* the Framework and it is used internally to identify the request.
*/
public final int requestId;
/**
* {@link NetworkTemplate} describing the network to monitor.
*/
public final NetworkTemplate template;
/**
* Threshold in bytes to be notified on.
*/
public final long thresholdInBytes;
public DataUsageRequest(int requestId, NetworkTemplate template, long thresholdInBytes) {
this.requestId = requestId;
this.template = template;
this.thresholdInBytes = thresholdInBytes;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(requestId);
dest.writeParcelable(template, flags);
dest.writeLong(thresholdInBytes);
}
public static final @android.annotation.NonNull Creator<DataUsageRequest> CREATOR =
new Creator<DataUsageRequest>() {
@Override
public DataUsageRequest createFromParcel(Parcel in) {
int requestId = in.readInt();
NetworkTemplate template = in.readParcelable(null, android.net.NetworkTemplate.class);
long thresholdInBytes = in.readLong();
DataUsageRequest result = new DataUsageRequest(requestId, template,
thresholdInBytes);
return result;
}
@Override
public DataUsageRequest[] newArray(int size) {
return new DataUsageRequest[size];
}
};
@Override
public String toString() {
return "DataUsageRequest [ requestId=" + requestId
+ ", networkTemplate=" + template
+ ", thresholdInBytes=" + thresholdInBytes + " ]";
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof DataUsageRequest == false) return false;
DataUsageRequest that = (DataUsageRequest) obj;
return that.requestId == this.requestId
&& Objects.equals(that.template, this.template)
&& that.thresholdInBytes == this.thresholdInBytes;
}
@Override
public int hashCode() {
return Objects.hash(requestId, template, thresholdInBytes);
}
}

View file

@ -0,0 +1,729 @@
/*
* Copyright (C) 2014 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 static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
import android.annotation.CallbackExecutor;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresFeature;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.OutcomeReceiver;
import android.os.RemoteException;
import com.android.internal.annotations.GuardedBy;
import com.android.modules.utils.BackgroundThread;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.function.IntConsumer;
/**
* A class that manages and configures Ethernet interfaces.
*
* @hide
*/
@SystemApi
@SystemService(Context.ETHERNET_SERVICE)
public class EthernetManager {
private static final String TAG = "EthernetManager";
private final IEthernetManager mService;
@GuardedBy("mListenerLock")
private final ArrayList<ListenerInfo<InterfaceStateListener>> mIfaceListeners =
new ArrayList<>();
@GuardedBy("mListenerLock")
private final ArrayList<ListenerInfo<IntConsumer>> mEthernetStateListeners =
new ArrayList<>();
final Object mListenerLock = new Object();
private final IEthernetServiceListener.Stub mServiceListener =
new IEthernetServiceListener.Stub() {
@Override
public void onEthernetStateChanged(int state) {
synchronized (mListenerLock) {
for (ListenerInfo<IntConsumer> li : mEthernetStateListeners) {
li.executor.execute(() -> {
li.listener.accept(state);
});
}
}
}
@Override
public void onInterfaceStateChanged(String iface, int state, int role,
IpConfiguration configuration) {
synchronized (mListenerLock) {
for (ListenerInfo<InterfaceStateListener> li : mIfaceListeners) {
li.executor.execute(() ->
li.listener.onInterfaceStateChanged(iface, state, role,
configuration));
}
}
}
};
/**
* Indicates that Ethernet is disabled.
*
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
public static final int ETHERNET_STATE_DISABLED = 0;
/**
* Indicates that Ethernet is enabled.
*
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
public static final int ETHERNET_STATE_ENABLED = 1;
private static class ListenerInfo<T> {
@NonNull
public final Executor executor;
@NonNull
public final T listener;
private ListenerInfo(@NonNull Executor executor, @NonNull T listener) {
this.executor = executor;
this.listener = listener;
}
}
/**
* The interface is absent.
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
public static final int STATE_ABSENT = 0;
/**
* The interface is present but link is down.
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
public static final int STATE_LINK_DOWN = 1;
/**
* The interface is present and link is up.
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
public static final int STATE_LINK_UP = 2;
/** @hide */
@IntDef(prefix = "STATE_", value = {STATE_ABSENT, STATE_LINK_DOWN, STATE_LINK_UP})
@Retention(RetentionPolicy.SOURCE)
public @interface InterfaceState {}
/**
* The interface currently does not have any specific role.
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
public static final int ROLE_NONE = 0;
/**
* The interface is in client mode (e.g., connected to the Internet).
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
public static final int ROLE_CLIENT = 1;
/**
* Ethernet interface is in server mode (e.g., providing Internet access to tethered devices).
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
public static final int ROLE_SERVER = 2;
/** @hide */
@IntDef(prefix = "ROLE_", value = {ROLE_NONE, ROLE_CLIENT, ROLE_SERVER})
@Retention(RetentionPolicy.SOURCE)
public @interface Role {}
/**
* A listener that receives notifications about the state of Ethernet interfaces on the system.
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
public interface InterfaceStateListener {
/**
* Called when an Ethernet interface changes state.
*
* @param iface the name of the interface.
* @param state the current state of the interface, or {@link #STATE_ABSENT} if the
* interface was removed.
* @param role whether the interface is in client mode or server mode.
* @param configuration the current IP configuration of the interface.
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
void onInterfaceStateChanged(@NonNull String iface, @InterfaceState int state,
@Role int role, @Nullable IpConfiguration configuration);
}
/**
* A listener interface to receive notification on changes in Ethernet.
* This has never been a supported API. Use {@link InterfaceStateListener} instead.
* @hide
*/
public interface Listener extends InterfaceStateListener {
/**
* Called when Ethernet port's availability is changed.
* @param iface Ethernet interface name
* @param isAvailable {@code true} if Ethernet port exists.
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
void onAvailabilityChanged(String iface, boolean isAvailable);
/** Default implementation for backwards compatibility. Only calls the legacy listener. */
default void onInterfaceStateChanged(@NonNull String iface, @InterfaceState int state,
@Role int role, @Nullable IpConfiguration configuration) {
onAvailabilityChanged(iface, (state >= STATE_LINK_UP));
}
}
/**
* Create a new EthernetManager instance.
* Applications will almost always want to use
* {@link android.content.Context#getSystemService Context.getSystemService()} to retrieve
* the standard {@link android.content.Context#ETHERNET_SERVICE Context.ETHERNET_SERVICE}.
* @hide
*/
public EthernetManager(Context context, IEthernetManager service) {
mService = service;
}
/**
* Get Ethernet configuration.
* @return the Ethernet Configuration, contained in {@link IpConfiguration}.
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public IpConfiguration getConfiguration(String iface) {
try {
return mService.getConfiguration(iface);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Set Ethernet configuration.
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public void setConfiguration(@NonNull String iface, @NonNull IpConfiguration config) {
try {
mService.setConfiguration(iface, config);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Indicates whether the system currently has one or more Ethernet interfaces.
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public boolean isAvailable() {
return getAvailableInterfaces().length > 0;
}
/**
* Indicates whether the system has given interface.
*
* @param iface Ethernet interface name
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public boolean isAvailable(String iface) {
try {
return mService.isAvailable(iface);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Adds a listener.
* This has never been a supported API. Use {@link #addInterfaceStateListener} instead.
*
* @param listener A {@link Listener} to add.
* @throws IllegalArgumentException If the listener is null.
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public void addListener(@NonNull Listener listener) {
addListener(listener, BackgroundThread.getExecutor());
}
/**
* Adds a listener.
* This has never been a supported API. Use {@link #addInterfaceStateListener} instead.
*
* @param listener A {@link Listener} to add.
* @param executor Executor to run callbacks on.
* @throws IllegalArgumentException If the listener or executor is null.
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public void addListener(@NonNull Listener listener, @NonNull Executor executor) {
addInterfaceStateListener(executor, listener);
}
/**
* Listen to changes in the state of Ethernet interfaces.
*
* Adds a listener to receive notification for any state change of all existing Ethernet
* interfaces.
* <p>{@link Listener#onInterfaceStateChanged} will be triggered immediately for all
* existing interfaces upon adding a listener. The same method will be called on the
* listener every time any of the interface changes state. In particular, if an
* interface is removed, it will be called with state {@link #STATE_ABSENT}.
* <p>Use {@link #removeInterfaceStateListener} with the same object to stop listening.
*
* @param executor Executor to run callbacks on.
* @param listener A {@link Listener} to add.
* @hide
*/
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
@SystemApi(client = MODULE_LIBRARIES)
public void addInterfaceStateListener(@NonNull Executor executor,
@NonNull InterfaceStateListener listener) {
if (listener == null || executor == null) {
throw new NullPointerException("listener and executor must not be null");
}
synchronized (mListenerLock) {
maybeAddServiceListener();
mIfaceListeners.add(new ListenerInfo<InterfaceStateListener>(executor, listener));
}
}
@GuardedBy("mListenerLock")
private void maybeAddServiceListener() {
if (!mIfaceListeners.isEmpty() || !mEthernetStateListeners.isEmpty()) return;
try {
mService.addListener(mServiceListener);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Returns an array of available Ethernet interface names.
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public String[] getAvailableInterfaces() {
try {
return mService.getAvailableInterfaces();
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
/**
* Removes a listener.
*
* @param listener A {@link Listener} to remove.
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
public void removeInterfaceStateListener(@NonNull InterfaceStateListener listener) {
Objects.requireNonNull(listener);
synchronized (mListenerLock) {
mIfaceListeners.removeIf(l -> l.listener == listener);
maybeRemoveServiceListener();
}
}
@GuardedBy("mListenerLock")
private void maybeRemoveServiceListener() {
if (!mIfaceListeners.isEmpty() || !mEthernetStateListeners.isEmpty()) return;
try {
mService.removeListener(mServiceListener);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Removes a listener.
* This has never been a supported API. Use {@link #removeInterfaceStateListener} instead.
* @param listener A {@link Listener} to remove.
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public void removeListener(@NonNull Listener listener) {
if (listener == null) {
throw new IllegalArgumentException("listener must not be null");
}
removeInterfaceStateListener(listener);
}
/**
* Whether to treat interfaces created by {@link TestNetworkManager#createTapInterface}
* as Ethernet interfaces. The effects of this method apply to any test interfaces that are
* already present on the system.
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
public void setIncludeTestInterfaces(boolean include) {
try {
mService.setIncludeTestInterfaces(include);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* A request for a tethered interface.
*/
public static class TetheredInterfaceRequest {
private final IEthernetManager mService;
private final ITetheredInterfaceCallback mCb;
private TetheredInterfaceRequest(@NonNull IEthernetManager service,
@NonNull ITetheredInterfaceCallback cb) {
this.mService = service;
this.mCb = cb;
}
/**
* Release the request, causing the interface to revert back from tethering mode if there
* is no other requestor.
*/
public void release() {
try {
mService.releaseTetheredInterface(mCb);
} catch (RemoteException e) {
e.rethrowFromSystemServer();
}
}
}
/**
* Callback for {@link #requestTetheredInterface(TetheredInterfaceCallback)}.
*/
public interface TetheredInterfaceCallback {
/**
* Called when the tethered interface is available.
* @param iface The name of the interface.
*/
void onAvailable(@NonNull String iface);
/**
* Called when the tethered interface is now unavailable.
*/
void onUnavailable();
}
/**
* Request a tethered interface in tethering mode.
*
* <p>When this method is called and there is at least one ethernet interface available, the
* system will designate one to act as a tethered interface. If there is already a tethered
* interface, the existing interface will be used.
* @param callback A callback to be called once the request has been fulfilled.
*/
@RequiresPermission(anyOf = {
android.Manifest.permission.NETWORK_STACK,
android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
})
@NonNull
public TetheredInterfaceRequest requestTetheredInterface(@NonNull final Executor executor,
@NonNull final TetheredInterfaceCallback callback) {
Objects.requireNonNull(callback, "Callback must be non-null");
Objects.requireNonNull(executor, "Executor must be non-null");
final ITetheredInterfaceCallback cbInternal = new ITetheredInterfaceCallback.Stub() {
@Override
public void onAvailable(String iface) {
executor.execute(() -> callback.onAvailable(iface));
}
@Override
public void onUnavailable() {
executor.execute(() -> callback.onUnavailable());
}
};
try {
mService.requestTetheredInterface(cbInternal);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
return new TetheredInterfaceRequest(mService, cbInternal);
}
private static final class NetworkInterfaceOutcomeReceiver
extends INetworkInterfaceOutcomeReceiver.Stub {
@NonNull
private final Executor mExecutor;
@NonNull
private final OutcomeReceiver<String, EthernetNetworkManagementException> mCallback;
NetworkInterfaceOutcomeReceiver(
@NonNull final Executor executor,
@NonNull final OutcomeReceiver<String, EthernetNetworkManagementException>
callback) {
Objects.requireNonNull(executor, "Pass a non-null executor");
Objects.requireNonNull(callback, "Pass a non-null callback");
mExecutor = executor;
mCallback = callback;
}
@Override
public void onResult(@NonNull String iface) {
mExecutor.execute(() -> mCallback.onResult(iface));
}
@Override
public void onError(@NonNull EthernetNetworkManagementException e) {
mExecutor.execute(() -> mCallback.onError(e));
}
}
private NetworkInterfaceOutcomeReceiver makeNetworkInterfaceOutcomeReceiver(
@Nullable final Executor executor,
@Nullable final OutcomeReceiver<String, EthernetNetworkManagementException> callback) {
if (null != callback) {
Objects.requireNonNull(executor, "Pass a non-null executor, or a null callback");
}
final NetworkInterfaceOutcomeReceiver proxy;
if (null == callback) {
proxy = null;
} else {
proxy = new NetworkInterfaceOutcomeReceiver(executor, callback);
}
return proxy;
}
/**
* Updates the configuration of an automotive device's ethernet network.
*
* The {@link EthernetNetworkUpdateRequest} {@code request} argument describes how to update the
* configuration for this network.
* Use {@link StaticIpConfiguration.Builder} to build a {@code StaticIpConfiguration} object for
* this network to put inside the {@code request}.
* Similarly, use {@link NetworkCapabilities.Builder} to build a {@code NetworkCapabilities}
* object for this network to put inside the {@code request}.
*
* This function accepts an {@link OutcomeReceiver} that is called once the operation has
* finished execution.
*
* @param iface the name of the interface to act upon.
* @param request the {@link EthernetNetworkUpdateRequest} used to set an ethernet network's
* {@link StaticIpConfiguration} and {@link NetworkCapabilities} values.
* @param executor an {@link Executor} to execute the callback on. Optional if callback is null.
* @param callback an optional {@link OutcomeReceiver} to listen for completion of the
* operation. On success, {@link OutcomeReceiver#onResult} is called with the
* interface name. On error, {@link OutcomeReceiver#onError} is called with more
* information about the error.
* @throws SecurityException if the process doesn't hold
* {@link android.Manifest.permission.MANAGE_ETHERNET_NETWORKS}.
* @throws UnsupportedOperationException if called on a non-automotive device or on an
* unsupported interface.
* @hide
*/
@SystemApi
@RequiresPermission(anyOf = {
NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
android.Manifest.permission.NETWORK_STACK,
android.Manifest.permission.MANAGE_ETHERNET_NETWORKS})
public void updateConfiguration(
@NonNull String iface,
@NonNull EthernetNetworkUpdateRequest request,
@Nullable @CallbackExecutor Executor executor,
@Nullable OutcomeReceiver<String, EthernetNetworkManagementException> callback) {
Objects.requireNonNull(iface, "iface must be non-null");
Objects.requireNonNull(request, "request must be non-null");
final NetworkInterfaceOutcomeReceiver proxy = makeNetworkInterfaceOutcomeReceiver(
executor, callback);
try {
mService.updateConfiguration(iface, request, proxy);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Enable a network interface.
*
* Enables a previously disabled network interface.
* This function accepts an {@link OutcomeReceiver} that is called once the operation has
* finished execution.
*
* @param iface the name of the interface to enable.
* @param executor an {@link Executor} to execute the callback on. Optional if callback is null.
* @param callback an optional {@link OutcomeReceiver} to listen for completion of the
* operation. On success, {@link OutcomeReceiver#onResult} is called with the
* interface name. On error, {@link OutcomeReceiver#onError} is called with more
* information about the error.
* @throws SecurityException if the process doesn't hold
* {@link android.Manifest.permission.MANAGE_ETHERNET_NETWORKS}.
* @hide
*/
@SystemApi
@RequiresPermission(anyOf = {
NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
android.Manifest.permission.NETWORK_STACK,
android.Manifest.permission.MANAGE_ETHERNET_NETWORKS})
@RequiresFeature(PackageManager.FEATURE_AUTOMOTIVE)
public void enableInterface(
@NonNull String iface,
@Nullable @CallbackExecutor Executor executor,
@Nullable OutcomeReceiver<String, EthernetNetworkManagementException> callback) {
Objects.requireNonNull(iface, "iface must be non-null");
final NetworkInterfaceOutcomeReceiver proxy = makeNetworkInterfaceOutcomeReceiver(
executor, callback);
try {
mService.connectNetwork(iface, proxy);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Disable a network interface.
*
* Disables the use of a network interface to fulfill network requests. If the interface
* currently serves a request, the network will be torn down.
* This function accepts an {@link OutcomeReceiver} that is called once the operation has
* finished execution.
*
* @param iface the name of the interface to disable.
* @param executor an {@link Executor} to execute the callback on. Optional if callback is null.
* @param callback an optional {@link OutcomeReceiver} to listen for completion of the
* operation. On success, {@link OutcomeReceiver#onResult} is called with the
* interface name. On error, {@link OutcomeReceiver#onError} is called with more
* information about the error.
* @throws SecurityException if the process doesn't hold
* {@link android.Manifest.permission.MANAGE_ETHERNET_NETWORKS}.
* @hide
*/
@SystemApi
@RequiresPermission(anyOf = {
NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
android.Manifest.permission.NETWORK_STACK,
android.Manifest.permission.MANAGE_ETHERNET_NETWORKS})
@RequiresFeature(PackageManager.FEATURE_AUTOMOTIVE)
public void disableInterface(
@NonNull String iface,
@Nullable @CallbackExecutor Executor executor,
@Nullable OutcomeReceiver<String, EthernetNetworkManagementException> callback) {
Objects.requireNonNull(iface, "iface must be non-null");
final NetworkInterfaceOutcomeReceiver proxy = makeNetworkInterfaceOutcomeReceiver(
executor, callback);
try {
mService.disconnectNetwork(iface, proxy);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Change ethernet setting.
*
* @param enabled enable or disable ethernet settings.
*
* @hide
*/
@RequiresPermission(anyOf = {
NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
android.Manifest.permission.NETWORK_STACK,
android.Manifest.permission.NETWORK_SETTINGS})
@SystemApi(client = MODULE_LIBRARIES)
public void setEthernetEnabled(boolean enabled) {
try {
mService.setEthernetEnabled(enabled);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Listen to changes in the state of ethernet.
*
* @param executor to run callbacks on.
* @param listener to listen ethernet state changed.
*
* @hide
*/
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
@SystemApi(client = MODULE_LIBRARIES)
public void addEthernetStateListener(@NonNull Executor executor,
@NonNull IntConsumer listener) {
Objects.requireNonNull(executor);
Objects.requireNonNull(listener);
synchronized (mListenerLock) {
maybeAddServiceListener();
mEthernetStateListeners.add(new ListenerInfo<IntConsumer>(executor, listener));
}
}
/**
* Removes a listener.
*
* @param listener to listen ethernet state changed.
*
* @hide
*/
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
@SystemApi(client = MODULE_LIBRARIES)
public void removeEthernetStateListener(@NonNull IntConsumer listener) {
Objects.requireNonNull(listener);
synchronized (mListenerLock) {
mEthernetStateListeners.removeIf(l -> l.listener == listener);
maybeRemoveServiceListener();
}
}
/**
* Returns an array of existing Ethernet interface names regardless whether the interface
* is available or not currently.
* @hide
*/
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
@SystemApi(client = MODULE_LIBRARIES)
@NonNull
public List<String> getInterfaceList() {
try {
return mService.getInterfaceList();
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
}

View file

@ -0,0 +1,19 @@
/*
* Copyright (C) 2021 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;
parcelable EthernetNetworkManagementException;

View file

@ -0,0 +1,73 @@
/*
* Copyright (C) 2021 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.annotation.NonNull;
import android.annotation.SystemApi;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Objects;
/** @hide */
@SystemApi
public final class EthernetNetworkManagementException
extends RuntimeException implements Parcelable {
/* @hide */
public EthernetNetworkManagementException(@NonNull final String errorMessage) {
super(errorMessage);
}
@Override
public int hashCode() {
return Objects.hash(getMessage());
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
final EthernetNetworkManagementException that = (EthernetNetworkManagementException) obj;
return Objects.equals(getMessage(), that.getMessage());
}
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
dest.writeString(getMessage());
}
@Override
public int describeContents() {
return 0;
}
@NonNull
public static final Parcelable.Creator<EthernetNetworkManagementException> CREATOR =
new Parcelable.Creator<EthernetNetworkManagementException>() {
@Override
public EthernetNetworkManagementException[] newArray(int size) {
return new EthernetNetworkManagementException[size];
}
@Override
public EthernetNetworkManagementException createFromParcel(@NonNull Parcel source) {
return new EthernetNetworkManagementException(source.readString());
}
};
}

View file

@ -0,0 +1,102 @@
/*
* Copyright (C) 2021 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.annotation.NonNull;
import android.annotation.Nullable;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import java.util.Objects;
/**
* A {@link NetworkSpecifier} used to identify ethernet interfaces.
*
* @see EthernetManager
*/
public final class EthernetNetworkSpecifier extends NetworkSpecifier implements Parcelable {
/**
* Name of the network interface.
*/
@NonNull
private final String mInterfaceName;
/**
* Create a new EthernetNetworkSpecifier.
* @param interfaceName Name of the ethernet interface the specifier refers to.
*/
public EthernetNetworkSpecifier(@NonNull String interfaceName) {
if (TextUtils.isEmpty(interfaceName)) {
throw new IllegalArgumentException();
}
mInterfaceName = interfaceName;
}
/**
* Get the name of the ethernet interface the specifier refers to.
*/
@Nullable
public String getInterfaceName() {
// This may be null in the future to support specifiers based on data other than the
// interface name.
return mInterfaceName;
}
/** @hide */
@Override
public boolean canBeSatisfiedBy(@Nullable NetworkSpecifier other) {
return equals(other);
}
@Override
public boolean equals(@Nullable Object o) {
if (!(o instanceof EthernetNetworkSpecifier)) return false;
return TextUtils.equals(mInterfaceName, ((EthernetNetworkSpecifier) o).mInterfaceName);
}
@Override
public int hashCode() {
return Objects.hashCode(mInterfaceName);
}
@Override
public String toString() {
return "EthernetNetworkSpecifier (" + mInterfaceName + ")";
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
dest.writeString(mInterfaceName);
}
public static final @NonNull Parcelable.Creator<EthernetNetworkSpecifier> CREATOR =
new Parcelable.Creator<EthernetNetworkSpecifier>() {
public EthernetNetworkSpecifier createFromParcel(Parcel in) {
return new EthernetNetworkSpecifier(in.readString());
}
public EthernetNetworkSpecifier[] newArray(int size) {
return new EthernetNetworkSpecifier[size];
}
};
}

View file

@ -0,0 +1,19 @@
/*
* Copyright (C) 2021 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;
parcelable EthernetNetworkUpdateRequest;

View file

@ -0,0 +1,185 @@
/*
* Copyright (C) 2021 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.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Objects;
/**
* Represents a request to update an existing Ethernet interface.
*
* @see EthernetManager#updateConfiguration
*
* @hide
*/
@SystemApi
public final class EthernetNetworkUpdateRequest implements Parcelable {
@Nullable
private final IpConfiguration mIpConfig;
@Nullable
private final NetworkCapabilities mNetworkCapabilities;
/**
* Setting the {@link IpConfiguration} is optional in {@link EthernetNetworkUpdateRequest}.
* When set to null, the existing IpConfiguration is not updated.
*
* @return the new {@link IpConfiguration} or null.
*/
@Nullable
public IpConfiguration getIpConfiguration() {
return mIpConfig == null ? null : new IpConfiguration(mIpConfig);
}
/**
* Setting the {@link NetworkCapabilities} is optional in {@link EthernetNetworkUpdateRequest}.
* When set to null, the existing NetworkCapabilities are not updated.
*
* @return the new {@link NetworkCapabilities} or null.
*/
@Nullable
public NetworkCapabilities getNetworkCapabilities() {
return mNetworkCapabilities == null ? null : new NetworkCapabilities(mNetworkCapabilities);
}
private EthernetNetworkUpdateRequest(@Nullable final IpConfiguration ipConfig,
@Nullable final NetworkCapabilities networkCapabilities) {
mIpConfig = ipConfig;
mNetworkCapabilities = networkCapabilities;
}
private EthernetNetworkUpdateRequest(@NonNull final Parcel source) {
Objects.requireNonNull(source);
mIpConfig = source.readParcelable(IpConfiguration.class.getClassLoader(),
IpConfiguration.class);
mNetworkCapabilities = source.readParcelable(NetworkCapabilities.class.getClassLoader(),
NetworkCapabilities.class);
}
/**
* Builder used to create {@link EthernetNetworkUpdateRequest} objects.
*/
public static final class Builder {
@Nullable
private IpConfiguration mBuilderIpConfig;
@Nullable
private NetworkCapabilities mBuilderNetworkCapabilities;
public Builder(){}
/**
* Constructor to populate the builder's values with an already built
* {@link EthernetNetworkUpdateRequest}.
* @param request the {@link EthernetNetworkUpdateRequest} to populate with.
*/
public Builder(@NonNull final EthernetNetworkUpdateRequest request) {
Objects.requireNonNull(request);
mBuilderIpConfig = null == request.mIpConfig
? null : new IpConfiguration(request.mIpConfig);
mBuilderNetworkCapabilities = null == request.mNetworkCapabilities
? null : new NetworkCapabilities(request.mNetworkCapabilities);
}
/**
* Set the {@link IpConfiguration} to be used with the {@code Builder}.
* @param ipConfig the {@link IpConfiguration} to set.
* @return The builder to facilitate chaining.
*/
@NonNull
public Builder setIpConfiguration(@Nullable final IpConfiguration ipConfig) {
mBuilderIpConfig = ipConfig == null ? null : new IpConfiguration(ipConfig);
return this;
}
/**
* Set the {@link NetworkCapabilities} to be used with the {@code Builder}.
* @param nc the {@link NetworkCapabilities} to set.
* @return The builder to facilitate chaining.
*/
@NonNull
public Builder setNetworkCapabilities(@Nullable final NetworkCapabilities nc) {
mBuilderNetworkCapabilities = nc == null ? null : new NetworkCapabilities(nc);
return this;
}
/**
* Build {@link EthernetNetworkUpdateRequest} return the current update request.
*
* @throws IllegalStateException when both mBuilderNetworkCapabilities and mBuilderIpConfig
* are null.
*/
@NonNull
public EthernetNetworkUpdateRequest build() {
if (mBuilderIpConfig == null && mBuilderNetworkCapabilities == null) {
throw new IllegalStateException(
"Cannot construct an empty EthernetNetworkUpdateRequest");
}
return new EthernetNetworkUpdateRequest(mBuilderIpConfig, mBuilderNetworkCapabilities);
}
}
@Override
public String toString() {
return "EthernetNetworkUpdateRequest{"
+ "mIpConfig=" + mIpConfig
+ ", mNetworkCapabilities=" + mNetworkCapabilities + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EthernetNetworkUpdateRequest that = (EthernetNetworkUpdateRequest) o;
return Objects.equals(that.getIpConfiguration(), mIpConfig)
&& Objects.equals(that.getNetworkCapabilities(), mNetworkCapabilities);
}
@Override
public int hashCode() {
return Objects.hash(mIpConfig, mNetworkCapabilities);
}
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
dest.writeParcelable(mIpConfig, flags);
dest.writeParcelable(mNetworkCapabilities, flags);
}
@Override
public int describeContents() {
return 0;
}
@NonNull
public static final Parcelable.Creator<EthernetNetworkUpdateRequest> CREATOR =
new Parcelable.Creator<EthernetNetworkUpdateRequest>() {
@Override
public EthernetNetworkUpdateRequest[] newArray(int size) {
return new EthernetNetworkUpdateRequest[size];
}
@Override
public EthernetNetworkUpdateRequest createFromParcel(@NonNull Parcel source) {
return new EthernetNetworkUpdateRequest(source);
}
};
}

View file

@ -0,0 +1,50 @@
/*
* Copyright (C) 2014 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.IpConfiguration;
import android.net.IEthernetServiceListener;
import android.net.EthernetNetworkManagementException;
import android.net.EthernetNetworkUpdateRequest;
import android.net.INetworkInterfaceOutcomeReceiver;
import android.net.ITetheredInterfaceCallback;
import java.util.List;
/**
* Interface that answers queries about, and allows changing
* ethernet configuration.
*/
/** {@hide} */
interface IEthernetManager
{
String[] getAvailableInterfaces();
IpConfiguration getConfiguration(String iface);
void setConfiguration(String iface, in IpConfiguration config);
boolean isAvailable(String iface);
void addListener(in IEthernetServiceListener listener);
void removeListener(in IEthernetServiceListener listener);
void setIncludeTestInterfaces(boolean include);
void requestTetheredInterface(in ITetheredInterfaceCallback callback);
void releaseTetheredInterface(in ITetheredInterfaceCallback callback);
void updateConfiguration(String iface, in EthernetNetworkUpdateRequest request,
in INetworkInterfaceOutcomeReceiver listener);
void connectNetwork(String iface, in INetworkInterfaceOutcomeReceiver listener);
void disconnectNetwork(String iface, in INetworkInterfaceOutcomeReceiver listener);
void setEthernetEnabled(boolean enabled);
List<String> getInterfaceList();
}

View file

@ -0,0 +1,27 @@
/*
* Copyright (C) 2014 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.IpConfiguration;
/** @hide */
oneway interface IEthernetServiceListener
{
void onEthernetStateChanged(int state);
void onInterfaceStateChanged(String iface, int state, int role,
in IpConfiguration configuration);
}

View file

@ -0,0 +1,78 @@
/*
** Copyright 2017, 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.LinkAddress;
import android.net.Network;
import android.net.IpSecConfig;
import android.net.IpSecUdpEncapResponse;
import android.net.IpSecSpiResponse;
import android.net.IpSecTransformResponse;
import android.net.IpSecTunnelInterfaceResponse;
import android.os.Bundle;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
/**
* @hide
*/
interface IIpSecService
{
IpSecSpiResponse allocateSecurityParameterIndex(
in String destinationAddress, int requestedSpi, in IBinder binder);
void releaseSecurityParameterIndex(int resourceId);
IpSecUdpEncapResponse openUdpEncapsulationSocket(int port, in IBinder binder);
void closeUdpEncapsulationSocket(int resourceId);
IpSecTunnelInterfaceResponse createTunnelInterface(
in String localAddr,
in String remoteAddr,
in Network underlyingNetwork,
in IBinder binder,
in String callingPackage);
void addAddressToTunnelInterface(
int tunnelResourceId,
in LinkAddress localAddr,
in String callingPackage);
void removeAddressFromTunnelInterface(
int tunnelResourceId,
in LinkAddress localAddr,
in String callingPackage);
void setNetworkForTunnelInterface(
int tunnelResourceId, in Network underlyingNetwork, in String callingPackage);
void deleteTunnelInterface(int resourceId, in String callingPackage);
IpSecTransformResponse createTransform(
in IpSecConfig c, in IBinder binder, in String callingPackage);
void deleteTransform(int transformId);
void applyTransportModeTransform(
in ParcelFileDescriptor socket, int direction, int transformId);
void applyTunnelModeTransform(
int tunnelResourceId, int direction, int transformResourceId, in String callingPackage);
void removeTransportModeTransforms(in ParcelFileDescriptor socket);
}

View file

@ -0,0 +1,25 @@
/**
* Copyright (c) 2021, 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.EthernetNetworkManagementException;
/** @hide */
oneway interface INetworkInterfaceOutcomeReceiver {
void onResult(in String iface);
void onError(in EthernetNetworkManagementException e);
}

View file

@ -0,0 +1,104 @@
/*
* Copyright (C) 2011 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.DataUsageRequest;
import android.net.INetworkStatsSession;
import android.net.Network;
import android.net.NetworkStateSnapshot;
import android.net.NetworkStats;
import android.net.NetworkStatsHistory;
import android.net.NetworkTemplate;
import android.net.UnderlyingNetworkInfo;
import android.net.netstats.IUsageCallback;
import android.net.netstats.provider.INetworkStatsProvider;
import android.net.netstats.provider.INetworkStatsProviderCallback;
import android.os.IBinder;
import android.os.Messenger;
/** {@hide} */
interface INetworkStatsService {
/** Start a statistics query session. */
@UnsupportedAppUsage
INetworkStatsSession openSession();
/** Start a statistics query session. If calling package is profile or device owner then it is
* granted automatic access if apiLevel is NetworkStatsManager.API_LEVEL_DPC_ALLOWED. If
* apiLevel is at least NetworkStatsManager.API_LEVEL_REQUIRES_PACKAGE_USAGE_STATS then
* PACKAGE_USAGE_STATS permission is always checked. If PACKAGE_USAGE_STATS is not granted
* READ_NETWORK_USAGE_STATS is checked for.
*/
@UnsupportedAppUsage(maxTargetSdk = 30, trackingBug = 170729553)
INetworkStatsSession openSessionForUsageStats(int flags, String callingPackage);
/** Return data layer snapshot of UID network usage. */
@UnsupportedAppUsage
NetworkStats getDataLayerSnapshotForUid(int uid);
/** Get the transport NetworkStats for all UIDs since boot. */
NetworkStats getUidStatsForTransport(int transport);
/** Return set of any ifaces associated with mobile networks since boot. */
@UnsupportedAppUsage
String[] getMobileIfaces();
/** Increment data layer count of operations performed for UID and tag. */
void incrementOperationCount(int uid, int tag, int operationCount);
/** Notify {@code NetworkStatsService} about network status changed. */
void notifyNetworkStatus(
in Network[] defaultNetworks,
in NetworkStateSnapshot[] snapshots,
in String activeIface,
in UnderlyingNetworkInfo[] underlyingNetworkInfos);
/** Force update of statistics. */
@UnsupportedAppUsage
void forceUpdate();
/** Registers a callback on data usage. */
DataUsageRequest registerUsageCallback(String callingPackage,
in DataUsageRequest request, in IUsageCallback callback);
/** Unregisters a callback on data usage. */
void unregisterUsageRequest(in DataUsageRequest request);
/** Get the uid stats information since boot */
long getUidStats(int uid, int type);
/** Get the iface stats information since boot */
long getIfaceStats(String iface, int type);
/** Get the total network stats information since boot */
long getTotalStats(int type);
/** Registers a network stats provider */
INetworkStatsProviderCallback registerNetworkStatsProvider(String tag,
in INetworkStatsProvider provider);
/** Mark given UID as being in foreground for stats purposes. */
void noteUidForeground(int uid, boolean uidForeground);
/** Advise persistence threshold; may be overridden internally. */
void advisePersistThreshold(long thresholdBytes);
/**
* Set the warning and limit to all registered custom network stats providers.
* Note that invocation of any interface will be sent to all providers.
*/
void setStatsProviderWarningAndLimitAsync(String iface, long warning, long limit);
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (C) 2012 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.NetworkStats;
import android.net.NetworkStatsHistory;
import android.net.NetworkTemplate;
/** {@hide} */
interface INetworkStatsSession {
/** Return device aggregated network layer usage summary for traffic that matches template. */
NetworkStats getDeviceSummaryForNetwork(in NetworkTemplate template, long start, long end);
/** Return network layer usage summary for traffic that matches template. */
@UnsupportedAppUsage
NetworkStats getSummaryForNetwork(in NetworkTemplate template, long start, long end);
/** Return historical network layer stats for traffic that matches template. */
@UnsupportedAppUsage
NetworkStatsHistory getHistoryForNetwork(in NetworkTemplate template, int fields);
/**
* Return historical network layer stats for traffic that matches template, start and end
* timestamp.
*/
NetworkStatsHistory getHistoryIntervalForNetwork(in NetworkTemplate template, int fields, long start, long end);
/**
* Return network layer usage summary per UID for traffic that matches template.
*
* <p>The resulting {@code NetworkStats#getElapsedRealtime()} contains time delta between
* {@code start} and {@code end}.
*
* @param template - a predicate to filter netstats.
* @param start - start of the range, timestamp in milliseconds since the epoch.
* @param end - end of the range, timestamp in milliseconds since the epoch.
* @param includeTags - includes data usage tags if true.
*/
@UnsupportedAppUsage
NetworkStats getSummaryForAllUid(in NetworkTemplate template, long start, long end, boolean includeTags);
/** Return network layer usage summary per UID for tagged traffic that matches template. */
NetworkStats getTaggedSummaryForAllUid(in NetworkTemplate template, long start, long end);
/** Return historical network layer stats for specific UID traffic that matches template. */
@UnsupportedAppUsage
NetworkStatsHistory getHistoryForUid(in NetworkTemplate template, int uid, int set, int tag, int fields);
/** Return historical network layer stats for specific UID traffic that matches template. */
NetworkStatsHistory getHistoryIntervalForUid(in NetworkTemplate template, int uid, int set, int tag, int fields, long start, long end);
/** Return array of uids that have stats and are accessible to the calling user */
int[] getRelevantUids();
@UnsupportedAppUsage
void close();
}

Some files were not shown because too many files have changed in this diff Show more