uevent.c 24.3 KB
Newer Older
Z
zhong_ning 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

L
lanxueyuan 已提交
16 17 18 19 20 21 22 23 24 25 26
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/netlink.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
Z
zhong_ning 已提交
27 28 29 30
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/un.h>
#include <unistd.h>
Z
zhong_ning 已提交
31
#include "init_log.h"
Z
zhong_ning 已提交
32 33 34
#include "list.h"
#include "securec.h"

L
leon 已提交
35
#define LINK_NUMBER 4
S
sun_fan 已提交
36
#define DEFAULT_DIR_MODE (S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
L
leon 已提交
37 38 39 40 41 42 43 44 45
#define TRIGGER_ADDR_SIZE 4
#define BASE_BUFFER_SIZE 1024
#define MAX_BUFFER 256
#define EVENT_MAX_BUFFER 1026
#define MAX_DEV_PATH 96
#define MINORS_GROUPS 128
#define SYS_LINK_NUMBER 2
#define MAX_DEVICE_LEN 64
#define DEFAULT_MODE 0000
S
sun_fan 已提交
46
#define DEVICE_DEFAULT_MODE (S_IRUSR | S_IWUSR | S_IRGRP)
L
leon 已提交
47

Z
zhong_ning 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
int g_ueventFD = -1;

struct Uevent {
    const char *action;
    const char *path;
    const char *subsystem;
    const char *firmware;
    const char *partitionName;
    const char *deviceName;
    int partitionNum;
    int major;
    int minor;
};

struct PlatformNode {
    char *name;
    char *path;
    size_t pathLen;
    struct ListNode list;
};

static struct ListNode g_platformNames = {
    .next = &g_platformNames,
    .prev = &g_platformNames,
};

L
leon 已提交
74
const char *g_trigger = "/dev/.trigger_uevent";
Z
zhong_ning 已提交
75 76 77 78 79 80 81
static void HandleUevent();

static int UeventFD()
{
    return g_ueventFD;
}

Z
zhong_ning 已提交
82
static void DoTrigger(DIR *dir, const char *path, int32_t pathLen)
Z
zhong_ning 已提交
83
{
Z
zhong_ning 已提交
84 85 86 87 88 89 90 91 92
    if (pathLen < 0) {
        return;
    }
    struct dirent *dirent = NULL;
    char ueventPath[MAX_BUFFER];
    if (snprintf_s(ueventPath, sizeof(ueventPath), sizeof(ueventPath) - 1, "%s/uevent", path) == -1) {
        return;
    }
    int fd = open(ueventPath, O_WRONLY);
Z
zhong_ning 已提交
93
    if (fd >= 0) {
L
leon 已提交
94
        write(fd, "add\n", TRIGGER_ADDR_SIZE);
Z
zhong_ning 已提交
95 96 97 98
        close(fd);
        HandleUevent();
    }

Z
zhong_ning 已提交
99 100
    while ((dirent = readdir(dir)) != NULL) {
        if (dirent->d_name[0] == '.' || dirent->d_type != DT_DIR) {
Z
zhong_ning 已提交
101 102
            continue;
        }
Z
zhong_ning 已提交
103 104
        char tmpPath[MAX_BUFFER];
        if (snprintf_s(tmpPath, sizeof(tmpPath), sizeof(tmpPath) - 1, "%s/%s", path, dirent->d_name) == -1) {
Z
zhong_ning 已提交
105 106 107
            continue;
        }

Z
zhong_ning 已提交
108 109 110
        DIR *dir2 = opendir(tmpPath);
        if (dir2) {
            DoTrigger(dir2, tmpPath, strlen(tmpPath));
Z
zhong_ning 已提交
111 112 113 114 115 116 117 118 119
            closedir(dir2);
        }
    }
}

void Trigger(const char *sysPath)
{
    DIR *dir = opendir(sysPath);
    if (dir) {
Z
zhong_ning 已提交
120
        DoTrigger(dir, sysPath, strlen(sysPath));
Z
zhong_ning 已提交
121 122 123 124 125 126
        closedir(dir);
    }
}

static void RetriggerUevent()
{
L
leon 已提交
127
    if (access(g_trigger, F_OK) == 0) {
Z
zhong_ning 已提交
128
        INIT_LOGI("Skip trigger uevent, alread done");
Z
zhong_ning 已提交
129 130 131 132 133
        return;
    }
    Trigger("/sys/class");
    Trigger("/sys/block");
    Trigger("/sys/devices");
L
leon 已提交
134
    int fd = open(g_trigger, O_WRONLY | O_CREAT | O_CLOEXEC, DEFAULT_MODE);
Z
zhong_ning 已提交
135
    if (fd >= 0) {
Z
zhong_ning 已提交
136 137
        close(fd);
    }
Z
zhong_ning 已提交
138
    INIT_LOGI("Re-trigger uevent done");
Z
zhong_ning 已提交
139 140 141 142 143
}

