1 // 2 // Copyright 2016 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 #define LOG_TAG "properties" 18 19 #include <ctype.h> 20 #include <stdbool.h> 21 #include <stdlib.h> 22 #include <string.h> 23 #include <unistd.h> 24 25 #include <cutils/properties.h> 26 #include <log/log.h> 27 28 static const int MAX_PROPERTIES = 5; 29 30 struct property { 31 char key[PROP_KEY_MAX + 2]; 32 char value[PROP_VALUE_MAX + 2]; 33 }; 34 35 int num_properties = 0; 36 struct property properties[MAX_PROPERTIES]; 37 38 // Find the correct entry. 39 static int property_find(const char *key) { 40 for (int i = 0; i < num_properties; i++) { 41 if (strncmp(properties[i].key, key, PROP_KEY_MAX) == 0) { 42 return i; 43 } 44 } 45 return MAX_PROPERTIES; 46 } 47 48 int property_set(const char *key, const char *value) { 49 if (strnlen(value, PROP_VALUE_MAX) > PROP_VALUE_MAX) return -1; 50 51 // Check to see if the property exists. 52 int prop_index = property_find(key); 53 54 if (prop_index == MAX_PROPERTIES) { 55 if (num_properties >= MAX_PROPERTIES) return -1; 56 prop_index = num_properties; 57 num_properties += 1; 58 } 59 60 // This is test code. Be nice and don't push the boundary cases! 61 strncpy(properties[prop_index].key, key, PROP_KEY_MAX + 1); 62 strncpy(properties[prop_index].value, value, PROP_VALUE_MAX + 1); 63 return 0; 64 } 65 66 int property_get(const char *key, char *value, const char *default_value) { 67 // This doesn't mock the behavior of default value 68 if (default_value != NULL) ALOGE("%s: default_value is ignored!", __func__); 69 70 // Check to see if the property exists. 71 int prop_index = property_find(key); 72 73 if (prop_index == MAX_PROPERTIES) return 0; 74 75 int len = strlen(properties[prop_index].value); 76 memcpy(value, properties[prop_index].value, len); 77 value[len] = '\0'; 78 return len; 79 } 80