devices.c revision fc0182eb1db0620eb71fb6ca219b15a17dcd912f
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 <errno.h>
18#include <stdio.h>
19#include <stdlib.h>
20#include <sys/stat.h>
21#include <sys/types.h>
22
23#include <fcntl.h>
24#include <dirent.h>
25#include <unistd.h>
26#include <string.h>
27
28#include <sys/socket.h>
29#include <sys/un.h>
30#include <linux/netlink.h>
31#include <private/android_filesystem_config.h>
32#include <sys/time.h>
33#include <asm/page.h>
34
35#include "init.h"
36#include "devices.h"
37
38#define CMDLINE_PREFIX  "/dev"
39#define SYSFS_PREFIX    "/sys"
40#define FIRMWARE_DIR    "/etc/firmware"
41#define MAX_QEMU_PERM 6
42
43struct uevent {
44    const char *action;
45    const char *path;
46    const char *subsystem;
47    const char *firmware;
48    int major;
49    int minor;
50};
51
52static int open_uevent_socket(void)
53{
54    struct sockaddr_nl addr;
55    int sz = 64*1024; // XXX larger? udev uses 16MB!
56    int s;
57
58    memset(&addr, 0, sizeof(addr));
59    addr.nl_family = AF_NETLINK;
60    addr.nl_pid = getpid();
61    addr.nl_groups = 0xffffffff;
62
63    s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
64    if(s < 0)
65        return -1;
66
67    setsockopt(s, SOL_SOCKET, SO_RCVBUFFORCE, &sz, sizeof(sz));
68
69    if(bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
70        close(s);
71        return -1;
72    }
73
74    return s;
75}
76
77struct perms_ {
78    char *name;
79    mode_t perm;
80    unsigned int uid;
81    unsigned int gid;
82    unsigned short prefix;
83};
84static struct perms_ devperms[] = {
85    { "/dev/null",          0666,   AID_ROOT,       AID_ROOT,       0 },
86    { "/dev/zero",          0666,   AID_ROOT,       AID_ROOT,       0 },
87    { "/dev/full",          0666,   AID_ROOT,       AID_ROOT,       0 },
88    { "/dev/ptmx",          0666,   AID_ROOT,       AID_ROOT,       0 },
89    { "/dev/tty",           0666,   AID_ROOT,       AID_ROOT,       0 },
90    { "/dev/random",        0666,   AID_ROOT,       AID_ROOT,       0 },
91    { "/dev/urandom",       0666,   AID_ROOT,       AID_ROOT,       0 },
92    { "/dev/ashmem",        0666,   AID_ROOT,       AID_ROOT,       0 },
93    { "/dev/binder",        0666,   AID_ROOT,       AID_ROOT,       0 },
94
95	    /* logger should be world writable (for logging) but not readable */
96    { "/dev/log/",          0662,   AID_ROOT,       AID_LOG,        1 },
97
98        /* these should not be world writable */
99    { "/dev/android_adb",   0660,   AID_ADB,        AID_ADB,        0 },
100    { "/dev/android_adb_enable",   0660,   AID_ADB,        AID_ADB,        0 },
101    { "/dev/ttyMSM0",       0600,   AID_BLUETOOTH,  AID_BLUETOOTH,  0 },
102    { "/dev/ttyHS0",        0600,   AID_BLUETOOTH,  AID_BLUETOOTH,  0 },
103    { "/dev/uinput",        0600,   AID_BLUETOOTH,  AID_BLUETOOTH,  0 },
104    { "/dev/alarm",         0664,   AID_SYSTEM,     AID_RADIO,      0 },
105    { "/dev/tty0",          0660,   AID_ROOT,       AID_SYSTEM,     0 },
106    { "/dev/graphics/",     0660,   AID_ROOT,       AID_GRAPHICS,   1 },
107    { "/dev/hw3d",          0660,   AID_SYSTEM,     AID_GRAPHICS,   0 },
108    { "/dev/input/",        0660,   AID_ROOT,       AID_INPUT,      1 },
109    { "/dev/eac",           0660,   AID_ROOT,       AID_AUDIO,      0 },
110    { "/dev/cam",           0660,   AID_ROOT,       AID_CAMERA,     0 },
111    { "/dev/pmem",          0660,   AID_SYSTEM,     AID_GRAPHICS,   0 },
112    { "/dev/pmem_gpu",      0660,   AID_SYSTEM,     AID_GRAPHICS,   1 },
113    { "/dev/pmem_adsp",     0660,   AID_SYSTEM,     AID_AUDIO,      1 },
114    { "/dev/pmem_camera",   0660,   AID_SYSTEM,     AID_CAMERA,     1 },
115    { "/dev/oncrpc/",       0660,   AID_ROOT,       AID_SYSTEM,     1 },
116    { "/dev/adsp/",         0660,   AID_SYSTEM,     AID_AUDIO,      1 },
117    { "/dev/mt9t013",       0660,   AID_SYSTEM,     AID_SYSTEM,     0 },
118    { "/dev/msm_camera/",   0660,   AID_SYSTEM,     AID_SYSTEM,     1 },
119    { "/dev/akm8976_daemon",0640,   AID_COMPASS,    AID_SYSTEM,     0 },
120    { "/dev/akm8976_aot",   0640,   AID_COMPASS,    AID_SYSTEM,     0 },
121    { "/dev/akm8976_pffd",  0640,   AID_COMPASS,    AID_SYSTEM,     0 },
122    { "/dev/msm_pcm_out",   0660,   AID_SYSTEM,     AID_AUDIO,      1 },
123    { "/dev/msm_pcm_in",    0660,   AID_SYSTEM,     AID_AUDIO,      1 },
124    { "/dev/msm_pcm_ctl",   0660,   AID_SYSTEM,     AID_AUDIO,      1 },
125    { "/dev/msm_snd",       0660,   AID_SYSTEM,     AID_AUDIO,      1 },
126    { "/dev/msm_mp3",       0660,   AID_SYSTEM,     AID_AUDIO,      1 },
127    { "/dev/msm_audpre",    0660,   AID_SYSTEM,     AID_AUDIO,      0 },
128    { "/dev/htc-acoustic",  0660,   AID_SYSTEM,     AID_AUDIO,      0 },
129    { "/dev/smd0",          0640,   AID_RADIO,      AID_RADIO,      0 },
130    { "/dev/qemu_trace",    0666,   AID_SYSTEM,     AID_SYSTEM,     0 },
131    { "/dev/qmi",           0640,   AID_RADIO,      AID_RADIO,      0 },
132    { "/dev/qmi0",          0640,   AID_RADIO,      AID_RADIO,      0 },
133    { "/dev/qmi1",          0640,   AID_RADIO,      AID_RADIO,      0 },
134    { "/dev/qmi2",          0640,   AID_RADIO,      AID_RADIO,      0 },
135    { "/dev/tun",           0640,   AID_VPN  ,      AID_VPN,        0 },
136    { NULL, 0, 0, 0, 0 },
137};
138
139/* devperms_partners list and perm_node are for hardware specific /dev entries */
140struct perm_node {
141    struct perms_ dp;
142    struct listnode plist;
143};
144list_declare(devperms_partners);
145
146/*
147 * Permission override when in emulator mode, must be parsed before
148 * system properties is initalized.
149 */
150static int qemu_perm_count;
151static struct perms_ qemu_perms[MAX_QEMU_PERM + 1];
152
153int add_devperms_partners(const char *name, mode_t perm, unsigned int uid,
154                        unsigned int gid, unsigned short prefix) {
155    int size;
156    struct perm_node *node = malloc(sizeof (struct perm_node));
157    if (!node)
158        return -ENOMEM;
159
160    size = strlen(name) + 1;
161    if ((node->dp.name = malloc(size)) == NULL)
162        return -ENOMEM;
163
164    memcpy(node->dp.name, name, size);
165    node->dp.perm = perm;
166    node->dp.uid = uid;
167    node->dp.gid = gid;
168    node->dp.prefix = prefix;
169
170    list_add_tail(&devperms_partners, &node->plist);
171    return 0;
172}
173
174void qemu_init(void) {
175    qemu_perm_count = 0;
176    memset(&qemu_perms, 0, sizeof(qemu_perms));
177}
178
179static int qemu_perm(const char* name, mode_t perm, unsigned int uid,
180                         unsigned int gid, unsigned short prefix)
181{
182    char *buf;
183    if (qemu_perm_count == MAX_QEMU_PERM)
184        return -ENOSPC;
185
186    buf = malloc(strlen(name) + 1);
187    if (!buf)
188        return -errno;
189
190    strlcpy(buf, name, strlen(name) + 1);
191    qemu_perms[qemu_perm_count].name = buf;
192    qemu_perms[qemu_perm_count].perm = perm;
193    qemu_perms[qemu_perm_count].uid = uid;
194    qemu_perms[qemu_perm_count].gid = gid;
195    qemu_perms[qemu_perm_count].prefix = prefix;
196
197    qemu_perm_count++;
198    return 0;
199}
200
201/* Permission overrides for emulator that are parsed from /proc/cmdline. */
202void qemu_cmdline(const char* name, const char *value)
203{
204    char *buf;
205    if (!strcmp(name, "android.ril")) {
206        /* cmd line params currently assume /dev/ prefix */
207        if (asprintf(&buf, CMDLINE_PREFIX"/%s", value) == -1) {
208            return;
209        }
210        INFO("nani- buf:: %s\n", buf);
211        qemu_perm(buf, 0660, AID_RADIO, AID_ROOT, 0);
212    }
213}
214
215static int get_device_perm_inner(struct perms_ *perms, const char *path,
216                                    unsigned *uid, unsigned *gid, mode_t *perm)
217{
218    int i;
219    for(i = 0; perms[i].name; i++) {
220
221        if(perms[i].prefix) {
222            if(strncmp(path, perms[i].name, strlen(perms[i].name)))
223                continue;
224        } else {
225            if(strcmp(path, perms[i].name))
226                continue;
227        }
228        *uid = perms[i].uid;
229        *gid = perms[i].gid;
230        *perm = perms[i].perm;
231        return 0;
232    }
233    return -1;
234}
235
236/* First checks for emulator specific permissions specified in /proc/cmdline. */
237static mode_t get_device_perm(const char *path, unsigned *uid, unsigned *gid)
238{
239    mode_t perm;
240
241    if (get_device_perm_inner(qemu_perms, path, uid, gid, &perm) == 0) {
242        return perm;
243    } else if (get_device_perm_inner(devperms, path, uid, gid, &perm) == 0) {
244        return perm;
245    } else {
246        struct listnode *node;
247        struct perm_node *perm_node;
248        struct perms_ *dp;
249
250        /* Check partners list. */
251        list_for_each(node, &devperms_partners) {
252            perm_node = node_to_item(node, struct perm_node, plist);
253            dp = &perm_node->dp;
254
255            if (dp->prefix) {
256                if (strncmp(path, dp->name, strlen(dp->name)))
257                    continue;
258            } else {
259                if (strcmp(path, dp->name))
260                    continue;
261            }
262            /* Found perm in partner list. */
263            *uid = dp->uid;
264            *gid = dp->gid;
265            return dp->perm;
266        }
267        /* Default if nothing found. */
268        *uid = 0;
269        *gid = 0;
270        return 0600;
271    }
272}
273
274static void make_device(const char *path, int block, int major, int minor)
275{
276    unsigned uid;
277    unsigned gid;
278    mode_t mode;
279    dev_t dev;
280
281    if(major > 255 || minor > 255)
282        return;
283
284    mode = get_device_perm(path, &uid, &gid) | (block ? S_IFBLK : S_IFCHR);
285    dev = (major << 8) | minor;
286    mknod(path, mode, dev);
287    chown(path, uid, gid);
288}
289
290#ifdef LOG_UEVENTS
291
292static inline suseconds_t get_usecs(void)
293{
294    struct timeval tv;
295    gettimeofday(&tv, 0);
296    return tv.tv_sec * (suseconds_t) 1000000 + tv.tv_usec;
297}
298
299#define log_event_print(x...) INFO(x)
300
301#else
302
303#define log_event_print(fmt, args...)   do { } while (0)
304#define get_usecs()                     0
305
306#endif
307
308static void parse_event(const char *msg, struct uevent *uevent)
309{
310    uevent->action = "";
311    uevent->path = "";
312    uevent->subsystem = "";
313    uevent->firmware = "";
314    uevent->major = -1;
315    uevent->minor = -1;
316
317        /* currently ignoring SEQNUM */
318    while(*msg) {
319        if(!strncmp(msg, "ACTION=", 7)) {
320            msg += 7;
321            uevent->action = msg;
322        } else if(!strncmp(msg, "DEVPATH=", 8)) {
323            msg += 8;
324            uevent->path = msg;
325        } else if(!strncmp(msg, "SUBSYSTEM=", 10)) {
326            msg += 10;
327            uevent->subsystem = msg;
328        } else if(!strncmp(msg, "FIRMWARE=", 9)) {
329            msg += 9;
330            uevent->firmware = msg;
331        } else if(!strncmp(msg, "MAJOR=", 6)) {
332            msg += 6;
333            uevent->major = atoi(msg);
334        } else if(!strncmp(msg, "MINOR=", 6)) {
335            msg += 6;
336            uevent->minor = atoi(msg);
337        }
338
339            /* advance to after the next \0 */
340        while(*msg++)
341            ;
342    }
343
344    log_event_print("event { '%s', '%s', '%s', '%s', %d, %d }\n",
345                    uevent->action, uevent->path, uevent->subsystem,
346                    uevent->firmware, uevent->major, uevent->minor);
347}
348
349static void handle_device_event(struct uevent *uevent)
350{
351    char devpath[96];
352    char *base, *name;
353    int block;
354
355        /* if it's not a /dev device, nothing to do */
356    if((uevent->major < 0) || (uevent->minor < 0))
357        return;
358
359        /* do we have a name? */
360    name = strrchr(uevent->path, '/');
361    if(!name)
362        return;
363    name++;
364
365        /* too-long names would overrun our buffer */
366    if(strlen(name) > 64)
367        return;
368
369        /* are we block or char? where should we live? */
370    if(!strncmp(uevent->subsystem, "block", 5)) {
371        block = 1;
372        base = "/dev/block/";
373        mkdir(base, 0755);
374    } else {
375        block = 0;
376            /* this should probably be configurable somehow */
377        if(!strncmp(uevent->subsystem, "graphics", 8)) {
378            base = "/dev/graphics/";
379            mkdir(base, 0755);
380        } else if (!strncmp(uevent->subsystem, "oncrpc", 6)) {
381            base = "/dev/oncrpc/";
382            mkdir(base, 0755);
383        } else if (!strncmp(uevent->subsystem, "adsp", 4)) {
384            base = "/dev/adsp/";
385            mkdir(base, 0755);
386        } else if (!strncmp(uevent->subsystem, "msm_camera", 10)) {
387            base = "/dev/msm_camera/";
388            mkdir(base, 0755);
389        } else if(!strncmp(uevent->subsystem, "input", 5)) {
390            base = "/dev/input/";
391            mkdir(base, 0755);
392        } else if(!strncmp(uevent->subsystem, "mtd", 3)) {
393            base = "/dev/mtd/";
394            mkdir(base, 0755);
395        } else if(!strncmp(uevent->subsystem, "misc", 4) &&
396                    !strncmp(name, "log_", 4)) {
397            base = "/dev/log/";
398            mkdir(base, 0755);
399            name += 4;
400        } else
401            base = "/dev/";
402    }
403
404    snprintf(devpath, sizeof(devpath), "%s%s", base, name);
405
406    if(!strcmp(uevent->action, "add")) {
407        make_device(devpath, block, uevent->major, uevent->minor);
408        return;
409    }
410
411    if(!strcmp(uevent->action, "remove")) {
412        unlink(devpath);
413        return;
414    }
415}
416
417static int load_firmware(int fw_fd, int loading_fd, int data_fd)
418{
419    struct stat st;
420    long len_to_copy;
421    int ret = 0;
422
423    if(fstat(fw_fd, &st) < 0)
424        return -1;
425    len_to_copy = st.st_size;
426
427    write(loading_fd, "1", 1);  /* start transfer */
428
429    while (len_to_copy > 0) {
430        char buf[PAGE_SIZE];
431        ssize_t nr;
432
433        nr = read(fw_fd, buf, sizeof(buf));
434        if(!nr)
435            break;
436        if(nr < 0) {
437            ret = -1;
438            break;
439        }
440
441        len_to_copy -= nr;
442        while (nr > 0) {
443            ssize_t nw = 0;
444
445            nw = write(data_fd, buf + nw, nr);
446            if(nw <= 0) {
447                ret = -1;
448                goto out;
449            }
450            nr -= nw;
451        }
452    }
453
454out:
455    if(!ret)
456        write(loading_fd, "0", 1);  /* successful end of transfer */
457    else
458        write(loading_fd, "-1", 2); /* abort transfer */
459
460    return ret;
461}
462
463static void process_firmware_event(struct uevent *uevent)
464{
465    char *root, *loading, *data, *file;
466    int l, loading_fd, data_fd, fw_fd;
467
468    log_event_print("firmware event { '%s', '%s' }\n",
469                    uevent->path, uevent->firmware);
470
471    l = asprintf(&root, SYSFS_PREFIX"%s/", uevent->path);
472    if (l == -1)
473        return;
474
475    l = asprintf(&loading, "%sloading", root);
476    if (l == -1)
477        goto root_free_out;
478
479    l = asprintf(&data, "%sdata", root);
480    if (l == -1)
481        goto loading_free_out;
482
483    l = asprintf(&file, FIRMWARE_DIR"/%s", uevent->firmware);
484    if (l == -1)
485        goto data_free_out;
486
487    loading_fd = open(loading, O_WRONLY);
488    if(loading_fd < 0)
489        goto file_free_out;
490
491    data_fd = open(data, O_WRONLY);
492    if(data_fd < 0)
493        goto loading_close_out;
494
495    fw_fd = open(file, O_RDONLY);
496    if(fw_fd < 0)
497        goto data_close_out;
498
499    if(!load_firmware(fw_fd, loading_fd, data_fd))
500        log_event_print("firmware copy success { '%s', '%s' }\n", root, file);
501    else
502        log_event_print("firmware copy failure { '%s', '%s' }\n", root, file);
503
504    close(fw_fd);
505data_close_out:
506    close(data_fd);
507loading_close_out:
508    close(loading_fd);
509file_free_out:
510    free(file);
511data_free_out:
512    free(data);
513loading_free_out:
514    free(loading);
515root_free_out:
516    free(root);
517}
518
519static void handle_firmware_event(struct uevent *uevent)
520{
521    pid_t pid;
522
523    if(strcmp(uevent->subsystem, "firmware"))
524        return;
525
526    if(strcmp(uevent->action, "add"))
527        return;
528
529    /* we fork, to avoid making large memory allocations in init proper */
530    pid = fork();
531    if (!pid) {
532        process_firmware_event(uevent);
533        exit(EXIT_SUCCESS);
534    }
535}
536
537#define UEVENT_MSG_LEN  1024
538void handle_device_fd(int fd)
539{
540    char msg[UEVENT_MSG_LEN+2];
541    int n;
542
543    while((n = recv(fd, msg, UEVENT_MSG_LEN, 0)) > 0) {
544        struct uevent uevent;
545
546        if(n == UEVENT_MSG_LEN)   /* overflow -- discard */
547            continue;
548
549        msg[n] = '\0';
550        msg[n+1] = '\0';
551
552        parse_event(msg, &uevent);
553
554        handle_device_event(&uevent);
555        handle_firmware_event(&uevent);
556    }
557}
558
559/* Coldboot walks parts of the /sys tree and pokes the uevent files
560** to cause the kernel to regenerate device add events that happened
561** before init's device manager was started
562**
563** We drain any pending events from the netlink socket every time
564** we poke another uevent file to make sure we don't overrun the
565** socket's buffer.
566*/
567
568static void do_coldboot(int event_fd, DIR *d)
569{
570    struct dirent *de;
571    int dfd, fd;
572
573    dfd = dirfd(d);
574
575    fd = openat(dfd, "uevent", O_WRONLY);
576    if(fd >= 0) {
577        write(fd, "add\n", 4);
578        close(fd);
579        handle_device_fd(event_fd);
580    }
581
582    while((de = readdir(d))) {
583        DIR *d2;
584
585        if(de->d_type != DT_DIR || de->d_name[0] == '.')
586            continue;
587
588        fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY);
589        if(fd < 0)
590            continue;
591
592        d2 = fdopendir(fd);
593        if(d2 == 0)
594            close(fd);
595        else {
596            do_coldboot(event_fd, d2);
597            closedir(d2);
598        }
599    }
600}
601
602static void coldboot(int event_fd, const char *path)
603{
604    DIR *d = opendir(path);
605    if(d) {
606        do_coldboot(event_fd, d);
607        closedir(d);
608    }
609}
610
611int device_init(void)
612{
613    suseconds_t t0, t1;
614    int fd;
615
616    fd = open_uevent_socket();
617    if(fd < 0)
618        return -1;
619
620    fcntl(fd, F_SETFD, FD_CLOEXEC);
621    fcntl(fd, F_SETFL, O_NONBLOCK);
622
623    t0 = get_usecs();
624    coldboot(fd, "/sys/class");
625    coldboot(fd, "/sys/block");
626    coldboot(fd, "/sys/devices");
627    t1 = get_usecs();
628
629    log_event_print("coldboot %ld uS\n", ((long) (t1 - t0)));
630
631    return fd;
632}
633