init_utils.c 13.9 KB
Newer Older
Z
zhong_ning 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2021 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.
 */
#include "init_utils.h"
S
sun_fan 已提交
16

Z
zhong_ning 已提交
17 18
#include <ctype.h>
#include <errno.h>
19
#include <dirent.h>
Z
zhong_ning 已提交
20
#include <fcntl.h>
S
sun_fan 已提交
21
#include <limits.h>
S
sun_fan 已提交
22
#include <pwd.h>
Z
zhong_ning 已提交
23
#include <stdlib.h>
S
sun_fan 已提交
24
#include <string.h>
Z
zhong_ning 已提交
25 26
#include <sys/stat.h>
#include <sys/types.h>
S
sun_fan 已提交
27
#include <time.h>
Z
zhong_ning 已提交
28
#include <unistd.h>
29

Z
zhong_ning 已提交
30 31
#include "init_log.h"
#include "securec.h"
X
xionglei6 已提交
32
#include "service_control.h"
Z
zhong_ning 已提交
33 34

#define MAX_BUF_SIZE  1024
X
xionglei6 已提交
35 36
#define MAX_DATA_BUFFER 2048

Z
zhong_ning 已提交
37 38 39 40 41
#ifdef STARTUP_UT
#define LOG_FILE_NAME "/media/sf_ubuntu/test/log.txt"
#else
#define LOG_FILE_NAME "/data/startup_log.txt"
#endif
Z
zhong_ning 已提交
42

Z
zhong_ning 已提交
43
#define MAX_JSON_FILE_LEN 102400    // max init.cfg size 100KB
44 45 46 47 48
#define CONVERT_MICROSEC_TO_SEC(x) ((x) / 1000 / 1000.0)
#ifndef DT_DIR
#define DT_DIR 4
#endif

S
sun_fan 已提交
49 50 51 52 53 54 55
#define THOUSAND_UNIT_INT 1000
#define THOUSAND_UNIT_FLOAT 1000.0

float ConvertMicrosecondToSecond(int x)
{
    return ((x / THOUSAND_UNIT_INT) / THOUSAND_UNIT_FLOAT);
}
Z
zhong_ning 已提交
56

S
sun_fan 已提交
57
uid_t DecodeUid(const char *name)
Z
zhong_ning 已提交
58
{
X
add ut  
xionglei6 已提交
59
    INIT_CHECK_RETURN_VALUE(name != NULL, -1);
S
sun_fan 已提交
60
    int digitFlag = 1;
X
xionglei6 已提交
61 62
    size_t nameLen = strlen(name);
    for (unsigned int i = 0; i < nameLen; ++i) {
Z
zhong_ning 已提交
63
        if (isalpha(name[i])) {
S
sun_fan 已提交
64
            digitFlag = 0;
Z
zhong_ning 已提交
65
            break;
Z
zhong_ning 已提交
66 67
        }
    }
Z
zhong_ning 已提交
68 69
    if (digitFlag) {
        errno = 0;
S
sun_fan 已提交
70
        uid_t result = strtoul(name, 0, DECIMAL_BASE);
X
add ut  
xionglei6 已提交
71
        INIT_CHECK_RETURN_VALUE(errno == 0, -1);
Z
zhong_ning 已提交
72 73
        return result;
    } else {
S
sun_fan 已提交
74 75
        struct passwd *userInf = getpwnam(name);
        if (userInf == NULL) {
Z
zhong_ning 已提交
76 77
            return -1;
        }
S
sun_fan 已提交
78
        return userInf->pw_uid;
Z
zhong_ning 已提交
79 80 81
    }
}

