init_cmds.c 15.5 KB
Newer Older
W
wenjun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * 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.
 */
15

W
wenjun 已提交
16 17 18
#include "init_cmds.h"
#include <ctype.h>
#include <errno.h>
19
#include <stdbool.h>
W
wenjun 已提交
20 21 22 23 24 25
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <unistd.h>
Z
zhong_ning 已提交
26
#ifndef OHOS_LITE
Z
zhong_ning 已提交
27 28 29 30
#include <sys/syscall.h>
#include <fcntl.h>
#include <linux/module.h>
#endif
W
wenjun 已提交
31 32 33 34 35 36 37 38
#include "init_service_manager.h"
#include "securec.h"

#define MODE_LEN 4   // for chmod mode, format 0xxx
#define DEFAULT_DIR_MODE 0755  // mkdir, default mode
#define SPACES_CNT_IN_CMD_MAX 10   // mount, max number of spaces in cmdline
#define SPACES_CNT_IN_CMD_MIN 2    // mount, min number of spaces in cmdline

M
mamingshuai 已提交
39 40 41
#define LOADCFG_BUF_SIZE  128  // loadcfg, max buffer for one cmdline
#define LOADCFG_MAX_FILE_LEN 51200  // loadcfg, max file size is 50K
#define LOADCFG_MAX_LOOP 20  // loadcfg, to prevent to be trapped in infite loop
L
leon 已提交
42
#define OCTAL_TYPE 8  // 8 means octal to decimal
M
mamingshuai 已提交
43 44 45 46
static const char *g_supportCfg[] = {
    "/patch/fstab.cfg",
};

W
wenjun 已提交
47 48 49 50 51 52
static const char* g_supportedCmds[] = {
    "start ",
    "mkdir ",
    "chmod ",
    "chown ",
    "mount ",
M
mamingshuai 已提交
53
    "loadcfg ",
Z
zhong_ning 已提交
54
    "insmod ",
W
wenjun 已提交
55 56 57 58
};

void ParseCmdLine(const char* cmdStr, CmdLine* resCmd)
{
59 60
    size_t cmdLineLen = 0;
    if (cmdStr == NULL || resCmd == NULL || (cmdLineLen = strlen(cmdStr)) == 0) {
W
wenjun 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        return;
    }

    size_t supportCmdCnt = sizeof(g_supportedCmds) / sizeof(g_supportedCmds[0]);
    int foundAndSucceed = 0;
    for (size_t i = 0; i < supportCmdCnt; ++i) {
        size_t curCmdNameLen = strlen(g_supportedCmds[i]);
        if (cmdLineLen > curCmdNameLen && cmdLineLen <= (curCmdNameLen + MAX_CMD_CONTENT_LEN) &&
            strncmp(g_supportedCmds[i], cmdStr, curCmdNameLen) == 0) {
            if (memcpy_s(resCmd->name, MAX_CMD_NAME_LEN, cmdStr, curCmdNameLen) != EOK) {
                break;
            }
            resCmd->name[curCmdNameLen] = '\0';

            const char* cmdContent = cmdStr + curCmdNameLen;
            size_t cmdContentLen = cmdLineLen - curCmdNameLen;
            if (memcpy_s(resCmd->cmdContent, MAX_CMD_CONTENT_LEN, cmdContent, cmdContentLen) != EOK) {
                break;
            }
            resCmd->cmdContent[cmdContentLen] = '\0';
            foundAndSucceed = 1;
            break;
        }
    }

    if (!foundAndSucceed) {
        (void)memset_s(resCmd, sizeof(*resCmd), 0, sizeof(*resCmd));
    }
}

static void DoStart(const char* cmdContent)
{
    StartServiceByName(cmdContent);
}

static void DoMkDir(const char* cmdContent)
{
    mode_t mode = DEFAULT_DIR_MODE;
    if (mkdir(cmdContent, mode) != 0) {
        if (errno != EEXIST) {
            printf("[Init] DoMkDir, failed for %s, err %d.\n", cmdContent, errno);
        }
    }
}