static void UeventSockInit()
{
    struct sockaddr_nl addr;
L
leon 已提交
144
    int buffSize = MAX_BUFFER * BASE_BUFFER_SIZE;
Z
zhong_ning 已提交
145 146 147 148 149 150 151 152 153 154 155
    int on = 1;

    if (memset_s(&addr, sizeof(addr), 0, sizeof(addr)) != 0) {
        return;
    }
    addr.nl_family = AF_NETLINK;
    addr.nl_pid = getpid();
    addr.nl_groups = 0xffffffff;

    int sockfd = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT);
    if (sockfd < 0) {
Z
zhong_ning 已提交
156
        INIT_LOGE("Create socket failed. %d", errno);
Z
zhong_ning 已提交
157 158 159 160 161 162 163
        return;
    }

    setsockopt(sockfd, SOL_SOCKET, SO_RCVBUFFORCE, &buffSize, sizeof(buffSize));
    setsockopt(sockfd, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on));

    if (bind(sockfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
Z
zhong_ning 已提交
164
        INIT_LOGE("Bind socket failed. %d", errno);
Z
zhong_ning 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        close(sockfd);
        return;
    }
    g_ueventFD = sockfd;
    fcntl(g_ueventFD, F_SETFD, FD_CLOEXEC);
    fcntl(g_ueventFD, F_SETFL, O_NONBLOCK);
    RetriggerUevent();
    return;
}

ssize_t ReadUevent(int fd, void *buf, size_t len)
{
    struct iovec iov = { buf, len };
    struct sockaddr_nl addr;
    char control[CMSG_SPACE(sizeof(struct ucred))];
    struct msghdr hdr = {
        &addr,
        sizeof(addr),
        &iov,
        1,
        control,
        sizeof(control),
        0,
    };
    ssize_t n = recvmsg(fd, &hdr, 0);
    if (n <= 0) {
        return n;
    }
    struct cmsghdr *cMsg = CMSG_FIRSTHDR(&hdr);
    if (cMsg == NULL || cMsg->cmsg_type != SCM_CREDENTIALS) {
Z
zhong_ning 已提交
195 196 197
        bzero(buf, len);
        errno = -EIO;
        return n;
Z
zhong_ning 已提交
198 199
    }
    struct ucred *cRed = (struct ucred *)CMSG_DATA(cMsg);
Z
zhong_ning 已提交
200 201 202 203
    if (cRed->uid != 0) {
        bzero(buf, len);
        errno = -EIO;
        return n;
Z
zhong_ning 已提交
204
    }
Z
zhong_ning 已提交
205

Z
zhong_ning 已提交
206 207
    if (addr.nl_groups == 0 || addr.nl_pid != 0) {
    /* ignoring non-kernel or unicast netlink message */
Z
zhong_ning 已提交
208 209 210
        bzero(buf, len);
        errno = -EIO;
        return n;
Z
zhong_ning 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    }

    return n;
}

static void InitUevent(struct Uevent *event)
{
    event->action = "";
    event->path = "";
    event->subsystem = "";
    event->firmware = "";
    event->partitionName = "";
    event->deviceName = "";
    event->partitionNum = -1;
}

static void ParseUevent(const char *buf, struct Uevent *event)
{
    InitUevent(event);
    while (*buf) {
Z
zhong_ning 已提交
231 232
        if (strncmp(buf, "ACTION=", strlen("ACTION=")) == 0) {
            buf += strlen("ACTION=");
Z
zhong_ning 已提交
233
            event->action = buf;
Z
zhong_ning 已提交
234 235
        } else if (strncmp(buf, "DEVPATH=", strlen("DEVPATH=")) == 0) {
            buf += strlen("DEVPATH=");
Z
zhong_ning 已提交
236
            event->path = buf;
Z
zhong_ning 已提交
237 238
        } else if (strncmp(buf, "SUBSYSTEM=", strlen("SUBSYSTEM=")) == 0) {
            buf += strlen("SUBSYSTEM=");
Z
zhong_ning 已提交
239
            event->subsystem = buf;
Z
zhong_ning 已提交
240 241
        } else if (strncmp(buf, "FIRMWARE=", strlen("FIRMWARE=")) == 0) {
            buf += strlen("FIRMWARE=");
Z
zhong_ning 已提交
242
            event->firmware = buf;
Z
zhong_ning 已提交
243 244
        } else if (strncmp(buf, "MAJOR=", strlen("MAJOR=")) == 0) {
            buf += strlen("MAJOR=");
Z
zhong_ning 已提交
245
            event->major = atoi(buf);
Z
zhong_ning 已提交
246 247
        } else if (strncmp(buf, "MINOR=", strlen("MINOR=")) == 0) {
            buf += strlen("MINOR=");
Z
zhong_ning 已提交
248
            event->minor = atoi(buf);
Z
zhong_ning 已提交
249 250
        } else if (strncmp(buf, "PARTN=", strlen("PARTN=")) == 0) {
            buf += strlen("PARTN=");
Z
zhong_ning 已提交
251
            event->partitionNum = atoi(buf);
Z
zhong_ning 已提交
252 253
        } else if (strncmp(buf, "PARTNAME=", strlen("PARTNAME=")) == 0) {
            buf += strlen("PARTNAME=");
Z
zhong_ning 已提交
254
            event->partitionName = buf;
Z
zhong_ning 已提交
255 256
        } else if (strncmp(buf, "DEVNAME=", strlen("DEVNAME=")) == 0) {
            buf += strlen("DEVNAME=");
Z
zhong_ning 已提交
257 258 259 260 261 262 263 264 265 266 267
            event->deviceName = buf;
        }
        // Drop reset.
        while (*buf++) {}
    }
}