S
sun_fan 已提交
82
char *ReadFileToBuf(const char *configFile)
Z
zhong_ning 已提交
83
{
S
sun_fan 已提交
84 85
    char *buffer = NULL;
    FILE *fd = NULL;
Z
zhong_ning 已提交
86
    struct stat fileStat = {0};
X
add ut  
xionglei6 已提交
87
    INIT_CHECK_RETURN_VALUE(configFile != NULL && *configFile != '\0', NULL);
Z
zhong_ning 已提交
88 89 90
    do {
        if (stat(configFile, &fileStat) != 0 ||
            fileStat.st_size <= 0 || fileStat.st_size > MAX_JSON_FILE_LEN) {
Z
zhong_ning 已提交
91
            INIT_LOGE("Unexpected config file \" %s \", check if it exist. if exist, check file size", configFile);
Z
zhong_ning 已提交
92 93 94 95
            break;
        }
        fd = fopen(configFile, "r");
        if (fd == NULL) {
Z
zhong_ning 已提交
96
            INIT_LOGE("Open %s failed. err = %d", configFile, errno);
Z
zhong_ning 已提交
97 98
            break;
        }
S
sun_fan 已提交
99
        buffer = (char*)malloc((size_t)(fileStat.st_size + 1));
Z
zhong_ning 已提交
100
        if (buffer == NULL) {
Z
zhong_ning 已提交
101
            INIT_LOGE("Failed to allocate memory for config file, err = %d", errno);
Z
zhong_ning 已提交
102 103 104 105 106 107 108 109 110 111 112 113
            break;
        }

        if (fread(buffer, fileStat.st_size, 1, fd) != 1) {
            free(buffer);
            buffer = NULL;
            break;
        }
        buffer[fileStat.st_size] = '\0';
    } while (0);

    if (fd != NULL) {
114
        (void)fclose(fd);
Z
zhong_ning 已提交
115 116 117
        fd = NULL;
    }
    return buffer;
S
sun_fan 已提交
118 119
}

X
xionglei6 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
char *ReadFileData(const char *fileName)
{
    if (fileName == NULL) {
        return NULL;
    }
    char *buffer = NULL;
    int fd = -1;
    do {
        fd = open(fileName, O_RDONLY);
        INIT_ERROR_CHECK(fd >= 0, break, "Failed to read file %s", fileName);

        buffer = (char *)malloc(MAX_DATA_BUFFER); // fsmanager not create, can not get fileStat st_size
        INIT_ERROR_CHECK(buffer != NULL, break, "Failed to allocate memory for %s", fileName);
        ssize_t readLen = read(fd, buffer, MAX_DATA_BUFFER - 1);
        INIT_ERROR_CHECK(readLen > 0, break, "Failed to read data for %s", fileName);
        buffer[readLen] = '\0';
    } while (0);
    if (fd != -1) {
        close(fd);
    }
    return buffer;
}

int GetProcCmdlineValue(const char *name, const char *buffer, char *value, int length)
{
    INIT_ERROR_CHECK(name != NULL && buffer != NULL && value != NULL, return -1, "Failed get parameters");
    char *endData = (char *)buffer + strlen(buffer);
    char *tmp = strstr(buffer, name);
    do {
        if (tmp == NULL) {
            return -1;
        }
        tmp = tmp + strlen(name);
        while (tmp < endData && *tmp == ' ') {
            tmp++;
        }
        if (*tmp == '=') {
            break;
        }
        tmp = strstr(tmp + 1, name);
    } while (tmp < endData);
    tmp++;
    size_t i = 0;
    size_t endIndex = 0;
    while (tmp < endData && *tmp == ' ') {
        tmp++;
    }
    for (; i < (size_t)length; tmp++) {
        if (tmp >= endData) {
            endIndex = i;
            break;
        }
X
xionglei6 已提交
172
        if (*tmp == ' ' || *tmp == '\n' || *tmp == '\r' || *tmp == '\t') {
X
xionglei6 已提交
173
            endIndex = i;
X
xionglei6 已提交
174
            break;
X
xionglei6 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
        }
        if (*tmp == '=') {
            if (endIndex != 0) { // for root=uuid=xxxx
                break;
            }
            i = 0;
            endIndex = 0;
            continue;
        }
        value[i++] = *tmp;
    }
    if (i >= (size_t)length) {
        return -1;
    }
    value[endIndex] = '\0';
    return 0;
}

