Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit f3013859 authored by Chiachang Wang's avatar Chiachang Wang
Browse files

Revert^2 "Replace the usage of UidRange"

5b7aad69

UidRange is used in a shared way between ConnectivityService
and VPN through the use of NetworkCapabilities. UidRange will
be part of the ConnectivityService mainline but Vpn.java will
stay in the framework. We need a way to replace the APIs using
UidRange, or to make UidRange system API. The only really
relevant surface here is NetworkCapabilities#{setUids, getUids}.
The need for UidRange could be replaced by an integer Range, so
replace the usage of UidRange by a integer Range in
NetworkCapabilities#{setUids, getUids} and update the relevant
callers.

Bug: 172183305
Test: atest FrameworksNetTests CtsNetTestCasesLatestSdk

Change-Id: I0f679fb5fb8f4fe26461ca4912ca1fdfe7f43c9e
Merged-In: I4e5aec6ef1ea02e038fcd7ed117a3b67b69c5cb9
parent 5b7aad69
Loading
Loading
Loading
Loading
+19 −12
Original line number Diff line number Diff line
@@ -32,6 +32,7 @@ import android.os.Parcelable;
import android.os.Process;
import android.text.TextUtils;
import android.util.ArraySet;
import android.util.Range;
import android.util.proto.ProtoOutputStream;

import com.android.internal.annotations.VisibleForTesting;
@@ -153,7 +154,7 @@ public final class NetworkCapabilities implements Parcelable {
            setTransportInfo(null);
        }
        mSignalStrength = nc.mSignalStrength;
        setUids(nc.mUids); // Will make the defensive copy
        mUids = (nc.mUids == null) ? null : new ArraySet<>(nc.mUids);
        setAdministratorUids(nc.getAdministratorUids());
        mOwnerUid = nc.mOwnerUid;
        mUnwantedNetworkCapabilities = nc.mUnwantedNetworkCapabilities;