static int MakeDir(const char *path, mode_t mode)
{
    int rc = mkdir(path, mode);
    if (rc < 0 && errno != EEXIST) {
Z
zhong_ning 已提交
268
        INIT_LOGE("Create %s failed. %d", path, errno);
Z
zhong_ning 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    }
    return rc;
}

static struct PlatformNode *FindPlatformDevice(const char *path)
{
    size_t pathLen = strlen(path);
    struct ListNode *node = NULL;
    struct PlatformNode *bus = NULL;

    for (node = (&g_platformNames)->prev; node != &g_platformNames; node = node->prev) {
        bus = (struct PlatformNode *)(((char*)(node)) - offsetof(struct PlatformNode, list));
        if ((bus->pathLen < pathLen) && (path[bus->pathLen] == '/') && !strncmp(path, bus->path, bus->pathLen)) {
            return bus;
        }
    }
    return NULL;
}

Z
zhong_ning 已提交
288
static void CheckValidPartitionName(char *partitionName)
Z
zhong_ning 已提交
289
{
Z
zhong_ning 已提交
290 291
    const char* supportPartition = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-";
    if (!partitionName) {
Z
zhong_ning 已提交
292 293 294
        return;
    }

Z
zhong_ning 已提交
295 296 297 298 299 300
    for (size_t i = 0; i < strlen(partitionName); i++) {
        int len = strspn(partitionName, supportPartition);
        partitionName += len;
        i = len;
        if (*partitionName) {
            *partitionName = '_';
Z
zhong_ning 已提交
301 302 303 304 305 306 307 308 309
        }
    }
}

static char **ParsePlatformBlockDevice(const struct Uevent *uevent)
{
    const char *device;
    char *slash = NULL;
    const char *type;
L
leon 已提交
310
    char linkPath[MAX_BUFFER];
Z
zhong_ning 已提交
311 312 313 314
    int linkNum = 0;
    char *p = NULL;

    struct PlatformNode *pDev = FindPlatformDevice(uevent->path);
L
leon 已提交
315
    if (!pDev) {
Z
zhong_ning 已提交
316 317
        return NULL;
    }
L
leon 已提交
318 319 320 321
    device = pDev->name;
    type = "platform";
    char **links = calloc(sizeof(char *), LINK_NUMBER);
    if (!links) {
Z
zhong_ning 已提交
322 323
        return NULL;
    }
Z
zhong_ning 已提交
324 325
    if (snprintf_s(linkPath, sizeof(linkPath), sizeof(linkPath) - 1, "/dev/block/%s/%s", type, device) == -1) {
        free(links);
Z
zhong_ning 已提交
326 327 328 329
        return NULL;
    }
    if (uevent->partitionName) {
        p = strdup(uevent->partitionName);
Z
zhong_ning 已提交
330
        CheckValidPartitionName(p);
Z
zhong_ning 已提交
331
        if (strcmp(uevent->partitionName, p)) {
Z
zhong_ning 已提交
332
            INIT_LOGI("Linking partition '%s' as '%s'", uevent->partitionName, p);
Z
zhong_ning 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
        }
        if (asprintf(&links[linkNum], "%s/by-name/%s", linkPath, p) > 0) {
            linkNum++;
        } else {
            links[linkNum] = NULL;
        }
        free(p);
    }
    if (uevent->partitionNum >= 0) {
        if (asprintf(&links[linkNum], "%s/by-num/p%d", linkPath, uevent->partitionNum) > 0) {
            linkNum++;
        } else {
            links[linkNum] = NULL;
        }
    }
    slash = strrchr(uevent->path, '/');
    if (asprintf(&links[linkNum], "%s/%s", linkPath, slash + 1) > 0) {
        linkNum++;
    } else {
        links[linkNum] = NULL;
    }
    return links;
}

