init_cmds.c 15.7 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
#include "init_cmds.h"
Z
zhong_ning 已提交
17

W
wenjun 已提交
18 19
#include <ctype.h>
#include <errno.h>
20
#include <stdbool.h>
W
wenjun 已提交
21 22 23 24 25 26
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <unistd.h>
Z
zhong_ning 已提交
27
#ifndef OHOS_LITE
Z
zhong_ning 已提交
28 29
#include <fcntl.h>
#include <linux/module.h>
Z
zhong_ning 已提交
30
#include <sys/syscall.h>
Z
zhong_ning 已提交
31
#endif
Z
zhong_ning 已提交
32

W
wenjun 已提交
33 34 35 36 37 38 39 40
#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 已提交
41 42 43
#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 已提交
44
#define OCTAL_TYPE 8  // 8 means octal to decimal
M
mamingshuai 已提交
45 46 47 48
static const char *g_supportCfg[] = {
    "/patch/fstab.cfg",
};

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

void ParseCmdLine(const char* cmdStr, CmdLine* resCmd)
{
61 62
    size_t cmdLineLen = 0;
    if (cmdStr == NULL || resCmd == NULL || (cmdLineLen = strlen(cmdStr)) == 0) {
W
wenjun 已提交
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 109 110
        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
111
    if (cmdContent[0] != '0' || cmdContent[MODE_LEN] != ' ' || strlen(cmdContent) <= MODE_LEN + 1) {
W
wenjun 已提交
112 113 114 115 116 117 118 119 120 121 122 123
        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 已提交
124
    mode_t mode = strtoul(cmdContent, NULL, OCTAL_TYPE);
W
wenjun 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    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 已提交
142 143 144 145 146 147 148 149 150 151 152
        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 已提交
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 179 180
        }
    }

    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 已提交
181
        printf("[Init] DoMount, invalid params<%zu, %zu> for %s.\n", endPos, startPos, srcStr);
W
wenjun 已提交
182 183 184 185 186 187
        return NULL;
    }

    size_t mallocLen = endPos - startPos + 1;
    char* retStr = (char*)malloc(mallocLen);
    if (retStr == NULL) {
Z
zhong_ning 已提交
188
        printf("[Init] DoMount, malloc failed! malloc size %zu, for %s.\n", mallocLen, srcStr);
W
wenjun 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        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 已提交
215
    } else if (strncmp(targetStr, "noexec", strlen("noexec")) == 0) {
W
wenjun 已提交
216
        (*mountflags) |= MS_NOEXEC;
G
Gymee 已提交
217
    } else if (strncmp(targetStr, "nosuid", strlen("nosuid")) == 0) {
W
wenjun 已提交
218
        (*mountflags) |= MS_NOSUID;
G
Gymee 已提交
219
    } else if (strncmp(targetStr, "rdonly", strlen("rdonly")) == 0) {
W
wenjun 已提交
220
        (*mountflags) |= MS_RDONLY;
G
Gymee 已提交
221 222
    } else {
        return 0;
W
wenjun 已提交
223
    }
G
Gymee 已提交
224
    return 1;
W
wenjun 已提交
225 226 227 228
}

static int CountSpaces(const char* cmdContent, size_t* spaceCnt, size_t* spacePosArr, size_t spacePosArrLen)
{
M
mamingshuai 已提交
229 230
    *spaceCnt = 0;
    size_t strLen = strlen(cmdContent);
W
wenjun 已提交
231
    for (size_t i = 0; i < strLen; ++i) {
M
mamingshuai 已提交
232 233 234 235 236 237 238
        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 已提交
239 240 241
        }
    }

M
mamingshuai 已提交
242 243 244
    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 已提交
245 246 247 248 249
        printf("[Init] DoMount, bad format for %s.\n", cmdContent);
        return 0;
    }

    // spaces should not be adjacent
