UidRanges.cpp revision b1425cc09f8a29350520db0d4f489331df5a689b
1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17#include "UidRanges.h" 18 19#include "NetdConstants.h" 20 21#include <stdlib.h> 22 23const std::vector<std::pair<uid_t, uid_t>>& UidRanges::getRanges() const { 24 return mRanges; 25} 26 27bool UidRanges::parseFrom(int argc, char* argv[]) { 28 mRanges.clear(); 29 for (int i = 0; i < argc; ++i) { 30 if (!*argv[i]) { 31 // The UID string is empty. 32 return false; 33 } 34 char* endPtr; 35 uid_t uidStart = strtoul(argv[i], &endPtr, 0); 36 uid_t uidEnd; 37 if (!*endPtr) { 38 // Found a single UID. The range contains just the one UID. 39 uidEnd = uidStart; 40 } else if (*endPtr == '-') { 41 if (!*++endPtr) { 42 // Unexpected end of string. 43 return false; 44 } 45 uidEnd = strtoul(endPtr, &endPtr, 0); 46 if (*endPtr) { 47 // Illegal trailing chars. 48 return false; 49 } 50 if (uidEnd < uidStart) { 51 // Invalid order. 52 return false; 53 } 54 } else { 55 // Not a single uid, not a range. Found some other illegal char. 56 return false; 57 } 58 if (uidStart == INVALID_UID || uidEnd == INVALID_UID) { 59 // Invalid UIDs. 60 return false; 61 } 62 mRanges.push_back(std::pair<uid_t, uid_t>(uidStart, uidEnd)); 63 } 64 std::sort(mRanges.begin(), mRanges.end()); 65 return true; 66} 67 68void UidRanges::add(const UidRanges& other) { 69 auto middle = mRanges.insert(mRanges.end(), other.mRanges.begin(), other.mRanges.end()); 70 std::inplace_merge(mRanges.begin(), middle, mRanges.end()); 71} 72 73void UidRanges::remove(const UidRanges& other) { 74 auto end = std::set_difference(mRanges.begin(), mRanges.end(), other.mRanges.begin(), 75 other.mRanges.end(), mRanges.begin()); 76 mRanges.erase(end, mRanges.end()); 77} 78