static void DoChmod(const char* cmdContent)
{
    // format: 0xxx /xxx/xxx/xxx
109
    if (cmdContent[0] != '0' || cmdContent[MODE_LEN] != ' ' || strlen(cmdContent) <= MODE_LEN + 1) {
W
wenjun 已提交
110 111 112 113 114 115 116 117 118 119 120 121
        printf("[Init] DoChmod, bad format for %s.\n", cmdContent);
        return;
    }

    for (size_t i = 1; i < MODE_LEN; ++i) {
        if (cmdContent[i] > '7' || cmdContent[i] < '0') {
            printf("[Init] DoChmod, bad mode format for %s.\n", cmdContent);
            return;
        }
    }

    const char* pathBeginStr = cmdContent + MODE_LEN + 1;  // after space
L
leon 已提交
122
    mode_t mode = strtoul(cmdContent, NULL, OCTAL_TYPE);
W
wenjun 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    if (mode == 0) {
        printf("[Init] DoChmod, strtoul failed for %s, er %d.\n", cmdContent, errno);
        return;
    }

    if (chmod(pathBeginStr, mode) != 0) {
        printf("[Init] DoChmod, failed for %s, err %d.\n", cmdContent, errno);
    }
}

static void DoChown(const char* cmdContent)
{
    // format: owner group /xxx/xxx/xxx
    size_t firstSpace = 0;
    size_t secondSpace = 0;
    size_t strLen = strlen(cmdContent);
    for (size_t i = 0; i < strLen; ++i) {
M
mamingshuai 已提交
140 141 142 143 144 145 146 147 148 149 150
        if (cmdContent[i] == ' ') {
            if (i == 0) {
                printf("[Init] DoChown, bad format for %s.\n", cmdContent);
                return;
            }
            if (firstSpace == 0) {
                firstSpace = i;
            } else {
                secondSpace = i;
                break;
            }
W
wenjun 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
        }
    }

    if (secondSpace <= firstSpace || firstSpace + 1 == secondSpace || secondSpace == strLen - 1) {
        printf("[Init] DoChown, bad format for %s.\n", cmdContent);
        return;
    }

    // only numbers valid
    for (size_t i = 0; i < secondSpace; ++i) {
        if (i != firstSpace && !isdigit(cmdContent[i])) {
            printf("[Init] DoChown, bad format for %s.\n", cmdContent);
            return;
        }
    }

    uid_t owner = strtoul(cmdContent, NULL, 0);
    const char* groupBegin = cmdContent + firstSpace + 1;
    gid_t group = strtoul(groupBegin, NULL, 0);
    const char *path = cmdContent + secondSpace + 1;
    if (chown(path, owner, group) != 0) {
        printf("[Init] DoChown, failed for %s, err %d.\n", cmdContent, errno);
    }
}

static char* CopySubStr(const char* srcStr, size_t startPos, size_t endPos)
{
    if (endPos <= startPos) {
Z
zhong_ning 已提交
179
        printf("[Init] DoMount, invalid params<%zu, %zu> for %s.\n", endPos, startPos, srcStr);
W
wenjun 已提交
180 181 182 183 184 185
        return NULL;
    }

    size_t mallocLen = endPos - startPos + 1;
    char* retStr = (char*)malloc(mallocLen);
    if (retStr == NULL) {
Z
zhong_ning 已提交
186
        printf("[Init] DoMount, malloc failed! malloc size %zu, for %s.\n", mallocLen, srcStr);
W
wenjun 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
        return NULL;
    }

    const char* copyStart = srcStr + startPos;
    if (memcpy_s(retStr, mallocLen, copyStart, endPos - startPos) != EOK) {
        printf("[Init] DoMount, memcpy_s failed for %s.\n", srcStr);
        free(retStr);
        return NULL;
    }
    retStr[mallocLen - 1] = '\0';

    // for example, source may be none
    if (strncmp(retStr, "none", strlen("none")) == 0) {
        retStr[0] = '\0';
    }
    return retStr;
}