193
int SplitString(char *srcPtr, const char *del, char **dstPtr, int maxNum)
S
sun_fan 已提交
194
{
X
add ut  
xionglei6 已提交
195
    INIT_CHECK_RETURN_VALUE(srcPtr != NULL && dstPtr != NULL && del != NULL, -1);
S
sun_fan 已提交
196
    char *buf = NULL;
197
    dstPtr[0] = strtok_r(srcPtr, del, &buf);
S
sun_fan 已提交
198 199 200
    int counter = 0;
    while (dstPtr[counter] != NULL && (counter < maxNum)) {
        counter++;
X
xionglei6 已提交
201
        if (counter >= maxNum) {
X
xionglei6 已提交
202
            break;
X
xionglei6 已提交
203
        }
X
xionglei6 已提交
204
        dstPtr[counter] = strtok_r(NULL, del, &buf);
S
sun_fan 已提交
205
    }
S
sun_fan 已提交
206
    return counter;
S
sun_fan 已提交
207
}
Z
zhong_ning 已提交
208

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
void FreeStringVector(char **vector, int count)
{
    if (vector != NULL) {
        for (int i = 0; i < count; i++) {
            if (vector[i] != NULL) {
                free(vector[i]);
            }
        }
        free(vector);
    }
}

char **SplitStringExt(char *buffer, const char *del, int *returnCount, int maxItemCount)
{
    INIT_CHECK_RETURN_VALUE((maxItemCount >= 0) && (buffer != NULL) && (del != NULL) && (returnCount != NULL), NULL);
    // Why is this number?
    // Now we use this function to split a string with a given delimeter
    // We do not know how many sub-strings out there after splitting.
    // 50 is just a guess value.
    const int defaultItemCounts = 50;
    int itemCounts = maxItemCount;

    if (maxItemCount > defaultItemCounts) {
        itemCounts = defaultItemCounts;
    }
    char **items = (char **)malloc(sizeof(char*) * itemCounts);
X
add ut  
xionglei6 已提交
235
    INIT_ERROR_CHECK(items != NULL, return NULL, "No enough memory to store items");
236 237 238 239 240
    char *rest = NULL;
    char *p = strtok_r(buffer, del, &rest);
    int count = 0;
    while (p != NULL) {
        if (count > itemCounts - 1) {
4
411148299@qq.com 已提交
241
            itemCounts += (itemCounts / 2) + 1; // 2 Request to increase the original memory by half.
X
xionglei6 已提交
242
            INIT_LOGV("Too many items,expand size");
243
            char **expand = (char **)(realloc(items, sizeof(char *) * itemCounts));
X
add ut  
xionglei6 已提交
244 245
            INIT_ERROR_CHECK(expand != NULL, FreeStringVector(items, count);
                return NULL, "Failed to expand memory for uevent config parser");
246 247 248 249
            items = expand;
        }
        size_t len = strlen(p);
        items[count] = (char *)malloc(len + 1);
X
add ut  
xionglei6 已提交
250 251
        INIT_CHECK(items[count] != NULL, FreeStringVector(items, count);
            return NULL);
252 253 254 255 256 257 258 259 260 261 262 263 264
        if (strncpy_s(items[count], len + 1, p, len) != EOK) {
            INIT_LOGE("Copy string failed");
            FreeStringVector(items, count);
            return NULL;
        }
        items[count][len] = '\0';
        count++;
        p = strtok_r(NULL, del, &rest);
    }
    *returnCount = count;
    return items;
}

H
huangshan 已提交
265
void WaitForFile(const char *source, unsigned int maxSecond)
Z
zhong_ning 已提交
266
{
H
huangshan 已提交
267
    INIT_ERROR_CHECK(maxSecond <= WAIT_MAX_SECOND, maxSecond = WAIT_MAX_SECOND, "WaitForFile max time is 5s");
268
    struct stat sourceInfo = {};
X
xionglei6 已提交
269
    unsigned int waitTime = 500000;
H
huangshan 已提交
270 271
    /* 500ms interval, check maxSecond*2 times total */
    unsigned int maxCount = maxSecond * 2;
Z
fix bug  
zhong_ning 已提交
272
    unsigned int count = 0;
Z
zhong_ning 已提交
273 274 275
    do {
        usleep(waitTime);
        count++;
H
huangshan 已提交
276 277
    } while ((stat(source, &sourceInfo) < 0) && (errno == ENOENT) && (count < maxCount));
    INIT_CHECK_ONLY_ELOG(count != maxCount, "wait for file:%s failed after %d second.", source, maxSecond);
Z
zhong_ning 已提交
278 279 280
    return;
}