@@ -1458,9 +1459,8 @@ public final class NetworkCapabilities implements Parcelable {
     * @hide
     */
    public @NonNull NetworkCapabilities setSingleUid(int uid) {
        final ArraySet<UidRange> identity = new ArraySet<>(1);
        identity.add(new UidRange(uid, uid));
        setUids(identity);
        mUids = new ArraySet<>(1);
        mUids.add(new UidRange(uid, uid));
        return this;
    }

@@ -1469,12 +1469,8 @@ public final class NetworkCapabilities implements Parcelable {
     * This makes a copy of the set so that callers can't modify it after the call.
     * @hide
     */
    public @NonNull NetworkCapabilities setUids(Set<UidRange> uids) {
        if (null == uids) {
            mUids = null;
        } else {
            mUids = new ArraySet<>(uids);
        }
    public @NonNull NetworkCapabilities setUids(@Nullable Set<Range<Integer>> uids) {
        mUids = UidRange.fromIntRanges(uids);
        return this;
    }

@@ -1483,8 +1479,19 @@ public final class NetworkCapabilities implements Parcelable {
     * This returns a copy of the set so that callers can't modify the original object.
     * @hide
     */
    public @Nullable Set<UidRange> getUids() {
        return null == mUids ? null : new ArraySet<>(mUids);
    public @Nullable Set<Range<Integer>> getUids() {
        return UidRange.toIntRanges(mUids);
    }

    /**
     * Get the list of UIDs this network applies to.
     * This returns a copy of the set so that callers can't modify the original object.
     * @hide
     */
    public @Nullable Set<UidRange> getUidRanges() {
        if (mUids == null) return null;

        return new ArraySet<>(mUids);
    }

    /**
+3 −2
Original line number Diff line number Diff line
@@ -45,6 +45,7 @@ import android.os.Parcel;
import android.os.Parcelable;
import android.os.Process;
import android.text.TextUtils;
import android.util.Range;
import android.util.proto.ProtoOutputStream;

import java.util.Arrays;
@@ -277,11 +278,11 @@ public class NetworkRequest implements Parcelable {
         * Set the watched UIDs for this request. This will be reset and wiped out unless
         * the calling app holds the CHANGE_NETWORK_STATE permission.
         *
         * @param uids The watched UIDs as a set of UidRanges, or null for everything.
         * @param uids The watched UIDs as a set of {@code Range<Integer>}, or null for everything.
         * @return The builder to facilitate chaining.
         * @hide
         */
        public Builder setUids(Set<UidRange> uids) {
        public Builder setUids(@Nullable Set<Range<Integer>> uids) {
            mNetworkCapabilities.setUids(uids);
            return this;
        }
+31 −0
Original line number Diff line number Diff line
@@ -20,8 +20,11 @@ import android.annotation.Nullable;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.UserHandle;
import android.util.ArraySet;
import android.util.Range;

import java.util.Collection;
import java.util.Set;

/**
 * An inclusive range of UIDs.
@@ -149,4 +152,32 @@ public final class UidRange implements Parcelable {
        }
        return false;
    }

    /**
     *  Convert a set of {@code Range<Integer>} to a set of {@link UidRange}.
     */
    @Nullable
    public static ArraySet<UidRange> fromIntRanges(@Nullable Set<Range<Integer>> ranges) {
        if (null == ranges) return null;

        final ArraySet<UidRange> uids = new ArraySet<>();
        for (Range<Integer> range : ranges) {
            uids.add(new UidRange(range.getLower(), range.getUpper()));
        }
        return uids;
    }

    /**
     *  Convert a set of {@link UidRange} to a set of {@code Range<Integer>}.
     */
    @Nullable
    public static ArraySet<Range<Integer>> toIntRanges(@Nullable Set<UidRange> ranges) {
        if (null == ranges) return null;

        final ArraySet<Range<Integer>> uids = new ArraySet<>();
        for (UidRange range : ranges) {
            uids.add(new Range<Integer>(range.start, range.stop));
        }
        return uids;
    }
}
+10 −12
Original line number Diff line number Diff line
@@ -1343,7 +1343,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
        netCap.addCapability(NET_CAPABILITY_INTERNET);
        netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
        netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
        netCap.setUids(Collections.singleton(uids));
        netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
        return netCap;
    }

@@ -2903,7 +2903,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
            if (0 == defaultRequest.mRequests.size()) {
                pw.println("none, this should never occur.");
            } else {
                pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUids());
                pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges());
            }
            pw.decreaseIndent();
            pw.decreaseIndent();
@@ -5320,9 +5320,8 @@ public class ConnectivityService extends IConnectivityManager.Stub
        private Set<UidRange> getUids() {
            // networkCapabilities.getUids() returns a defensive copy.
            // multilayer requests will all have the same uids so return the first one.
            final Set<UidRange> uids = null == mRequests.get(0).networkCapabilities.getUids()
                    ? new ArraySet<>() : mRequests.get(0).networkCapabilities.getUids();
            return uids;
            final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
            return (null == uids) ? new ArraySet<>() : uids;
        }

        NetworkRequestInfo(@NonNull final NetworkRequest r, @Nullable final PendingIntent pi,
@@ -6128,7 +6127,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
        for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
            // Currently, all network requests will have the same uids therefore checking the first
            // one is sufficient. If/when uids are tracked at the nri level, this can change.
            final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUids();
            final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
            if (null == uids) {
                continue;
            }
@@ -6569,7 +6568,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
            return;
        }

        final Set<UidRange> ranges = nai.networkCapabilities.getUids();
        final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
        final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
        // TODO: this create a window of opportunity for apps to receive traffic between the time
        // when the old rules are removed and the time when new rules are added. To fix this,
@@ -6934,8 +6933,8 @@ public class ConnectivityService extends IConnectivityManager.Stub

    private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
            NetworkCapabilities newNc) {
        Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
        Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
        Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
        Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
        if (null == prevRanges) prevRanges = new ArraySet<>();
        if (null == newRanges) newRanges = new ArraySet<>();
        final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
@@ -9266,7 +9265,7 @@ public class ConnectivityService extends IConnectivityManager.Stub
            final ArrayList<NetworkRequest> nrs = new ArrayList<>();
            nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
            nrs.add(createDefaultRequest());
            setNetworkRequestUids(nrs, pref.capabilities.getUids());
            setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
            final NetworkRequestInfo nri = new NetworkRequestInfo(nrs);
            result.add(nri);
        }
@@ -9482,9 +9481,8 @@ public class ConnectivityService extends IConnectivityManager.Stub

    private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
            @NonNull final Set<UidRange> uids) {
        final Set<UidRange> ranges = new ArraySet<>(uids);
        for (final NetworkRequest req : requests) {
            req.networkCapabilities.setUids(ranges);
            req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
        }
    }