static int GetMountFlag(unsigned long* mountflags, const char* targetStr)
{
    if (targetStr == NULL) {
        return 0;
    }

    if (strncmp(targetStr, "nodev", strlen("nodev")) == 0) {
        (*mountflags) |= MS_NODEV;
G
Gymee 已提交
213
    } else if (strncmp(targetStr, "noexec", strlen("noexec")) == 0) {
W
wenjun 已提交
214
        (*mountflags) |= MS_NOEXEC;
G
Gymee 已提交
215
    } else if (strncmp(targetStr, "nosuid", strlen("nosuid")) == 0) {
W
wenjun 已提交
216
        (*mountflags) |= MS_NOSUID;
G
Gymee 已提交
217
    } else if (strncmp(targetStr, "rdonly", strlen("rdonly")) == 0) {
W
wenjun 已提交
218
        (*mountflags) |= MS_RDONLY;
G
Gymee 已提交
219 220
    } else {
        return 0;
W
wenjun 已提交
221
    }
G
Gymee 已提交
222
    return 1;
W
wenjun 已提交
223 224 225 226
}

static int CountSpaces(const char* cmdContent, size_t* spaceCnt, size_t* spacePosArr, size_t spacePosArrLen)
{
M
mamingshuai 已提交
227 228
    *spaceCnt = 0;
    size_t strLen = strlen(cmdContent);
W
wenjun 已提交
229
    for (size_t i = 0; i < strLen; ++i) {
M
mamingshuai 已提交
230 231 232 233 234 235 236
        if (cmdContent[i] == ' ') {
            ++(*spaceCnt);
            if ((*spaceCnt) > spacePosArrLen) {
                printf("[Init] DoMount, too many spaces, bad format for %s.\n", cmdContent);
                return 0;
            }
            spacePosArr[(*spaceCnt) - 1] = i;
W
wenjun 已提交
237 238 239
        }
    }

M
mamingshuai 已提交
240 241 242
    if ((*spaceCnt) < SPACES_CNT_IN_CMD_MIN ||           // spaces count should not less than 2(at least 3 items)
        spacePosArr[0] == 0 ||                           // should not start with space
        spacePosArr[(*spaceCnt) - 1] == strLen - 1) {    // should not end with space
W
wenjun 已提交
243 244 245 246 247
        printf("[Init] DoMount, bad format for %s.\n", cmdContent);
        return 0;
    }

    // spaces should not be adjacent
M
mamingshuai 已提交
248 249
    for (size_t i = 1; i < (*spaceCnt); ++i) {
        if (spacePosArr[i] == spacePosArr[i - 1] + 1) {
W
wenjun 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
            printf("[Init] DoMount, bad format for %s.\n", cmdContent);
            return 0;
        }
    }
    return 1;
}

static void DoMount(const char* cmdContent)
{
    size_t spaceCnt = 0;
    size_t spacePosArr[SPACES_CNT_IN_CMD_MAX] = {0};
    if (!CountSpaces(cmdContent, &spaceCnt, spacePosArr, SPACES_CNT_IN_CMD_MAX)) {
        return;
    }

265 266 267
    // format: fileSystemType source target mountFlag1 mountFlag2... data
    unsigned long mountflags = 0;
    size_t strLen = strlen(cmdContent);
W
wenjun 已提交
268 269
    size_t indexOffset = 0;
    char* fileSysType = CopySubStr(cmdContent, 0, spacePosArr[indexOffset]);
M
mamingshuai 已提交
270 271 272 273
    if (fileSysType == NULL) {
        return;
    }

W
wenjun 已提交
274
    char* source = CopySubStr(cmdContent, spacePosArr[indexOffset] + 1, spacePosArr[indexOffset + 1]);
M
mamingshuai 已提交
275 276 277 278
    if (source == NULL) {
        free(fileSysType);
        return;
    }
W
wenjun 已提交
279 280 281 282 283
    ++indexOffset;

    // maybe only has "filesystype source target", 2 spaces
    size_t targetEndPos = (indexOffset == spaceCnt - 1) ? strLen : spacePosArr[indexOffset + 1];
    char* target = CopySubStr(cmdContent, spacePosArr[indexOffset] + 1, targetEndPos);
M
mamingshuai 已提交
284 285 286 287 288
    if (target == NULL) {
        free(fileSysType);
        free(source);
        return;
    }
W
wenjun 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    ++indexOffset;

    // get mountflags, if fail, the rest part of string will be data
    while (indexOffset < spaceCnt) {
        size_t tmpStrEndPos = (indexOffset == spaceCnt - 1) ? strLen : spacePosArr[indexOffset + 1];
        char* tmpStr = CopySubStr(cmdContent, spacePosArr[indexOffset] + 1, tmpStrEndPos);
        int ret = GetMountFlag(&mountflags, tmpStr);
        free(tmpStr);
        tmpStr = NULL;

        // get flag failed, the rest part of string will be data
        if (ret == 0) {
            break;
        }
        ++indexOffset;
    }

M
mamingshuai 已提交
306 307 308
    int mountRet;
    if (indexOffset >= spaceCnt) {    // no data
        mountRet = mount(source, target, fileSysType, mountflags, NULL);
W
wenjun 已提交
309
    } else {
M
mamingshuai 已提交
310 311 312 313 314 315
        const char* dataStr = cmdContent + spacePosArr[indexOffset] + 1;
        mountRet = mount(source, target, fileSysType, mountflags, dataStr);
    }

    if (mountRet != 0) {
        printf("[Init] DoMount, failed for %s, err %d.\n", cmdContent, errno);
W
wenjun 已提交
316 317 318 319 320 321 322
    }

    free(fileSysType);
    free(source);
    free(target);
}

