OSDN Git Service

su: update CyanogenMod's latest version
[android-x86/system-extras.git] / su / utils.c
1 /*
2 ** Copyright 2012, The CyanogenMod 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 <unistd.h>
18 #include <limits.h>
19 #include <fcntl.h>
20 #include <errno.h>
21 #include <endian.h>
22 #include <ctype.h>
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <cutils/properties.h>
28
29 /* reads a file, making sure it is terminated with \n \0 */
30 char* read_file(const char *fn, unsigned *_sz)
31 {
32     char *data;
33     int sz;
34     int fd;
35
36     data = 0;
37     fd = open(fn, O_RDONLY);
38     if(fd < 0) return 0;
39
40     sz = lseek(fd, 0, SEEK_END);
41     if(sz < 0) goto oops;
42
43     if(lseek(fd, 0, SEEK_SET) != 0) goto oops;
44
45     data = (char*) malloc(sz + 2);
46     if(data == 0) goto oops;
47
48     if(read(fd, data, sz) != sz) goto oops;
49     close(fd);
50     data[sz] = '\n';
51     data[sz+1] = 0;
52     if(_sz) *_sz = sz;
53     return data;
54
55 oops:
56     close(fd);
57     if(data != 0) free(data);
58     return 0;
59 }
60
61 int get_property(const char *data, char *found, const char *searchkey, const char *not_found)
62 {
63     char *key, *value, *eol, *sol, *tmp;
64     if (data == NULL) goto defval;
65     int matched = 0;
66     sol = strdup(data);
67     while((eol = strchr(sol, '\n'))) {
68         key = sol;
69         *eol++ = 0;
70         sol = eol;
71
72         value = strchr(key, '=');
73         if(value == 0) continue;
74         *value++ = 0;
75
76         while(isspace(*key)) key++;
77         if(*key == '#') continue;
78         tmp = value - 2;
79         while((tmp > key) && isspace(*tmp)) *tmp-- = 0;
80
81         while(isspace(*value)) value++;
82         tmp = eol - 2;
83         while((tmp > value) && isspace(*tmp)) *tmp-- = 0;
84
85         if (strncmp(searchkey, key, strlen(searchkey)) == 0) {
86             matched = 1;
87             break;
88         }
89     }
90     int len;
91     if (matched) {
92         len = strlen(value);
93         if (len >= PROPERTY_VALUE_MAX)
94             return -1;
95         memcpy(found, value, len + 1);
96     } else goto defval;
97     return len;
98
99 defval:
100     len = strlen(not_found);
101     memcpy(found, not_found, len + 1);
102     return len;
103 }
104