1/*
2 * Copyright (C) 2007 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 <stdio.h>
18#include <stdlib.h>
19#include <unistd.h>
20#include <string.h>
21#include <ctype.h>
22#include <fcntl.h>
23#include <stdarg.h>
24#include <dirent.h>
25#include <limits.h>
26#include <errno.h>
27
28#include <cutils/misc.h>
29#include <cutils/sockets.h>
30
31#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
32#include <sys/_system_properties.h>
33
34#include <sys/socket.h>
35#include <sys/un.h>
36#include <sys/select.h>
37#include <sys/types.h>
38#include <netinet/in.h>
39#include <sys/mman.h>
40#include <sys/atomics.h>
41#include <private/android_filesystem_config.h>
42
43#include "property_service.h"
44#include "init.h"
45#include "util.h"
46#include "log.h"
47
48#define PERSISTENT_PROPERTY_DIR  "/data/property"
49
50static int persistent_properties_loaded = 0;
51static int property_area_inited = 0;
52
53static int property_set_fd = -1;
54
55/* White list of permissions for setting property services. */
56struct {
57    const char *prefix;
58    unsigned int uid;
59    unsigned int gid;
60} property_perms[] = {
61    { "net.rmnet0.",      AID_RADIO,    0 },
62    { "net.gprs.",        AID_RADIO,    0 },
63    { "net.ppp",          AID_RADIO,    0 },
64    { "ril.",             AID_RADIO,    0 },
65    { "gsm.",             AID_RADIO,    0 },
66    { "persist.radio",    AID_RADIO,    0 },
67    { "net.dns",          AID_RADIO,    0 },
68    { "net.",             AID_SYSTEM,   0 },
69    { "dev.",             AID_SYSTEM,   0 },
70    { "runtime.",         AID_SYSTEM,   0 },
71    { "hw.",              AID_SYSTEM,   0 },
72    { "sys.",             AID_SYSTEM,   0 },
73    { "service.",         AID_SYSTEM,   0 },
74    { "wlan.",            AID_SYSTEM,   0 },
75    { "dhcp.",            AID_SYSTEM,   0 },
76    { "dhcp.",            AID_DHCP,     0 },
77    { "vpn.",             AID_SYSTEM,   0 },
78    { "vpn.",             AID_VPN,      0 },
79    { "debug.",           AID_SHELL,    0 },
80    { "log.",             AID_SHELL,    0 },
81    { "service.adb.root", AID_SHELL,    0 },
82    { "persist.sys.",     AID_SYSTEM,   0 },
83    { "persist.service.", AID_SYSTEM,   0 },
84    { "persist.security.", AID_SYSTEM,   0 },
85    { NULL, 0, 0 }
86};
87
88/*
89 * White list of UID that are allowed to start/stop services.
90 * Currently there are no user apps that require.
91 */
92struct {
93    const char *service;
94    unsigned int uid;
95    unsigned int gid;
96} control_perms[] = {
97    { "dumpstate",AID_SHELL, AID_LOG },
98     {NULL, 0, 0 }
99};
100
101typedef struct {
102    void *data;
103    size_t size;
104    int fd;
105} workspace;
106
107static int init_workspace(workspace *w, size_t size)
108{
109    void *data;
110    int fd;
111
112        /* dev is a tmpfs that we can use to carve a shared workspace
113         * out of, so let's do that...
114         */
115    fd = open("/dev/__properties__", O_RDWR | O_CREAT, 0600);
116    if (fd < 0)
117        return -1;
118
119    if (ftruncate(fd, size) < 0)
120        goto out;
121
122    data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
123    if(data == MAP_FAILED)
124        goto out;
125
126    close(fd);
127
128    fd = open("/dev/__properties__", O_RDONLY);
129    if (fd < 0)
130        return -1;
131
132    unlink("/dev/__properties__");
133
134    w->data = data;
135    w->size = size;
136    w->fd = fd;
137    return 0;
138
139out:
140    close(fd);
141    return -1;
142}
143
144/* (8 header words + 247 toc words) = 1020 bytes */
145/* 1024 bytes header and toc + 247 prop_infos @ 128 bytes = 32640 bytes */
146
147#define PA_COUNT_MAX  247
148#define PA_INFO_START 1024
149#define PA_SIZE       32768
150
151static workspace pa_workspace;
152static prop_info *pa_info_array;
153
154extern prop_area *__system_property_area__;
155
156static int init_property_area(void)
157{
158    prop_area *pa;
159
160    if(pa_info_array)
161        return -1;
162
163    if(init_workspace(&pa_workspace, PA_SIZE))
164        return -1;
165
166    fcntl(pa_workspace.fd, F_SETFD, FD_CLOEXEC);
167
168    pa_info_array = (void*) (((char*) pa_workspace.data) + PA_INFO_START);
169
170    pa = pa_workspace.data;
171    memset(pa, 0, PA_SIZE);
172    pa->magic = PROP_AREA_MAGIC;
173    pa->version = PROP_AREA_VERSION;
174
175        /* plug into the lib property services */
176    __system_property_area__ = pa;
177    property_area_inited = 1;
178    return 0;
179}
180
181static void update_prop_info(prop_info *pi, const char *value, unsigned len)
182{
183    pi->serial = pi->serial | 1;
184    memcpy(pi->value, value, len + 1);
185    pi->serial = (len << 24) | ((pi->serial + 1) & 0xffffff);
186    __futex_wake(&pi->serial, INT32_MAX);
187}
188
189static int property_write(prop_info *pi, const char *value)
190{
191    int valuelen = strlen(value);
192    if(valuelen >= PROP_VALUE_MAX) return -1;
193    update_prop_info(pi, value, valuelen);
194    return 0;
195}
196
197
198/*
199 * Checks permissions for starting/stoping system services.
200 * AID_SYSTEM and AID_ROOT are always allowed.
201 *
202 * Returns 1 if uid allowed, 0 otherwise.
203 */
204static int check_control_perms(const char *name, unsigned int uid, unsigned int gid) {
205    int i;
206    if (uid == AID_SYSTEM || uid == AID_ROOT)
207        return 1;
208
209    /* Search the ACL */
210    for (i = 0; control_perms[i].service; i++) {
211        if (strcmp(control_perms[i].service, name) == 0) {
212            if ((uid && control_perms[i].uid == uid) ||
213                (gid && control_perms[i].gid == gid)) {
214                return 1;
215            }
216        }
217    }
218    return 0;
219}
220
221/*
222 * Checks permissions for setting system properties.
223 * Returns 1 if uid allowed, 0 otherwise.
224 */
225static int check_perms(const char *name, unsigned int uid, unsigned int gid)
226{
227    int i;
228    if (uid == 0)
229        return 1;
230
231    if(!strncmp(name, "ro.", 3))
232        name +=3;
233
234    for (i = 0; property_perms[i].prefix; i++) {
235        int tmp;
236        if (strncmp(property_perms[i].prefix, name,
237                    strlen(property_perms[i].prefix)) == 0) {
238            if ((uid && property_perms[i].uid == uid) ||
239                (gid && property_perms[i].gid == gid)) {
240                return 1;
241            }
242        }
243    }
244
245    return 0;
246}
247
248const char* property_get(const char *name)
249{
250    prop_info *pi;
251
252    if(strlen(name) >= PROP_NAME_MAX) return 0;
253
254    pi = (prop_info*) __system_property_find(name);
255
256    if(pi != 0) {
257        return pi->value;
258    } else {
259        return 0;
260    }
261}
262
263static void write_persistent_property(const char *name, const char *value)
264{
265    const char *tempPath = PERSISTENT_PROPERTY_DIR "/.temp";
266    char path[PATH_MAX];
267    int fd, length;
268
269    snprintf(path, sizeof(path), "%s/%s", PERSISTENT_PROPERTY_DIR, name);
270
271    fd = open(tempPath, O_WRONLY|O_CREAT|O_TRUNC, 0600);
272    if (fd < 0) {
273        ERROR("Unable to write persistent property to temp file %s errno: %d\n", tempPath, errno);
274        return;
275    }
276    write(fd, value, strlen(value));
277    close(fd);
278
279    if (rename(tempPath, path)) {
280        unlink(tempPath);
281        ERROR("Unable to rename persistent property file %s to %s\n", tempPath, path);
282    }
283}
284
285int property_set(const char *name, const char *value)
286{
287    prop_area *pa;
288    prop_info *pi;
289
290    int namelen = strlen(name);
291    int valuelen = strlen(value);
292
293    if(namelen >= PROP_NAME_MAX) return -1;
294    if(valuelen >= PROP_VALUE_MAX) return -1;
295    if(namelen < 1) return -1;
296
297    pi = (prop_info*) __system_property_find(name);
298
299    if(pi != 0) {
300        /* ro.* properties may NEVER be modified once set */
301        if(!strncmp(name, "ro.", 3)) return -1;
302
303        pa = __system_property_area__;
304        update_prop_info(pi, value, valuelen);
305        pa->serial++;
306        __futex_wake(&pa->serial, INT32_MAX);
307    } else {
308        pa = __system_property_area__;
309        if(pa->count == PA_COUNT_MAX) return -1;
310
311        pi = pa_info_array + pa->count;
312        pi->serial = (valuelen << 24);
313        memcpy(pi->name, name, namelen + 1);
314        memcpy(pi->value, value, valuelen + 1);
315
316        pa->toc[pa->count] =
317            (namelen << 24) | (((unsigned) pi) - ((unsigned) pa));
318
319        pa->count++;
320        pa->serial++;
321        __futex_wake(&pa->serial, INT32_MAX);
322    }
323    /* If name starts with "net." treat as a DNS property. */
324    if (strncmp("net.", name, strlen("net.")) == 0)  {
325        if (strcmp("net.change", name) == 0) {
326            return 0;
327        }
328       /*
329        * The 'net.change' property is a special property used track when any
330        * 'net.*' property name is updated. It is _ONLY_ updated here. Its value
331        * contains the last updated 'net.*' property.
332        */
333        property_set("net.change", name);
334    } else if (persistent_properties_loaded &&
335            strncmp("persist.", name, strlen("persist.")) == 0) {
336        /*
337         * Don't write properties to disk until after we have read all default properties
338         * to prevent them from being overwritten by default values.
339         */
340        write_persistent_property(name, value);
341    }
342    property_changed(name, value);
343    return 0;
344}
345
346static int property_list(void (*propfn)(const char *key, const char *value, void *cookie),
347                  void *cookie)
348{
349    char name[PROP_NAME_MAX];
350    char value[PROP_VALUE_MAX];
351    const prop_info *pi;
352    unsigned n;
353
354    for(n = 0; (pi = __system_property_find_nth(n)); n++) {
355        __system_property_read(pi, name, value);
356        propfn(name, value, cookie);
357    }
358    return 0;
359}
360
361void handle_property_set_fd()
362{
363    prop_msg msg;
364    int s;
365    int r;
366    int res;
367    struct ucred cr;
368    struct sockaddr_un addr;
369    socklen_t addr_size = sizeof(addr);
370    socklen_t cr_size = sizeof(cr);
371
372    if ((s = accept(property_set_fd, (struct sockaddr *) &addr, &addr_size)) < 0) {
373        return;
374    }
375
376    /* Check socket options here */
377    if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
378        close(s);
379        ERROR("Unable to recieve socket options\n");
380        return;
381    }
382
383    r = recv(s, &msg, sizeof(msg), 0);
384    close(s);
385    if(r != sizeof(prop_msg)) {
386        ERROR("sys_prop: mis-match msg size recieved: %d expected: %d\n",
387              r, sizeof(prop_msg));
388        return;
389    }
390
391    switch(msg.cmd) {
392    case PROP_MSG_SETPROP:
393        msg.name[PROP_NAME_MAX-1] = 0;
394        msg.value[PROP_VALUE_MAX-1] = 0;
395
396        if(memcmp(msg.name,"ctl.",4) == 0) {
397            if (check_control_perms(msg.value, cr.uid, cr.gid)) {
398                handle_control_message((char*) msg.name + 4, (char*) msg.value);
399            } else {
400                ERROR("sys_prop: Unable to %s service ctl [%s] uid: %d pid:%d\n",
401                        msg.name + 4, msg.value, cr.uid, cr.pid);
402            }
403        } else {
404            if (check_perms(msg.name, cr.uid, cr.gid)) {
405                property_set((char*) msg.name, (char*) msg.value);
406            } else {
407                ERROR("sys_prop: permission denied uid:%d  name:%s\n",
408                      cr.uid, msg.name);
409            }
410        }
411        break;
412
413    default:
414        break;
415    }
416}
417
418void get_property_workspace(int *fd, int *sz)
419{
420    *fd = pa_workspace.fd;
421    *sz = pa_workspace.size;
422}
423
424static void load_properties(char *data)
425{
426    char *key, *value, *eol, *sol, *tmp;
427
428    sol = data;
429    while((eol = strchr(sol, '\n'))) {
430        key = sol;
431        *eol++ = 0;
432        sol = eol;
433
434        value = strchr(key, '=');
435        if(value == 0) continue;
436        *value++ = 0;
437
438        while(isspace(*key)) key++;
439        if(*key == '#') continue;
440        tmp = value - 2;
441        while((tmp > key) && isspace(*tmp)) *tmp-- = 0;
442
443        while(isspace(*value)) value++;
444        tmp = eol - 2;
445        while((tmp > value) && isspace(*tmp)) *tmp-- = 0;
446
447        property_set(key, value);
448    }
449}
450
451static void load_properties_from_file(const char *fn)
452{
453    char *data;
454    unsigned sz;
455
456    data = read_file(fn, &sz);
457
458    if(data != 0) {
459        load_properties(data);
460        free(data);
461    }
462}
463
464static void load_persistent_properties()
465{
466    DIR* dir = opendir(PERSISTENT_PROPERTY_DIR);
467    struct dirent*  entry;
468    char path[PATH_MAX];
469    char value[PROP_VALUE_MAX];
470    int fd, length;
471
472    if (dir) {
473        while ((entry = readdir(dir)) != NULL) {
474            if (strncmp("persist.", entry->d_name, strlen("persist.")))
475                continue;
476#if HAVE_DIRENT_D_TYPE
477            if (entry->d_type != DT_REG)
478                continue;
479#endif
480            /* open the file and read the property value */
481            snprintf(path, sizeof(path), "%s/%s", PERSISTENT_PROPERTY_DIR, entry->d_name);
482            fd = open(path, O_RDONLY);
483            if (fd >= 0) {
484                length = read(fd, value, sizeof(value) - 1);
485                if (length >= 0) {
486                    value[length] = 0;
487                    property_set(entry->d_name, value);
488                } else {
489                    ERROR("Unable to read persistent property file %s errno: %d\n", path, errno);
490                }
491                close(fd);
492            } else {
493                ERROR("Unable to open persistent property file %s errno: %d\n", path, errno);
494            }
495        }
496        closedir(dir);
497    } else {
498        ERROR("Unable to open persistent property directory %s errno: %d\n", PERSISTENT_PROPERTY_DIR, errno);
499    }
500
501    persistent_properties_loaded = 1;
502}
503
504void property_init(void)
505{
506    init_property_area();
507    load_properties_from_file(PROP_PATH_RAMDISK_DEFAULT);
508}
509
510int properties_inited(void)
511{
512    return property_area_inited;
513}
514
515void start_property_service(void)
516{
517    int fd;
518
519    load_properties_from_file(PROP_PATH_SYSTEM_BUILD);
520    load_properties_from_file(PROP_PATH_SYSTEM_DEFAULT);
521    load_properties_from_file(PROP_PATH_LOCAL_OVERRIDE);
522    /* Read persistent properties after all default values have been loaded. */
523    load_persistent_properties();
524
525    fd = create_socket(PROP_SERVICE_NAME, SOCK_STREAM, 0666, 0, 0);
526    if(fd < 0) return;
527    fcntl(fd, F_SETFD, FD_CLOEXEC);
528    fcntl(fd, F_SETFL, O_NONBLOCK);
529
530    listen(fd, 8);
531    property_set_fd = fd;
532}
533
534int get_property_set_fd()
535{
536    return property_set_fd;
537}
538