util.c revision 8348d279c7ce1a2453965ba7f05a7b818d58886c
1/*
2 * Copyright (C) 2008 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 <stdarg.h>
18#include <stdlib.h>
19#include <stdio.h>
20#include <string.h>
21#include <fcntl.h>
22#include <ctype.h>
23#include <errno.h>
24#include <time.h>
25
26#include <selinux/label.h>
27
28#include <sys/stat.h>
29#include <sys/types.h>
30#include <sys/socket.h>
31#include <sys/un.h>
32
33/* for ANDROID_SOCKET_* */
34#include <cutils/sockets.h>
35
36#include <private/android_filesystem_config.h>
37
38#include "init.h"
39#include "log.h"
40#include "util.h"
41
42/*
43 * android_name_to_id - returns the integer uid/gid associated with the given
44 * name, or -1U on error.
45 */
46static unsigned int android_name_to_id(const char *name)
47{
48    const struct android_id_info *info = android_ids;
49    unsigned int n;
50
51    for (n = 0; n < android_id_count; n++) {
52        if (!strcmp(info[n].name, name))
53            return info[n].aid;
54    }
55
56    return -1U;
57}
58
59/*
60 * decode_uid - decodes and returns the given string, which can be either the
61 * numeric or name representation, into the integer uid or gid. Returns -1U on
62 * error.
63 */
64unsigned int decode_uid(const char *s)
65{
66    unsigned int v;
67
68    if (!s || *s == '\0')
69        return -1U;
70    if (isalpha(s[0]))
71        return android_name_to_id(s);
72
73    errno = 0;
74    v = (unsigned int) strtoul(s, 0, 0);
75    if (errno)
76        return -1U;
77    return v;
78}
79
80/*
81 * create_socket - creates a Unix domain socket in ANDROID_SOCKET_DIR
82 * ("/dev/socket") as dictated in init.rc. This socket is inherited by the
83 * daemon. We communicate the file descriptor's value via the environment
84 * variable ANDROID_SOCKET_ENV_PREFIX<name> ("ANDROID_SOCKET_foo").
85 */
86int create_socket(const char *name, int type, mode_t perm, uid_t uid,
87                  gid_t gid, const char *socketcon)
88{
89    struct sockaddr_un addr;
90    int fd, ret;
91    char *filecon;
92
93    if (socketcon)
94        setsockcreatecon(socketcon);
95
96    fd = socket(PF_UNIX, type, 0);
97    if (fd < 0) {
98        ERROR("Failed to open socket '%s': %s\n", name, strerror(errno));
99        return -1;
100    }
101
102    if (socketcon)
103        setsockcreatecon(NULL);
104
105    memset(&addr, 0 , sizeof(addr));
106    addr.sun_family = AF_UNIX;
107    snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR"/%s",
108             name);
109
110    ret = unlink(addr.sun_path);
111    if (ret != 0 && errno != ENOENT) {
112        ERROR("Failed to unlink old socket '%s': %s\n", name, strerror(errno));
113        goto out_close;
114    }
115
116    filecon = NULL;
117    if (sehandle) {
118        ret = selabel_lookup(sehandle, &filecon, addr.sun_path, S_IFSOCK);
119        if (ret == 0)
120            setfscreatecon(filecon);
121    }
122
123    ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr));
124    if (ret) {
125        ERROR("Failed to bind socket '%s': %s\n", name, strerror(errno));
126        goto out_unlink;
127    }
128
129    setfscreatecon(NULL);
130    freecon(filecon);
131
132    chown(addr.sun_path, uid, gid);
133    chmod(addr.sun_path, perm);
134
135    INFO("Created socket '%s' with mode '%o', user '%d', group '%d'\n",
136         addr.sun_path, perm, uid, gid);
137
138    return fd;
139
140out_unlink:
141    unlink(addr.sun_path);
142out_close:
143    close(fd);
144    return -1;
145}
146
147/* reads a file, making sure it is terminated with \n \0 */
148void *read_file(const char *fn, unsigned *_sz)
149{
150    char *data;
151    int sz;
152    int fd;
153    struct stat sb;
154
155    data = 0;
156    fd = open(fn, O_RDONLY);
157    if(fd < 0) return 0;
158
159    // for security reasons, disallow world-writable
160    // or group-writable files
161    if (fstat(fd, &sb) < 0) {
162        ERROR("fstat failed for '%s'\n", fn);
163        goto oops;
164    }
165    if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
166        ERROR("skipping insecure file '%s'\n", fn);
167        goto oops;
168    }
169
170    sz = lseek(fd, 0, SEEK_END);
171    if(sz < 0) goto oops;
172
173    if(lseek(fd, 0, SEEK_SET) != 0) goto oops;
174
175    data = (char*) malloc(sz + 2);
176    if(data == 0) goto oops;
177
178    if(read(fd, data, sz) != sz) goto oops;
179    close(fd);
180    data[sz] = '\n';
181    data[sz+1] = 0;
182    if(_sz) *_sz = sz;
183    return data;
184
185oops:
186    close(fd);
187    if(data != 0) free(data);
188    return 0;
189}
190
191#define MAX_MTD_PARTITIONS 16
192
193static struct {
194    char name[16];
195    int number;
196} mtd_part_map[MAX_MTD_PARTITIONS];
197
198static int mtd_part_count = -1;
199
200static void find_mtd_partitions(void)
201{
202    int fd;
203    char buf[1024];
204    char *pmtdbufp;
205    ssize_t pmtdsize;
206    int r;
207
208    fd = open("/proc/mtd", O_RDONLY);
209    if (fd < 0)
210        return;
211
212    buf[sizeof(buf) - 1] = '\0';
213    pmtdsize = read(fd, buf, sizeof(buf) - 1);
214    pmtdbufp = buf;
215    while (pmtdsize > 0) {
216        int mtdnum, mtdsize, mtderasesize;
217        char mtdname[16];
218        mtdname[0] = '\0';
219        mtdnum = -1;
220        r = sscanf(pmtdbufp, "mtd%d: %x %x %15s",
221                   &mtdnum, &mtdsize, &mtderasesize, mtdname);
222        if ((r == 4) && (mtdname[0] == '"')) {
223            char *x = strchr(mtdname + 1, '"');
224            if (x) {
225                *x = 0;
226            }
227            INFO("mtd partition %d, %s\n", mtdnum, mtdname + 1);
228            if (mtd_part_count < MAX_MTD_PARTITIONS) {
229                strcpy(mtd_part_map[mtd_part_count].name, mtdname + 1);
230                mtd_part_map[mtd_part_count].number = mtdnum;
231                mtd_part_count++;
232            } else {
233                ERROR("too many mtd partitions\n");
234            }
235        }
236        while (pmtdsize > 0 && *pmtdbufp != '\n') {
237            pmtdbufp++;
238            pmtdsize--;
239        }
240        if (pmtdsize > 0) {
241            pmtdbufp++;
242            pmtdsize--;
243        }
244    }
245    close(fd);
246}
247
248int mtd_name_to_number(const char *name)
249{
250    int n;
251    if (mtd_part_count < 0) {
252        mtd_part_count = 0;
253        find_mtd_partitions();
254    }
255    for (n = 0; n < mtd_part_count; n++) {
256        if (!strcmp(name, mtd_part_map[n].name)) {
257            return mtd_part_map[n].number;
258        }
259    }
260    return -1;
261}
262
263/*
264 * gettime() - returns the time in seconds of the system's monotonic clock or
265 * zero on error.
266 */
267time_t gettime(void)
268{
269    struct timespec ts;
270    int ret;
271
272    ret = clock_gettime(CLOCK_MONOTONIC, &ts);
273    if (ret < 0) {
274        ERROR("clock_gettime(CLOCK_MONOTONIC) failed: %s\n", strerror(errno));
275        return 0;
276    }
277
278    return ts.tv_sec;
279}
280
281int mkdir_recursive(const char *pathname, mode_t mode)
282{
283    char buf[128];
284    const char *slash;
285    const char *p = pathname;
286    int width;
287    int ret;
288    struct stat info;
289
290    while ((slash = strchr(p, '/')) != NULL) {
291        width = slash - pathname;
292        p = slash + 1;
293        if (width < 0)
294            break;
295        if (width == 0)
296            continue;
297        if ((unsigned int)width > sizeof(buf) - 1) {
298            ERROR("path too long for mkdir_recursive\n");
299            return -1;
300        }
301        memcpy(buf, pathname, width);
302        buf[width] = 0;
303        if (stat(buf, &info) != 0) {
304            ret = make_dir(buf, mode);
305            if (ret && errno != EEXIST)
306                return ret;
307        }
308    }
309    ret = make_dir(pathname, mode);
310    if (ret && errno != EEXIST)
311        return ret;
312    return 0;
313}
314
315/*
316 * replaces any unacceptable characters with '_', the
317 * length of the resulting string is equal to the input string
318 */
319void sanitize(char *s)
320{
321    const char* accept =
322            "abcdefghijklmnopqrstuvwxyz"
323            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
324            "0123456789"
325            "_-.";
326
327    if (!s)
328        return;
329
330    for (; *s; s++) {
331        s += strspn(s, accept);
332        if (*s) *s = '_';
333    }
334}
335
336void make_link(const char *oldpath, const char *newpath)
337{
338    int ret;
339    char buf[256];
340    char *slash;
341    int width;
342
343    slash = strrchr(newpath, '/');
344    if (!slash)
345        return;
346    width = slash - newpath;
347    if (width <= 0 || width > (int)sizeof(buf) - 1)
348        return;
349    memcpy(buf, newpath, width);
350    buf[width] = 0;
351    ret = mkdir_recursive(buf, 0755);
352    if (ret)
353        ERROR("Failed to create directory %s: %s (%d)\n", buf, strerror(errno), errno);
354
355    ret = symlink(oldpath, newpath);
356    if (ret && errno != EEXIST)
357        ERROR("Failed to symlink %s to %s: %s (%d)\n", oldpath, newpath, strerror(errno), errno);
358}
359
360void remove_link(const char *oldpath, const char *newpath)
361{
362    char path[256];
363    ssize_t ret;
364    ret = readlink(newpath, path, sizeof(path) - 1);
365    if (ret <= 0)
366        return;
367    path[ret] = 0;
368    if (!strcmp(path, oldpath))
369        unlink(newpath);
370}
371
372int wait_for_file(const char *filename, int timeout)
373{
374    struct stat info;
375    time_t timeout_time = gettime() + timeout;
376    int ret = -1;
377
378    while (gettime() < timeout_time && ((ret = stat(filename, &info)) < 0))
379        usleep(10000);
380
381    return ret;
382}
383
384void open_devnull_stdio(void)
385{
386    int fd;
387    static const char *name = "/dev/__null__";
388    if (mknod(name, S_IFCHR | 0600, (1 << 8) | 3) == 0) {
389        fd = open(name, O_RDWR);
390        unlink(name);
391        if (fd >= 0) {
392            dup2(fd, 0);
393            dup2(fd, 1);
394            dup2(fd, 2);
395            if (fd > 2) {
396                close(fd);
397            }
398            return;
399        }
400    }
401
402    exit(1);
403}
404
405void get_hardware_name(char *hardware, unsigned int *revision)
406{
407    char data[1024];
408    int fd, n;
409    char *x, *hw, *rev;
410
411    /* Hardware string was provided on kernel command line */
412    if (hardware[0])
413        return;
414
415    fd = open("/proc/cpuinfo", O_RDONLY);
416    if (fd < 0) return;
417
418    n = read(fd, data, 1023);
419    close(fd);
420    if (n < 0) return;
421
422    data[n] = 0;
423    hw = strstr(data, "\nHardware");
424    rev = strstr(data, "\nRevision");
425
426    if (hw) {
427        x = strstr(hw, ": ");
428        if (x) {
429            x += 2;
430            n = 0;
431            while (*x && *x != '\n') {
432                if (!isspace(*x))
433                    hardware[n++] = tolower(*x);
434                x++;
435                if (n == 31) break;
436            }
437            hardware[n] = 0;
438        }
439    }
440
441    if (rev) {
442        x = strstr(rev, ": ");
443        if (x) {
444            *revision = strtoul(x + 2, 0, 16);
445        }
446    }
447}
448
449void import_kernel_cmdline(int in_qemu,
450                           void (*import_kernel_nv)(char *name, int in_qemu))
451{
452    char cmdline[1024];
453    char *ptr;
454    int fd;
455
456    fd = open("/proc/cmdline", O_RDONLY);
457    if (fd >= 0) {
458        int n = read(fd, cmdline, 1023);
459        if (n < 0) n = 0;
460
461        /* get rid of trailing newline, it happens */
462        if (n > 0 && cmdline[n-1] == '\n') n--;
463
464        cmdline[n] = 0;
465        close(fd);
466    } else {
467        cmdline[0] = 0;
468    }
469
470    ptr = cmdline;
471    while (ptr && *ptr) {
472        char *x = strchr(ptr, ' ');
473        if (x != 0) *x++ = 0;
474        import_kernel_nv(ptr, in_qemu);
475        ptr = x;
476    }
477}
478
479int make_dir(const char *path, mode_t mode)
480{
481    int rc;
482
483    char *secontext = NULL;
484
485    if (sehandle) {
486        selabel_lookup(sehandle, &secontext, path, mode);
487        setfscreatecon(secontext);
488    }
489
490    rc = mkdir(path, mode);
491
492    if (secontext) {
493        int save_errno = errno;
494        freecon(secontext);
495        setfscreatecon(NULL);
496        errno = save_errno;
497    }
498
499    return rc;
500}
501
502int restorecon(const char *pathname)
503{
504    char *secontext = NULL;
505    struct stat sb;
506    int i;
507
508    if (is_selinux_enabled() <= 0 || !sehandle)
509        return 0;
510
511    if (lstat(pathname, &sb) < 0)
512        return -errno;
513    if (selabel_lookup(sehandle, &secontext, pathname, sb.st_mode) < 0)
514        return -errno;
515    if (lsetfilecon(pathname, secontext) < 0) {
516        freecon(secontext);
517        return -errno;
518    }
519    freecon(secontext);
520    return 0;
521}
522