+45 −35
Original line number Diff line number Diff line
@@ -19,6 +19,7 @@ package com.android.server.connectivity;
import static android.Manifest.permission.BIND_VPN_SERVICE;
import static android.net.ConnectivityManager.NETID_UNSET;
import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
import static android.os.UserHandle.PER_USER_RANGE;
import static android.net.RouteInfo.RTN_THROW;
import static android.net.RouteInfo.RTN_UNREACHABLE;
import static android.net.VpnManager.NOTIFICATION_CHANNEL_VPN;
@@ -69,7 +70,6 @@ import android.net.NetworkInfo.DetailedState;
import android.net.NetworkProvider;
import android.net.NetworkRequest;
import android.net.RouteInfo;
import android.net.UidRange;
import android.net.UidRangeParcel;
import android.net.UnderlyingNetworkInfo;
import android.net.VpnManager;
@@ -1346,7 +1346,7 @@ public class Vpn {
        String oldInterface = mInterface;
        Connection oldConnection = mConnection;
        NetworkAgent oldNetworkAgent = mNetworkAgent;
        Set<UidRange> oldUsers = mNetworkCapabilities.getUids();
        Set<Range<Integer>> oldUsers = mNetworkCapabilities.getUids();

        // Configure the interface. Abort if any of these steps fails.
        ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
@@ -1452,7 +1452,7 @@ public class Vpn {
    }

    /**
     * Creates a {@link Set} of non-intersecting {@link UidRange} objects including all UIDs
     * Creates a {@link Set} of non-intersecting {@code Range<Integer>} objects including all UIDs
     * associated with one user, and any restricted profiles attached to that user.
     *
     * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
@@ -1465,10 +1465,10 @@ public class Vpn {
     * @param disallowedApplications (optional) List of applications to deny.
     */
    @VisibleForTesting
    Set<UidRange> createUserAndRestrictedProfilesRanges(@UserIdInt int userId,
    Set<Range<Integer>> createUserAndRestrictedProfilesRanges(@UserIdInt int userId,
            @Nullable List<String> allowedApplications,
            @Nullable List<String> disallowedApplications) {
        final Set<UidRange> ranges = new ArraySet<>();
        final Set<Range<Integer>> ranges = new ArraySet<>();

        // Assign the top-level user to the set of ranges
        addUserToRanges(ranges, userId, allowedApplications, disallowedApplications);
@@ -1492,20 +1492,20 @@ public class Vpn {
    }

    /**
     * Updates a {@link Set} of non-intersecting {@link UidRange} objects to include all UIDs
     * Updates a {@link Set} of non-intersecting {@code Range<Integer>} objects to include all UIDs
     * associated with one user.
     *
     * <p>If one of {@param allowedApplications} or {@param disallowedApplications} is provided,
     * the UID ranges will match the app allowlist or denylist specified there. Otherwise, all UIDs
     * in the user will be included.
     *
     * @param ranges {@link Set} of {@link UidRange}s to which to add.
     * @param ranges {@link Set} of {@code Range<Integer>}s to which to add.
     * @param userId The userId to add to {@param ranges}.
     * @param allowedApplications (optional) allowlist of applications to include.
     * @param disallowedApplications (optional) denylist of applications to exclude.
     */
    @VisibleForTesting
    void addUserToRanges(@NonNull Set<UidRange> ranges, @UserIdInt int userId,
    void addUserToRanges(@NonNull Set<Range<Integer>> ranges, @UserIdInt int userId,
            @Nullable List<String> allowedApplications,
            @Nullable List<String> disallowedApplications) {
        if (allowedApplications != null) {
@@ -1515,40 +1515,41 @@ public class Vpn {
                if (start == -1) {
                    start = uid;
                } else if (uid != stop + 1) {
                    ranges.add(new UidRange(start, stop));
                    ranges.add(new Range<Integer>(start, stop));
                    start = uid;
                }
                stop = uid;
            }
            if (start != -1) ranges.add(new UidRange(start, stop));
            if (start != -1) ranges.add(new Range<Integer>(start, stop));
        } else if (disallowedApplications != null) {
            // Add all ranges for user skipping UIDs for disallowedApplications.
            final UidRange userRange = UidRange.createForUser(UserHandle.of(userId));
            int start = userRange.start;
            final Range<Integer> userRange = createUidRangeForUser(userId);
            int start = userRange.getLower();
            for (int uid : getAppsUids(disallowedApplications, userId)) {
                if (uid == start) {
                    start++;
                } else {
                    ranges.add(new UidRange(start, uid - 1));
                    ranges.add(new Range<Integer>(start, uid - 1));
                    start = uid + 1;
                }
            }
            if (start <= userRange.stop) ranges.add(new UidRange(start, userRange.stop));
            if (start <= userRange.getUpper()) {
                ranges.add(new Range<Integer>(start, userRange.getUpper()));
            }
        } else {
            // Add all UIDs for the user.
            ranges.add(UidRange.createForUser(UserHandle.of(userId)));
            ranges.add(createUidRangeForUser(userId));
        }
    }

    // Returns the subset of the full list of active UID ranges the VPN applies to (mVpnUsers) that
    // apply to userId.
    private static List<UidRange> uidRangesForUser(int userId, Set<UidRange> existingRanges) {
        // UidRange#createForUser returns the entire range of UIDs available to a macro-user.
        // This is something like 0-99999 ; {@see UserHandle#PER_USER_RANGE}
        final UidRange userRange = UidRange.createForUser(UserHandle.of(userId));
        final List<UidRange> ranges = new ArrayList<>();
        for (UidRange range : existingRanges) {
            if (userRange.containsRange(range)) {
    private static List<Range<Integer>> uidRangesForUser(int userId,
            Set<Range<Integer>> existingRanges) {
        final Range<Integer> userRange = createUidRangeForUser(userId);
        final List<Range<Integer>> ranges = new ArrayList<>();
        for (Range<Integer> range : existingRanges) {
            if (userRange.contains(range)) {
                ranges.add(range);
            }
        }
@@ -1565,7 +1566,7 @@ public class Vpn {
        UserInfo user = mUserManager.getUserInfo(userId);
        if (user.isRestricted() && user.restrictedProfileParentId == mUserId) {
            synchronized(Vpn.this) {
                final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
                final Set<Range<Integer>> existingRanges = mNetworkCapabilities.getUids();
                if (existingRanges != null) {
                    try {
                        addUserToRanges(existingRanges, userId, mConfig.allowedApplications,
@@ -1593,10 +1594,10 @@ public class Vpn {
        UserInfo user = mUserManager.getUserInfo(userId);
        if (user.isRestricted() && user.restrictedProfileParentId == mUserId) {
            synchronized(Vpn.this) {
                final Set<UidRange> existingRanges = mNetworkCapabilities.getUids();
                final Set<Range<Integer>> existingRanges = mNetworkCapabilities.getUids();
                if (existingRanges != null) {
                    try {
                        final List<UidRange> removedRanges =
                        final List<Range<Integer>> removedRanges =
                                uidRangesForUser(userId, existingRanges);
                        existingRanges.removeAll(removedRanges);
                        mNetworkCapabilities.setUids(existingRanges);
@@ -1657,7 +1658,7 @@ public class Vpn {
        final Set<UidRangeParcel> rangesToRemove = new ArraySet<>(mBlockedUidsAsToldToConnectivity);
        final Set<UidRangeParcel> rangesToAdd;
        if (enforce) {
            final Set<UidRange> restrictedProfilesRanges =
            final Set<Range<Integer>> restrictedProfilesRanges =
                    createUserAndRestrictedProfilesRanges(mUserId,
                    /* allowedApplications */ null,
                    /* disallowedApplications */ exemptedPackages);
@@ -1666,11 +1667,12 @@ public class Vpn {
            // The UID range of the first user (0-99999) would block the IPSec traffic, which comes
            // directly from the kernel and is marked as uid=0. So we adjust the range to allow
            // it through (b/69873852).
            for (UidRange range : restrictedProfilesRanges) {
                if (range.start == 0 && range.stop != 0) {
                    rangesThatShouldBeBlocked.add(new UidRangeParcel(1, range.stop));
                } else if (range.start != 0) {
                    rangesThatShouldBeBlocked.add(new UidRangeParcel(range.start, range.stop));
            for (Range<Integer> range : restrictedProfilesRanges) {
                if (range.getLower() == 0 && range.getUpper() != 0) {
                    rangesThatShouldBeBlocked.add(new UidRangeParcel(1, range.getUpper()));
                } else if (range.getLower() != 0) {
                    rangesThatShouldBeBlocked.add(
                            new UidRangeParcel(range.getLower(), range.getUpper()));
                }
            }

@@ -1692,12 +1694,12 @@ public class Vpn {
    }

    /**
     * Tell ConnectivityService to add or remove a list of {@link UidRange}s to the list of UIDs
     * that are only allowed to make connections through sockets that have had {@code protect()}
     * called on them.
     * Tell ConnectivityService to add or remove a list of {@link UidRangeParcel}s to the list of
     * UIDs that are only allowed to make connections through sockets that have had
     * {@code protect()} called on them.
     *
     * @param enforce {@code true} to add to the denylist, {@code false} to remove.
     * @param ranges {@link Collection} of {@link UidRange}s to add (if {@param enforce} is
     * @param ranges {@link Collection} of {@link UidRangeParcel}s to add (if {@param enforce} is
     *               {@code true}) or to remove.
     * @return {@code true} if all of the UIDs were added/removed. {@code false} otherwise,
     *         including added ranges that already existed or removed ones that didn't.
@@ -3338,4 +3340,12 @@ public class Vpn {
                    firstChildSessionCallback);
        }
    }

    /**
     * Returns the entire range of UIDs available to a macro-user. This is something like 0-99999.
     */
    @VisibleForTesting
    static Range<Integer> createUidRangeForUser(int userId) {
        return new Range<Integer>(userId * PER_USER_RANGE, (userId + 1) * PER_USER_RANGE - 1);
    }
}
Loading