M
mamingshuai 已提交
250 251
    for (size_t i = 1; i < (*spaceCnt); ++i) {
        if (spacePosArr[i] == spacePosArr[i - 1] + 1) {
W
wenjun 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
            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;
    }

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

W
wenjun 已提交
276
    char* source = CopySubStr(cmdContent, spacePosArr[indexOffset] + 1, spacePosArr[indexOffset + 1]);
M
mamingshuai 已提交
277 278 279 280
    if (source == NULL) {
        free(fileSysType);
        return;
    }
W
wenjun 已提交
281 282 283 284 285
    ++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 已提交
286 287 288 289 290
    if (target == NULL) {
        free(fileSysType);
        free(source);
        return;
    }
W
wenjun 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    ++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 已提交
308 309 310
    int mountRet;
    if (indexOffset >= spaceCnt) {    // no data
        mountRet = mount(source, target, fileSysType, mountflags, NULL);
W
wenjun 已提交
311
    } else {
M
mamingshuai 已提交
312 313 314 315 316 317
        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 已提交
318 319 320 321 322 323 324
    }

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

Z
zhong_ning 已提交
325
#ifndef OHOS_LITE
L
leon 已提交
326
#define OPTIONS_SIZE 128u
L
leon 已提交
327 328 329 330 331 332 333 334 335
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 已提交
336
        } else if (secondPtr != NULL) {
L
leon 已提交
337 338 339 340 341 342
            if (strncpy_s(options, OPTIONS_SIZE - 1, secondPtr, strlen(secondPtr)) != 0) {
                goto out;
            }
        }
    } else { // Only restPtr is option
        if (restPtr != NULL) {
Z
zhong_ning 已提交
343 344 345
            if (strncpy_s(options, OPTIONS_SIZE - 1, restPtr, strlen(restPtr)) != 0) {
                goto out;
            }
L
leon 已提交
346 347
        }
    }
Z
zhong_ning 已提交
348 349 350
    if (!fileName) {
        goto out;
    }
L
leon 已提交
351 352 353 354 355 356 357 358 359 360
    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:
Z
zhong_ning 已提交
361
    if (fd >= 0) {
L
leon 已提交
362 363 364 365 366
        close(fd);
    }
    return;
}

Z
zhong_ning 已提交
367 368 369 370 371 372
// format insmod <ko name> [-f] [options]
static void DoInsmod(const char *cmdContent)
{
    char *p = NULL;
    char *restPtr = NULL;
    char *fileName = NULL;
L
leon 已提交
373
    char *line = NULL;
Z
zhong_ning 已提交
374 375 376 377 378 379 380 381 382 383 384
    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 已提交
385

Z
zhong_ning 已提交
386 387
    if (memcpy_s(line, count, cmdContent, count) != EOK) {
        printf("[Init] memcpy failed\n");
Z
zhong_ning 已提交
388
        free(line);
L
leon 已提交
389
        return;
Z
zhong_ning 已提交
390 391 392 393 394
    }
    line[count] = '\0';
    do {
        if ((p = strtok_r(line, " ", &restPtr)) == NULL) {
            printf("[Init] debug, cannot get filename\n");
Z
zhong_ning 已提交
395
            free(line);
Z
zhong_ning 已提交
396 397 398 399 400 401 402 403 404 405 406
            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 已提交
407
    DoInsmodInternal(fileName, p, restPtr, flags);
Z
zhong_ning 已提交
408 409 410
    if (line != NULL) {
        free(line);
    }
L
leon 已提交
411
    return;
Z
zhong_ning 已提交
412
}
L
leon 已提交
413
#endif // OHOS_LITE
Z
zhong_ning 已提交
414

M
mamingshuai 已提交
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 475 476 477 478 479 480 481 482
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 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
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 已提交
499 500
    } else if (strncmp(curCmd->name, "loadcfg ", strlen("loadcfg ")) == 0) {
        DoLoadCfg(curCmd->cmdContent);
Z
zhong_ning 已提交
501
#ifndef OHOS_LITE
L
leon 已提交
502
    } else if (strncmp(curCmd->name, "insmod ", strlen("insmod ")) == 0) {
Z
zhong_ning 已提交
503 504
        DoInsmod(curCmd->cmdContent);
#endif
L
leon 已提交
505
    } else {
W
wenjun 已提交
506 507 508
        printf("[Init] DoCmd, unknown cmd name %s.\n", curCmd->name);
    }
}
M
mamingshuai 已提交
509