S
sun_fan 已提交
357 358 359 360 361 362 363
struct DevPermissionMapper {
    char *devName;
    mode_t devMode;
    uid_t uid;
    gid_t gid;
};

Z
zhong_ning 已提交
364
struct DevPermissionMapper DEV_MAPPER[] = {
Z
zhong_ning 已提交
365
    {"/dev/binder", 0666, 0, 0},
S
sun_fan 已提交
366 367 368
    {"/dev/input/event0", 0660, 0, 1004},
    {"/dev/input/event1", 0660, 0, 1004},
    {"/dev/input/mice", 0660, 0, 1004},
Z
zhong_ning 已提交
369 370
    {"/dev/input/mouse0", 0660, 0, 0},
    {"/dev/input/event0", 0660, 0, 0},
S
sun_fan 已提交
371 372 373 374 375 376 377 378
    {"/dev/snd/timer", 0660, 1000, 1005},
    {"/dev/zero", 0666, 0, 0},
    {"/dev/full", 0666, 0, 0},
    {"/dev/ptmx", 0666, 0, 0},
    {"/dev/tty", 0666, 0, 0},
    {"/dev/random", 0666, 0, 0},
    {"/dev/urandom", 0666, 0, 0},
    {"/dev/ashmem", 0666, 0, 0},
Z
zhong_ning 已提交
379
    {"/dev/pmsg0", 0222, 0, 1007},
S
sun_fan 已提交
380 381 382 383 384 385 386
    {"/dev/jpeg", 0666, 1000, 1003},
    {"/dev/vinput", 0660, 1000, 1004},
    {"/dev/mmz_userdev", 0644, 1000, 1005},
    {"/dev/graphics/fb0", 0660, 1000, 1003},
    {"/dev/mem", 0660, 1000, 1005},
    {"/dev/ion", 0666, 1000, 1000},
    {"/dev/btusb0", 0660, 1002, 1002},
Z
zhong_ning 已提交
387
    {"/dev/uhid", 0660, 3011, 3011},
S
sun_fan 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    {"/dev/tc_ns_client", 0660, 1000, 1005},
    {"/dev/rtk_btusb", 0660, 1002, 0},
    {"/dev/sil9293", 0660, 1000, 1005},
    {"/dev/stpbt", 0660, 1002, 1001},
    {"/dev/avs", 0660, 1000, 1005},
    {"/dev/gdc", 0660, 1000, 1005},
    {"/dev/hdmi", 0660, 1000, 1005},
    {"/dev/hi_mipi", 0660, 1000, 1005},
    {"/dev/hi_mipi_tx", 0660, 1000, 1005},
    {"/dev/hi_tde", 0644, 1000, 1003},
    {"/dev/isp_dev", 0660, 1000, 1006},
    {"/dev/match", 0660, 1000, 1005},
    {"/dev/photo", 0660, 1000, 1005},
    {"/dev/rect", 0660, 1000, 1005},
    {"/dev/rgn", 0660, 1000, 1005},
    {"/dev/sys", 0660, 1000, 1005},
    {"/dev/vb", 0666, 1000, 1005},
    {"/dev/vdec", 0666, 1000, 1005},
    {"/dev/venc", 0666, 1000, 1005},
    {"/dev/vi", 0660, 1000, 1005},
    {"/dev/vo", 0660, 1000, 1005},
    {"/dev/vpss", 0660, 1000, 1005},
    {"/dev/i2c-0", 0660, 1000, 1006},
    {"/dev/i2c-1", 0660, 1000, 1006},
    {"/dev/i2c-2", 0660, 1000, 1006},
    {"/dev/i2c-3", 0660, 1000, 1006},
    {"/dev/i2c-4", 0660, 1000, 1006},
    {"/dev/i2c-5", 0660, 1000, 1006},
    {"/dev/i2c-6", 0660, 1000, 1006},
    {"/dev/i2c-7", 0660, 1000, 1006},
    {"/dev/vgs", 0666, 1000, 1005},
Z
zhong_ning 已提交
419 420 421
    {"/dev/dri/card0", 0666, 0, 1003},
    {"/dev/dri/card0-DSI-1", 0666, 0, 1003},
    {"/dev/dri/card0-HDMI-A-1", 0666, 0, 1003},
Z
zhong_ning 已提交
422 423 424 425
    {"/dev/dri/renderD128", 0666, 0, 1003},
    {"/dev/rtc0", 0640, 1000, 1000},
    {"/dev/tty0", 0660, 0, 1000},
    {"/dev/uinput", 0660, 3011, 3011}
S
sun_fan 已提交
426 427 428 429
};