S
sun_fan 已提交
281
size_t WriteAll(int fd, const char *buffer, size_t size)
S
sun_fan 已提交
282
{
X
add ut  
xionglei6 已提交
283
    INIT_CHECK_RETURN_VALUE(buffer != NULL && fd >= 0 && *buffer != '\0', 0);
S
sun_fan 已提交
284
    const char *p = buffer;
S
sun_fan 已提交
285
    size_t left = size;
X
add ut  
xionglei6 已提交
286
    ssize_t written;
S
sun_fan 已提交
287 288 289 290 291 292 293 294 295 296 297 298
    while (left > 0) {
        do {
            written = write(fd, p, left);
        } while (written < 0 && errno == EINTR);
        if (written < 0) {
            INIT_LOGE("Failed to write %lu bytes, err = %d", left, errno);
            break;
        }
        p += written;
        left -= written;
    }
    return size - left;
S
sun_fan 已提交
299 300
}

301
char *GetRealPath(const char *source)
S
sun_fan 已提交
302
{
X
add ut  
xionglei6 已提交
303
    INIT_CHECK_RETURN_VALUE(source != NULL, NULL);
304 305
    char *path = realpath(source, NULL);
    if (path == NULL) {
X
add ut  
xionglei6 已提交
306
        INIT_ERROR_CHECK(errno == ENOENT, return NULL, "Failed to resolve %s real path err=%d", source, errno);
S
sun_fan 已提交
307
    }
308
    return path;
S
sun_fan 已提交
309 310 311 312 313 314 315 316 317 318
}

int MakeDir(const char *dir, mode_t mode)
{
    int rc = -1;
    if (dir == NULL || *dir == '\0') {
        errno = EINVAL;
        return rc;
    }
    rc = mkdir(dir, mode);
X
add ut  
xionglei6 已提交
319 320
    INIT_ERROR_CHECK(!(rc < 0 && errno != EEXIST), return rc,
        "Create directory \" %s \" failed, err = %d", dir, errno);
S
sun_fan 已提交
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    // create dir success or it already exist.
    return 0;
}

int MakeDirRecursive(const char *dir, mode_t mode)
{
    int rc = -1;
    char buffer[PATH_MAX] = {};
    const char *p = NULL;
    if (dir == NULL || *dir == '\0') {
        errno = EINVAL;
        return rc;
    }
    p = dir;
    char *slash = strchr(dir, '/');
    while (slash != NULL) {
        int gap = slash - p;
        p = slash + 1;
        if (gap == 0) {
            slash = strchr(p, '/');
            continue;
        }
        if (gap < 0) { // end with '/'
            break;
        }
X
add ut  
xionglei6 已提交
346
        INIT_CHECK_RETURN_VALUE(memcpy_s(buffer, PATH_MAX, dir, p - dir - 1) == 0, -1);
S
sun_fan 已提交
347
        rc = MakeDir(buffer, mode);
X
add ut  
xionglei6 已提交
348
        INIT_CHECK_RETURN_VALUE(rc >= 0, rc);
S
sun_fan 已提交
349 350 351 352 353 354 355 356 357 358 359 360
        slash = strchr(p, '/');
    }
    return MakeDir(dir, mode);
}

int StringToInt(const char *str, int defaultValue)
{
    if (str == NULL || *str == '\0') {
        return defaultValue;
    }
    errno = 0;
    int value = (int)strtoul(str, NULL, DECIMAL_BASE);
X
add ut  
xionglei6 已提交
361
    return (errno != 0) ? defaultValue : value;
362 363 364 365 366
}

