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