static void AdjustDevicePermission(const char *devPath)
{
Z
zhong_ning 已提交
430 431 432 433
    for (unsigned int i = 0; i < sizeof(DEV_MAPPER) / sizeof(struct DevPermissionMapper); ++i) {
        if (strcmp(devPath, DEV_MAPPER[i].devName) == 0) {
            if (chmod(devPath, DEV_MAPPER[i].devMode) != 0) {
                INIT_LOGE("AdjustDevicePermission, failed for %s, err %d.", devPath, errno);
S
sun_fan 已提交
434 435
                return;
            }
Z
zhong_ning 已提交
436 437
            if (chown(devPath, DEV_MAPPER[i].uid, DEV_MAPPER[i].gid) != 0) {
                INIT_LOGE("AdjustDevicePermission, failed for %s, err %d.", devPath, errno);
S
sun_fan 已提交
438 439
                return;
            }
Z
zhong_ning 已提交
440
            INIT_LOGI("AdjustDevicePermission :%s success", devPath);
S
sun_fan 已提交
441 442 443 444 445
        }
    }
}

static void MakeDevice(const char *devPath, const char *path, int block, int major, int minor)
Z
zhong_ning 已提交
446 447 448 449
{
    /* Only for super user */
    gid_t gid = 0;
    dev_t dev;
S
sun_fan 已提交
450
    mode_t mode = DEVICE_DEFAULT_MODE;
Z
zhong_ning 已提交
451 452 453
    mode |= (block ? S_IFBLK : S_IFCHR);
    dev = makedev(major, minor);
    setegid(gid);
S
sun_fan 已提交
454
    if (mknod(devPath, mode, dev) != 0) {
Z
zhong_ning 已提交
455
        if (errno != EEXIST) {
Z
zhong_ning 已提交
456
            INIT_LOGE("Make device node[%d, %d] failed. %d", major, minor, errno);
Z
zhong_ning 已提交
457 458
        }
    }
S
sun_fan 已提交
459
    AdjustDevicePermission(devPath);
Z
zhong_ning 已提交
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
}

int MkdirRecursive(const char *pathName, mode_t mode)
{
    char buf[128];
    const char *slash;
    const char *p = pathName;
    struct stat info;

    while ((slash = strchr(p, '/')) != NULL) {
        int width = slash - pathName;
        p = slash + 1;
        if (width < 0) {
            break;
        }
        if (width == 0) {
            continue;
        }
        if ((unsigned int)width > sizeof(buf) - 1) {
Z
zhong_ning 已提交
479
            INIT_LOGE("path too long for MkdirRecursive");
Z
zhong_ning 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
            return -1;
        }
        if (memcpy_s(buf, width, pathName, width) != 0) {
            return -1;
        }
        buf[width] = 0;
        if (stat(buf, &info) != 0) {
            int ret = MakeDir(buf, mode);
            if (ret && errno != EEXIST) {
                return ret;
            }
        }
    }
    int ret = MakeDir(pathName, mode);
    if (ret && errno != EEXIST) {
        return ret;
    }
    return 0;
}

void RemoveLink(const char *oldpath, const char *newpath)
{
L
leon 已提交
502
    char path[MAX_BUFFER];
Z
zhong_ning 已提交
503 504 505 506 507 508 509 510 511 512 513 514
    ssize_t ret = readlink(newpath, path, sizeof(path) - 1);
    if (ret <= 0) {
        return;
    }
    path[ret] = 0;
    if (!strcmp(path, oldpath)) {
        unlink(newpath);
    }
}