int ReadFileInDir(const char *dirPath, const char *includeExt,
    int (*processFile)(const char *fileName, void *context), void *context)
{
X
add ut  
xionglei6 已提交
367
    INIT_CHECK_RETURN_VALUE(dirPath != NULL && processFile != NULL, -1);
368 369 370 371 372 373 374 375 376 377 378
    DIR *pDir = opendir(dirPath);
    INIT_ERROR_CHECK(pDir != NULL, return -1, "Read dir :%s failed.%d", dirPath, errno);
    char *fileName = malloc(MAX_BUF_SIZE);
    INIT_ERROR_CHECK(fileName != NULL, closedir(pDir);
        return -1, "Failed to malloc for %s", dirPath);

    struct dirent *dp;
    while ((dp = readdir(pDir)) != NULL) {
        if (dp->d_type == DT_DIR) {
            continue;
        }
X
xionglei6 已提交
379
        INIT_LOGV("ReadFileInDir %s", dp->d_name);
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        if (includeExt != NULL) {
            char *tmp = strstr(dp->d_name, includeExt);
            if (tmp == NULL) {
                continue;
            }
            if (strcmp(tmp, includeExt) != 0) {
                continue;
            }
        }
        int ret = snprintf_s(fileName, MAX_BUF_SIZE, MAX_BUF_SIZE - 1, "%s/%s", dirPath, dp->d_name);
        if (ret <= 0) {
            INIT_LOGE("Failed to get file name for %s", dp->d_name);
            continue;
        }
        struct stat st;
        if (stat(fileName, &st) == 0) {
            processFile(fileName, context);
        }
    }
    free(fileName);
    closedir(pDir);
    return 0;
S
sun_fan 已提交
402 403
}

404 405 406 407 408 409 410 411 412 413
// Check if in updater mode.
int InUpdaterMode(void)
{
    const char * const updaterExecutabeFile = "/bin/updater";
    if (access(updaterExecutabeFile, X_OK) == 0) {
        return 1;
    } else {
        return 0;
    }
}
X
xionglei6 已提交
414

T
toutes 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
int InChargerMode(void)
{
    char *data = ReadFileData(PARAM_CMD_LINE);
    char value[CMDLINE_VALUE_LEN_MAX];
    int ret = 0;

    if ((GetProcCmdlineValue("reboot_reason", data, value, CMDLINE_VALUE_LEN_MAX) == 0) &&
        (strcmp(value, "poweroff_charge") == 0)) {
        ret = 1;
    }
    INIT_LOGE("GetProcCmdlineValue():reboot_reason=%s ,ret=%d\n", value, ret);
    free(data);
    return ret;
}

X
xionglei6 已提交
430 431 432 433 434 435 436 437 438 439
int StringReplaceChr(char *strl, char oldChr, char newChr)
{
    INIT_ERROR_CHECK(strl != NULL, return -1, "Invalid parament");
    char *p = strl;
    while (*p != '\0') {
        if (*p == oldChr) {
            *p = newChr;
        }
        p++;
    }
X
xionglei6 已提交
440
    INIT_LOGV("strl is %s", strl);
X
xionglei6 已提交
441 442
    return 0;
}
X
xionglei6 已提交
443 444 445

int GetMapValue(const char *name, const InitArgInfo *infos, int argNum, int defValue)
{
X
xionglei6 已提交
446 447 448
    if ((argNum == 0) || (infos == NULL) || (name == NULL)) {
        return defValue;
    }
X
xionglei6 已提交
449 450 451 452 453 454
    for (int i = 0; i < argNum; i++) {
        if (strcmp(infos[i].name, name) == 0) {
            return infos[i].value;
        }
    }
    return defValue;
X
xionglei6 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
}

const static InitArgInfo g_servieStatusMap[] = {
    {"created", SERVICE_IDLE},
    {"starting", SERVICE_STARTING},
    {"running", SERVICE_STARTED},
    {"ready", SERVICE_READY},
    {"stopping", SERVICE_STOPPING},
    {"stopped", SERVICE_STOPPED},
    {"suspended", SERVICE_SUSPENDED},
    {"freezed", SERVICE_FREEZED},
    {"disabled", SERVICE_DISABLED},
    {"critial", SERVICE_CRITIAL}
};

const InitArgInfo *GetServieStatusMap(int *size)
{
    if (size != 0) {
        *size = ARRAY_LENGTH(g_servieStatusMap);
    }
    return g_servieStatusMap;
}