Z
zhong_ning 已提交
323
#ifndef OHOS_LITE
L
leon 已提交
324
#define OPTIONS_SIZE 128u
L
leon 已提交
325 326 327 328 329 330 331 332 333 334
static void DoInsmodInternal(const char *fileName, char *secondPtr, char *restPtr, int flags)
{
    int fd = -1;
    char options[OPTIONS_SIZE] = {0};

    if (flags == 0) { //  '-f' option
        if (restPtr != NULL && secondPtr != NULL) { // Reset arugments, combine then all.
            if (snprintf_s(options, sizeof(options), OPTIONS_SIZE -1, "%s %s", secondPtr, restPtr) == -1) {
                goto out;
            }
L
leon 已提交
335
        } else if (secondPtr != NULL) {
L
leon 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
            if (strncpy_s(options, OPTIONS_SIZE - 1, secondPtr, strlen(secondPtr)) != 0) {
                goto out;
            }
        }
    } else { // Only restPtr is option
        if (restPtr != NULL) {
            strncpy_s(options, OPTIONS_SIZE - 1, restPtr, strlen(restPtr));
        }
    }
    fd = open(fileName, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
    if (fd < 0) {
        printf("[Init] failed to open %s: %d\n", fileName, errno);
        goto out;
    }
    int rc = syscall(__NR_finit_module, fd, options, flags);
    if (rc == -1) {
        printf("[Init] finit_module for %s failed: %d\n", fileName, errno);
    }
out:
    if (fd > 0) {
        close(fd);
    }
    return;
}

Z
zhong_ning 已提交
361 362 363 364 365 366
// format insmod <ko name> [-f] [options]
static void DoInsmod(const char *cmdContent)
{
    char *p = NULL;
    char *restPtr = NULL;
    char *fileName = NULL;
L
leon 已提交
367
    char *line = NULL;
Z
zhong_ning 已提交
368 369 370 371 372 373 374 375 376 377 378
    int flags = 0;

    size_t count = strlen(cmdContent);
    if (count > OPTIONS_SIZE) {
        printf("[Init], options too long, maybe lost some of options\n");
    }
    line = (char *)malloc(count + 1);
    if (line == NULL) {
        printf("[Init] Allocate memory failed.\n");
        return;
    }
L
leon 已提交
379

Z
zhong_ning 已提交
380 381
    if (memcpy_s(line, count, cmdContent, count) != EOK) {
        printf("[Init] memcpy failed\n");
L
leon 已提交
382
        return;
Z
zhong_ning 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    }
    line[count] = '\0';
    do {
        if ((p = strtok_r(line, " ", &restPtr)) == NULL) {
            printf("[Init] debug, cannot get filename\n");
            return;
        }
        fileName = p;
        printf("[Init] debug, fileName is [%s]\n", fileName);
        if ((p = strtok_r(NULL, " ", &restPtr)) == NULL) {
            break;
        }
        if (!strcmp(p, "-f")) {
            flags = MODULE_INIT_IGNORE_VERMAGIC | MODULE_INIT_IGNORE_MODVERSIONS;
        }
    } while (0);
L
leon 已提交
399
    DoInsmodInternal(fileName, p, restPtr, flags);
Z
zhong_ning 已提交
400 401 402
    if (line != NULL) {
        free(line);
    }
L
leon 已提交
403
    return;
Z
zhong_ning 已提交
404
}
L
leon 已提交
405
#endif // OHOS_LITE
Z
zhong_ning 已提交
406

M
mamingshuai 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
static bool CheckValidCfg(const char *path)
{
    size_t cfgCnt = sizeof(g_supportCfg) / sizeof(g_supportCfg[0]);
    struct stat fileStat = {0};

    if (stat(path, &fileStat) != 0 || fileStat.st_size <= 0 || fileStat.st_size > LOADCFG_MAX_FILE_LEN) {
        return false;
    }

    for (size_t i = 0; i < cfgCnt; ++i) {
        if (strcmp(path, g_supportCfg[i]) == 0) {
            return true;
        }
    }

    return false;
}

static void DoLoadCfg(const char *path)
{
    char buf[LOADCFG_BUF_SIZE] = {0};
    FILE *fp = NULL;
    size_t maxLoop = 0;
    CmdLine *cmdLine = NULL;
    int len;

    if (path == NULL) {
        return;
    }

    printf("[Init] DoLoadCfg cfg file %s\n", path);
    if (!CheckValidCfg(path)) {
        printf("[Init] CheckCfg file %s Failed\n", path);
        return;
    }

    fp = fopen(path, "r");
    if (fp == NULL) {
        printf("[Init] open cfg error = %d\n", errno);
        return;
    }

    cmdLine = (CmdLine *)malloc(sizeof(CmdLine));
    if (cmdLine == NULL) {
        printf("[Init] malloc cmdline error");
        fclose(fp);
        return;
    }

    while (fgets(buf, LOADCFG_BUF_SIZE, fp) != NULL && maxLoop < LOADCFG_MAX_LOOP) {
        maxLoop++;
        len = strlen(buf);
        if (len < 1) {
            continue;
        }
        if (buf[len - 1] == '\n') {
            buf[len - 1] = '\0'; // we replace '\n' with '\0'
        }
        (void)memset_s(cmdLine, sizeof(CmdLine), 0, sizeof(CmdLine));
        ParseCmdLine(buf, cmdLine);
        DoCmd(cmdLine);
        (void)memset_s(buf, sizeof(char) * LOADCFG_BUF_SIZE, 0, sizeof(char) * LOADCFG_BUF_SIZE);
    }

    free(cmdLine);
    fclose(fp);
}

W
wenjun 已提交
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
void DoCmd(const CmdLine* curCmd)
{
    if (curCmd == NULL) {
        return;
    }

    if (strncmp(curCmd->name, "start ", strlen("start ")) == 0) {
        DoStart(curCmd->cmdContent);
    } else if (strncmp(curCmd->name, "mkdir ", strlen("mkdir ")) == 0) {
        DoMkDir(curCmd->cmdContent);
    } else if (strncmp(curCmd->name, "chmod ", strlen("chmod ")) == 0) {
        DoChmod(curCmd->cmdContent);
    } else if (strncmp(curCmd->name, "chown ", strlen("chown ")) == 0) {
        DoChown(curCmd->cmdContent);
    } else if (strncmp(curCmd->name, "mount ", strlen("mount ")) == 0) {
        DoMount(curCmd->cmdContent);
M
mamingshuai 已提交
491 492
    } else if (strncmp(curCmd->name, "loadcfg ", strlen("loadcfg ")) == 0) {
        DoLoadCfg(curCmd->cmdContent);
Z
zhong_ning 已提交
493
#ifndef OHOS_LITE
L
leon 已提交
494
    } else if (strncmp(curCmd->name, "insmod ", strlen("insmod ")) == 0) {
Z
zhong_ning 已提交
495 496
        DoInsmod(curCmd->cmdContent);
#endif
L
leon 已提交
497
    } else {
W
wenjun 已提交
498 499 500
        printf("[Init] DoCmd, unknown cmd name %s.\n", curCmd->name);
    }
}
M
mamingshuai 已提交
501