static void MakeLink(const char *oldPath, const char *newPath)
{
L
leon 已提交
515
    char buf[MAX_BUFFER];
Z
zhong_ning 已提交
516 517 518 519 520 521 522 523 524 525 526 527
    char *slash = strrchr(newPath, '/');
    if (!slash) {
        return;
    }
    int width = slash - newPath;
    if (width <= 0 || width > (int)sizeof(buf) - 1) {
        return;
    }
    if (memcpy_s(buf, sizeof(buf), newPath, width) != 0) {
        return;
    }
    buf[width] = 0;
L
leon 已提交
528
    int ret = MkdirRecursive(buf, DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
529
    if (ret) {
Z
zhong_ning 已提交
530
        INIT_LOGE("Failed to create directory %s: %s (%d)", buf, strerror(errno), errno);
Z
zhong_ning 已提交
531 532 533
    }
    ret = symlink(oldPath, newPath);
    if (ret && errno != EEXIST) {
Z
zhong_ning 已提交
534
        INIT_LOGE("Failed to symlink %s to %s: %s (%d)", oldPath, newPath, strerror(errno), errno);
Z
zhong_ning 已提交
535 536 537
    }
}

L
leon 已提交
538
static void HandleDevice(struct Uevent *event, const char *devpath, int block, char **links)
Z
zhong_ning 已提交
539 540
{
    int i;
L
leon 已提交
541 542
    if (!strcmp(event->action, "add")) {
        MakeDevice(devpath, event->path, block, event->major, event->minor);
Z
zhong_ning 已提交
543 544 545 546 547 548 549
        if (links) {
            for (i = 0; links[i]; i++) {
                MakeLink(devpath, links[i]);
            }
        }
    }

L
leon 已提交
550
    if (!strcmp(event->action, "remove")) {
Z
zhong_ning 已提交
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
        if (links) {
            for (i = 0; links[i]; i++) {
                RemoveLink(devpath, links[i]);
            }
        }
        unlink(devpath);
    }

    if (links) {
        for (i = 0; links[i]; i++) {
            free(links[i]);
        }
        free(links);
    }
}

static void HandleBlockDevice(struct Uevent *event)
{
    const char *base = "/dev/block";
L
leon 已提交
570
    char devpath[MAX_DEV_PATH];
Z
zhong_ning 已提交
571 572 573 574 575 576 577 578 579 580
    char **links = NULL;

    if (event->major < 0 || event->minor < 0) {
        return;
    }
    const char *name = strrchr(event->path, '/');
    if (name == NULL) {
        return;
    }
    name++;
L
leon 已提交
581
    if (strlen(name) > MAX_DEVICE_LEN) { // too long
Z
zhong_ning 已提交
582 583
        return;
    }
Z
zhong_ning 已提交
584
    if (snprintf_s(devpath, sizeof(devpath), sizeof(devpath) - 1, "%s/%s", base, name) == -1) {
Z
zhong_ning 已提交
585 586
        return;
    }
L
leon 已提交
587
    MakeDir(base, DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
588
    if (!strncmp(event->path, "/devices/", strlen("/devices/"))) {
Z
zhong_ning 已提交
589 590
        links = ParsePlatformBlockDevice(event);
    }
L
leon 已提交
591
    HandleDevice(event, devpath, 1, links);
Z
zhong_ning 已提交
592 593 594 595 596 597
}

static void AddPlatformDevice(const char *path)
{
    size_t pathLen = strlen(path);
    const char *name = path;
Z
zhong_ning 已提交
598 599 600 601 602 603
    size_t deviceLength = strlen("/devices/");
    size_t platformLength = strlen("platform/");
    if (!strncmp(path, "/devices/", deviceLength)) {
        name += deviceLength;
        if (!strncmp(name, "platform/", platformLength)) {
            name += platformLength;
Z
zhong_ning 已提交
604 605
        }
    }
Z
zhong_ning 已提交
606
    INIT_LOGI("adding platform device %s (%s)", name, path);
Z
zhong_ning 已提交
607
    struct PlatformNode *bus = calloc(1, sizeof(struct PlatformNode));
Z
zhong_ning 已提交
608 609 610
    if (!bus) {
        return;
    }
Z
zhong_ning 已提交
611 612 613 614
    bus->path = strdup(path);
    bus->pathLen = pathLen;
    bus->name = bus->path + (name - path);
    ListAddTail(&g_platformNames, &bus->list);
Z
zhong_ning 已提交
615
    return;
Z
zhong_ning 已提交
616 617 618 619 620 621 622 623 624 625
}

static void RemovePlatformDevice(const char *path)
{
    struct ListNode *node = NULL;
    struct PlatformNode *bus = NULL;

    for (node = (&g_platformNames)->prev; node != &g_platformNames; node = node->prev) {
        bus = (struct PlatformNode *)(((char*)(node)) - offsetof(struct PlatformNode, list));
        if (!strcmp(path, bus->path)) {
Z
zhong_ning 已提交
626
            INIT_LOGI("removing platform device %s", bus->name);
Z
zhong_ning 已提交
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
            free(bus->path);
            ListRemove(node);
            free(bus);
            return;
        }
    }
}

static void HandlePlatformDevice(const struct Uevent *event)
{
    const char *path = event->path;
    if (strcmp(event->action, "add") == 0) {
        AddPlatformDevice(path);
    } else if (strcmp(event->action, "remove") == 0) {
        RemovePlatformDevice(path);
    }
}

static const char *ParseDeviceName(const struct Uevent *uevent, unsigned int len)
{
    /* if it's not a /dev device, nothing else to do */
    if ((uevent->major < 0) || (uevent->minor < 0)) {
        return NULL;
    }
    /* do we have a name? */
    const char *name = strrchr(uevent->path, '/');
    if (!name) {
        return NULL;
    }
    name++;
    /* too-long names would overrun our buffer */
    if (strlen(name) > len) {
        return NULL;
    }
    return name;
}

static char **GetCharacterDeviceSymlinks(const struct Uevent *uevent)
{
    char *slash = NULL;
    int linkNum = 0;
    int width;

    struct PlatformNode *pDev = FindPlatformDevice(uevent->path);
L
leon 已提交
671 672 673 674 675
    if (!pDev) {
        return NULL;
    }
    char **links = calloc(sizeof(char *), SYS_LINK_NUMBER);
    if (!links) {
Z
zhong_ning 已提交
676 677 678 679 680 681 682 683 684
        return NULL;
    }

    /* skip "/devices/platform/<driver>" */
    const char *parent = strchr(uevent->path + pDev->pathLen, '/');
    if (!*parent) {
        goto err;
    }

Z
zhong_ning 已提交
685
    if (strncmp(parent, "/usb", strlen("/usb"))) {
Z
zhong_ning 已提交
686
        goto err;
Z
zhong_ning 已提交
687 688 689 690 691 692 693 694 695 696 697 698 699
    }
    /* skip root hub name and device. use device interface */
    if (!*parent) {
        goto err;
    }
    slash = strchr(++parent, '/');
    if (!slash) {
        goto err;
    }
    width = slash - parent;
    if (width <= 0) {
        goto err;
    }
Z
zhong_ning 已提交
700

Z
zhong_ning 已提交
701 702
    if (asprintf(&links[linkNum], "/dev/usb/%s%.*s", uevent->subsystem, width, parent) > 0) {
        linkNum++;
Z
zhong_ning 已提交
703
    } else {
Z
zhong_ning 已提交
704
        links[linkNum] = NULL;
Z
zhong_ning 已提交
705
    }
Z
zhong_ning 已提交
706
    mkdir("/dev/usb", DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
707 708 709 710 711 712
    return links;
err:
    free(links);
    return NULL;
}

L
leon 已提交
713 714 715 716 717 718 719 720
static int HandleUsbDevice(const struct Uevent *event, char *devpath, int len)
{
    if (event->deviceName) {
        /*
         * create device node provided by kernel if present
         * see drivers/base/core.c
         */
        char *p = devpath;
Z
zhong_ning 已提交
721
        if (snprintf_s(devpath, len, len - 1, "/dev/%s", event->deviceName) == -1) {
L
leon 已提交
722 723 724
            return -1;
        }
        /* skip leading /dev/ */
Z
zhong_ning 已提交
725
        p += strlen("/dev/");
L
leon 已提交
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
        /* build directories */
        while (*p) {
            if (*p == '/') {
                *p = 0;
                MakeDir(devpath, DEFAULT_DIR_MODE);
                *p = '/';
            }
            p++;
        }
    } else {
        /* This imitates the file system that would be created
         * if we were using devfs instead.
         * Minors are broken up into groups of 128, starting at "001"
         */
        int busId  = event->minor / MINORS_GROUPS + 1;
        int deviceId = event->minor % MINORS_GROUPS + 1;
        /* build directories */
        MakeDir("/dev/bus", DEFAULT_DIR_MODE);
        MakeDir("/dev/bus/usb", DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
745
        if (snprintf_s(devpath, len, len - 1, "/dev/bus/usb/%03d", busId) == -1) {
L
leon 已提交
746 747 748
            return -1;
        }
        MakeDir(devpath, DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
749
        if (snprintf_s(devpath, len, len - 1, "/dev/bus/usb/%03d/%03d", busId,
L
leon 已提交
750 751 752 753 754 755 756 757 758 759 760 761
            deviceId) == -1) {
            return -1;
        }
    }
    return 0;
}

static void HandleDeviceEvent(struct Uevent *event, char *devpath, int len, const char *base, const char *name)
{
    char **links = NULL;
    links = GetCharacterDeviceSymlinks(event);
    if (!devpath[0]) {
Z
zhong_ning 已提交
762
        if (snprintf_s(devpath, len, len - 1, "%s%s", base, name) == -1) {
Z
zhong_ning 已提交
763
            INIT_LOGE("snprintf_s err ");
Z
zhong_ning 已提交
764
            goto err;
L
leon 已提交
765 766 767 768
        }
    }
    HandleDevice(event, devpath, 0, links);
    return;
Z
zhong_ning 已提交
769 770 771 772 773 774 775 776
err:
    if (links) {
        for (int i = 0; links[i]; i++) {
            free(links[i]);
        }
        free(links);
    }
    return;
L
leon 已提交
777
}
Z
zhong_ning 已提交
778 779 780
static void HandleGenericDevice(struct Uevent *event)
{
    char *base = NULL;
L
leon 已提交
781 782
    char devpath[MAX_DEV_PATH] = {0};
    const char *name = ParseDeviceName(event, MAX_DEVICE_LEN);
Z
zhong_ning 已提交
783 784 785
    if (!name) {
        return;
    }
Z
zhong_ning 已提交
786
    if (!strncmp(event->subsystem, "usb", strlen("usb"))) {
Z
zhong_ning 已提交
787
        if (!strcmp(event->subsystem, "usb")) {
L
leon 已提交
788 789
            if (HandleUsbDevice(event, devpath, MAX_DEV_PATH) == -1) {
                return;
Z
zhong_ning 已提交
790 791 792 793 794
            }
        } else {
            /* ignore other USB events */
            return;
        }
Z
zhong_ning 已提交
795
    } else if (!strncmp(event->subsystem, "graphics", strlen("graphics"))) {
Z
zhong_ning 已提交
796
        base = "/dev/graphics/";
L
leon 已提交
797
        MakeDir(base, DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
798
    } else if (!strncmp(event->subsystem, "drm", strlen("drm"))) {
Z
zhong_ning 已提交
799
        base = "/dev/dri/";
L
leon 已提交
800
        MakeDir(base, DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
801
    } else if (!strncmp(event->subsystem, "oncrpc", strlen("oncrpc"))) {
Z
zhong_ning 已提交
802
        base = "/dev/oncrpc/";
L
leon 已提交
803
        MakeDir(base, DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
804
    } else if (!strncmp(event->subsystem, "adsp", strlen("adsp"))) {
Z
zhong_ning 已提交
805
        base = "/dev/adsp/";
L
leon 已提交
806
        MakeDir(base, DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
807
    } else if (!strncmp(event->subsystem, "input", strlen("input"))) {
Z
zhong_ning 已提交
808
        base = "/dev/input/";
L
leon 已提交
809
        MakeDir(base, DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
810
    } else if (!strncmp(event->subsystem, "mtd", strlen("mtd"))) {
Z
zhong_ning 已提交
811
        base = "/dev/mtd/";
L
leon 已提交
812
        MakeDir(base, DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
813
    } else if (!strncmp(event->subsystem, "sound", strlen("sound"))) {
Z
zhong_ning 已提交
814
        base = "/dev/snd/";
L
leon 已提交
815
        MakeDir(base, DEFAULT_DIR_MODE);
Z
zhong_ning 已提交
816 817 818
    } else {
        base = "/dev/";
    }
L
leon 已提交
819 820
    HandleDeviceEvent(event, devpath, MAX_DEV_PATH, base, name);
    return;
Z
zhong_ning 已提交
821 822 823 824 825 826 827
}

static void HandleDeviceUevent(struct Uevent *event)
{
    if (strcmp(event->action, "add") == 0 || strcmp(event->action, "change") == 0) {
        /* Do nothing for now */
    }
Z
zhong_ning 已提交
828
    if (strncmp(event->subsystem, "block", strlen("block")) == 0) {
Z
zhong_ning 已提交
829
        HandleBlockDevice(event);
Z
zhong_ning 已提交
830
    } else if (strncmp(event->subsystem, "platform", strlen("platform")) == 0) {
Z
zhong_ning 已提交
831 832 833 834 835 836 837 838
        HandlePlatformDevice(event);
    } else {
        HandleGenericDevice(event);
    }
}

static void HandleUevent()
{
L
leon 已提交
839
    char buf[EVENT_MAX_BUFFER];
Z
zhong_ning 已提交
840 841
    int ret;
    struct Uevent event;
L
leon 已提交
842 843
    while ((ret = ReadUevent(g_ueventFD, buf, BASE_BUFFER_SIZE)) > 0) {
        if (ret >= BASE_BUFFER_SIZE) {
Z
zhong_ning 已提交
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
            continue;
        }
        buf[ret] = '\0';
        buf[ret + 1] = '\0';
        ParseUevent(buf, &event);
        HandleDeviceUevent(&event);
    }
}

void UeventInit()
{
    struct pollfd ufd;
    UeventSockInit();
    ufd.events = POLLIN;
    ufd.fd = UeventFD();
    while (1) {
        ufd.revents = 0;
        int ret = poll(&ufd, 1, -1);
        if (ret <= 0) {
            continue;
        }
        if (ufd.revents & POLLIN) {
            HandleUevent();
        }
    }
    return;
}

L
leon 已提交
872
int main(const int argc, const char **argv)
Z
zhong_ning 已提交
873
{
Z
zhong_ning 已提交
874
    INIT_LOGI("Uevent demo starting...");
Z
zhong_ning 已提交
875 876 877
    UeventInit();
    return 0;
}