1 /* 2 * Copyright (C) 2023 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 "./string-utils.h" 18 19 #include <errno.h> 20 #include <stdlib.h> 21 #include <string.h> 22 23 namespace shell_as { 24 StringToUInt32(const char * s,uint32_t * i)25 bool StringToUInt32(const char* s, uint32_t* i) { 26 uint64_t value = 0; 27 if (!StringToUInt64(s, &value)) { 28 return false; 29 } 30 if (value > UINT_MAX) { 31 return false; 32 } 33 *i = value; 34 return true; 35 } 36 StringToUInt64(const char * s,uint64_t * i)37 bool StringToUInt64(const char* s, uint64_t* i) { 38 char* endptr = nullptr; 39 // Reset errno to a non-error value since strtoul does not clear errno. 40 errno = 0; 41 *i = strtoul(s, &endptr, 10); 42 // strtoul will return 0 if the value cannot be parsed as an unsigned long. If 43 // this occurs, ensure that the ID actually was zero. This is done by ensuring 44 // that the end pointer was advanced and that it now points to the end of the 45 // string (a null byte). 46 return errno == 0 && (*i != 0 || (endptr != s && *endptr == '\0')); 47 } 48 SplitIdsAndSkip(char * line,const char * separators,int num_to_skip,std::vector<uid_t> * ids)49 bool SplitIdsAndSkip(char* line, const char* separators, int num_to_skip, 50 std::vector<uid_t>* ids) { 51 if (line == nullptr) { 52 return false; 53 } 54 55 ids->clear(); 56 for (char* id_string = strtok(line, separators); id_string != nullptr; 57 id_string = strtok(nullptr, separators)) { 58 if (num_to_skip > 0) { 59 num_to_skip--; 60 continue; 61 } 62 63 gid_t id; 64 if (!StringToUInt32(id_string, &id)) { 65 return false; 66 } 67 ids->push_back(id); 68 } 69 return true; 70 } 71 72 } // namespace shell_as 73