2 * Copyright (C) 2014 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "UidRanges.h"
19 #include "NetdConstants.h"
23 #include <android-base/stringprintf.h>
25 using android::base::StringAppendF;
27 bool UidRanges::hasUid(uid_t uid) const {
28 auto iter = std::lower_bound(mRanges.begin(), mRanges.end(), Range(uid, uid));
29 return (iter != mRanges.end() && iter->first == uid) ||
30 (iter != mRanges.begin() && (--iter)->second >= uid);
33 const std::vector<UidRanges::Range>& UidRanges::getRanges() const {
37 bool UidRanges::parseFrom(int argc, char* argv[]) {
39 for (int i = 0; i < argc; ++i) {
41 // The UID string is empty.
45 uid_t uidStart = strtoul(argv[i], &endPtr, 0);
48 // Found a single UID. The range contains just the one UID.
50 } else if (*endPtr == '-') {
52 // Unexpected end of string.
55 uidEnd = strtoul(endPtr, &endPtr, 0);
57 // Illegal trailing chars.
60 if (uidEnd < uidStart) {
65 // Not a single uid, not a range. Found some other illegal char.
68 if (uidStart == INVALID_UID || uidEnd == INVALID_UID) {
72 mRanges.push_back(Range(uidStart, uidEnd));
74 std::sort(mRanges.begin(), mRanges.end());
78 UidRanges::UidRanges(const std::vector<android::net::UidRange>& ranges) {
79 mRanges.resize(ranges.size());
80 std::transform(ranges.begin(), ranges.end(), mRanges.begin(),
81 [](const android::net::UidRange& range) {
82 return Range(range.getStart(), range.getStop());
84 std::sort(mRanges.begin(), mRanges.end());
87 void UidRanges::add(const UidRanges& other) {
88 auto middle = mRanges.insert(mRanges.end(), other.mRanges.begin(), other.mRanges.end());
89 std::inplace_merge(mRanges.begin(), middle, mRanges.end());
92 void UidRanges::remove(const UidRanges& other) {
93 auto end = std::set_difference(mRanges.begin(), mRanges.end(), other.mRanges.begin(),
94 other.mRanges.end(), mRanges.begin());
95 mRanges.erase(end, mRanges.end());
98 std::string UidRanges::toString() const {
99 std::string s("UidRanges{ ");
100 for (Range range : mRanges) {
101 if (range.first != range.second) {
102 StringAppendF(&s, "%u-%u ", range.first, range.second);
104 StringAppendF(&s, "%u ", range.first);
107 StringAppendF(&s, "}");