init_service_manager.c 42.5 KB
Newer Older
1
/*
2
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * 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_service_manager.h"

#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
21
#include <sys/wait.h>
22
#include <unistd.h>
C
cheng_jinsong 已提交
23
#include <sys/ioctl.h>
24 25
#include "cJSON.h"
#include "init.h"
X
xionglei6 已提交
26
#include "init_group_manager.h"
Z
zhong_ning 已提交
27
#include "init_jobs_internal.h"
28
#include "init_log.h"
X
xionglei6 已提交
29
#include "init_service_file.h"
30 31 32
#include "init_service_socket.h"
#include "init_utils.h"
#include "securec.h"
X
xionglei6 已提交
33
#include "service_control.h"
C
cheng_jinsong 已提交
34
#include "sys_param.h"
35 36 37
#ifdef ASAN_DETECTOR
#include "init_param.h"
#endif
X
xionglei6 已提交
38

39 40 41 42 43
#ifndef OHOS_LITE
#include "hookmgr.h"
#include "bootstage.h"
#endif

44
// All service processes that init will fork+exec.
X
xionglei6 已提交
45
static ServiceSpace g_serviceSpace = { 0 };
X
xionglei6 已提交
46 47 48 49
static const int CRITICAL_DEFAULT_CRASH_TIME = 20;
// maximum number of crashes within time CRITICAL_DEFAULT_CRASH_TIME for one service
static const int CRITICAL_DEFAULT_CRASH_COUNT =  4;
static const int CRITICAL_CONFIG_ARRAY_LEN = 3;
50 51 52

static void FreeServiceArg(ServiceArgs *arg)
{
X
add ut  
xionglei6 已提交
53
    if (arg == NULL) {
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
        return;
    }
    for (int i = 0; i < arg->count; ++i) {
        if (arg->argv[i] != NULL) {
            free(arg->argv[i]);
            arg->argv[i] = NULL;
        }
    }
    free(arg->argv);
    arg->argv = NULL;
    arg->count = 0;
}

static void FreeServiceSocket(ServiceSocket *sockopt)
{
    while (sockopt != NULL) {
        ServiceSocket *tmp = sockopt;
        if (tmp->sockFd >= 0) {
            close(tmp->sockFd);
            tmp->sockFd = -1;
        }
        sockopt = sockopt->next;
        free(tmp);
    }
    return;
}

X
xionglei6 已提交
81
Service *AddService(const char *name)
82
{
X
xionglei6 已提交
83 84
    // check service in group
    if (CheckNodeValid(NODE_TYPE_SERVICES, name) != 0) {
X
xionglei6 已提交
85
        INIT_LOGI("Service %s not exist in group ", name);
X
xionglei6 已提交
86 87 88 89
        return NULL;
    }
    InitGroupNode *node = AddGroupNode(NODE_TYPE_SERVICES, name);
    if (node == NULL) {
X
xionglei6 已提交
90
        INIT_LOGE("Failed to create service name %s", name);
X
xionglei6 已提交
91 92
        return NULL;
    }
93 94
    Service *service = (Service *)calloc(1, sizeof(Service));
    INIT_ERROR_CHECK(service != NULL, return NULL, "Failed to malloc for service");
X
xionglei6 已提交
95 96
    node->data.service = service;
    service->name = node->name;
X
xionglei6 已提交
97
    service->status = SERVICE_IDLE;
C
cheng_jinsong 已提交
98
    service->cpuSet = NULL;
M
Mupceet 已提交
99
    OH_ListInit(&service->extDataNode);
100
    g_serviceSpace.serviceCount++;
X
xionglei6 已提交
101
    INIT_LOGV("AddService %s", node->name);
102 103 104
    return service;
}

X
xionglei6 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118
static void FreeServiceFile(ServiceFile *fileOpt)
{
    while (fileOpt != NULL) {
        ServiceFile *tmp = fileOpt;
        if (tmp->fd >= 0) {
            close(tmp->fd);
            tmp->fd = -1;
        }
        fileOpt = fileOpt->next;
        free(tmp);
    }
    return;
}

X
add ut  
xionglei6 已提交
119
void ReleaseService(Service *service)
120 121 122 123 124 125
{
    if (service == NULL) {
        return;
    }
    FreeServiceArg(&service->pathArgs);
    FreeServiceArg(&service->writePidArgs);
126
    FreeServiceArg(&service->capsArgs);
Y
yichengzhao 已提交
127
    FreeServiceArg(&service->permArgs);
Y
yichengzhao 已提交
128
    FreeServiceArg(&service->permAclsArgs);
129 130 131 132 133 134 135 136 137 138 139 140

    if (service->servPerm.caps != NULL) {
        free(service->servPerm.caps);
        service->servPerm.caps = NULL;
    }
    service->servPerm.capsCnt = 0;
    if (service->servPerm.gIDArray != NULL) {
        free(service->servPerm.gIDArray);
        service->servPerm.gIDArray = NULL;
    }
    service->servPerm.gIDCnt = 0;
    FreeServiceSocket(service->socketCfg);
X
xionglei6 已提交
141
    FreeServiceFile(service->fileCfg);
142

C
codex  
chengjinsong 已提交
143
    if (service->apl != NULL) {
144 145 146
        free(service->apl);
        service->apl = NULL;
    }
C
cheng_jinsong 已提交
147 148 149 150 151 152
    for (size_t i = 0; i < JOB_ON_MAX; i++) {
        if (service->serviceJobs.jobsName[i] != NULL) {
            free(service->serviceJobs.jobsName[i]);
        }
        service->serviceJobs.jobsName[i] = NULL;
    }
C
cheng_jinsong 已提交
153 154 155 156
    if (service->cpuSet != NULL) {
        free(service->cpuSet);
        service->cpuSet = NULL;
    }
M
Mupceet 已提交
157 158 159 160 161 162
#ifndef OHOS_LITE
    // clear ext data
    SERVICE_INFO_CTX ctx = {0};
    ctx.serviceName = service->name;
    HookMgrExecute(GetBootStageHookMgr(), INIT_SERVICE_CLEAR, (void *)&ctx, NULL);
#endif
X
xionglei6 已提交
163 164 165 166
    g_serviceSpace.serviceCount--;
    InitGroupNode *groupNode = GetGroupNode(NODE_TYPE_SERVICES, service->name);
    if (groupNode != NULL) {
        groupNode->data.service = NULL;
167 168 169 170
    }
    free(service);
}

171 172 173
static char *GetStringValue(const cJSON *json, const char *name, size_t *strLen)
{
    char *fieldStr = cJSON_GetStringValue(cJSON_GetObjectItem(json, name));
174
    INIT_CHECK(fieldStr != NULL, return NULL);
175 176 177 178
    *strLen = strlen(fieldStr);
    return fieldStr;
}

179 180 181 182 183 184 185
cJSON *GetArrayItem(const cJSON *fileRoot, int *arrSize, const char *arrName)
{
    cJSON *arrItem = cJSON_GetObjectItemCaseSensitive(fileRoot, arrName);
    if (!cJSON_IsArray(arrItem)) {
        return NULL;
    }
    *arrSize = cJSON_GetArraySize(arrItem);
X
add ut  
xionglei6 已提交
186
    INIT_CHECK_RETURN_VALUE(*arrSize > 0, NULL);
187 188 189 190 191 192 193 194 195 196 197 198 199
    return arrItem;
}

static int GetServiceArgs(const cJSON *argJson, const char *name, int maxCount, ServiceArgs *args)
{
    INIT_ERROR_CHECK(argJson != NULL, return SERVICE_FAILURE, "Invalid argJson");
    cJSON *obj = cJSON_GetObjectItem(argJson, name);
    INIT_CHECK(obj != NULL, return SERVICE_FAILURE);

    int ret = cJSON_IsArray(obj);
    INIT_ERROR_CHECK(ret, return SERVICE_FAILURE, "Invalid type");
    int count = cJSON_GetArraySize(obj);
    INIT_ERROR_CHECK((count > 0) && (count < maxCount), return SERVICE_FAILURE, "Array size = %d is wrong", count);
200 201 202
    if ((args->argv != NULL) && (args->count > 0)) {
        FreeServiceArg(args);
    }
203 204 205 206 207
    args->argv = (char **)malloc((count + 1) * sizeof(char *));
    INIT_ERROR_CHECK(args->argv != NULL, return SERVICE_FAILURE, "Failed to malloc for argv");
    for (int i = 0; i < count + 1; ++i) {
        args->argv[i] = NULL;
    }
X
xionglei6 已提交
208
    // ServiceArgs have a variety of uses, some requiring a NULL ending, some not
Y
yichengzhao 已提交
209 210
    if (strcmp(name, D_CAPS_STR_IN_CFG) != 0 && strcmp(name, "permission_acls") != 0 &&
        strcmp(name, "permission") != 0) {
211 212 213 214
        args->count = count + 1;
    } else {
        args->count = count;
    }
215 216 217 218 219
    for (int i = 0; i < count; ++i) {
        char *curParam = cJSON_GetStringValue(cJSON_GetArrayItem(obj, i));
        INIT_ERROR_CHECK(curParam != NULL, return SERVICE_FAILURE, "Invalid arg %d", i);
        INIT_ERROR_CHECK(strlen(curParam) <= MAX_ONE_ARG_LEN, return SERVICE_FAILURE, "Arg %s is tool long", curParam);
        args->argv[i] = strdup(curParam);
C
fix log  
cheng_jinsong 已提交
220
        INIT_ERROR_CHECK(args->argv[i] != NULL, return SERVICE_FAILURE, "Failed to duplicate argument %s", curParam);
221 222 223 224 225 226 227 228 229 230 231 232 233
    }
    return SERVICE_SUCCESS;
}

static int GetUid(cJSON *json, uid_t *uid)
{
    INIT_CHECK_RETURN_VALUE(json != NULL, SERVICE_SUCCESS);
    if (cJSON_IsString(json)) {
        char *str = cJSON_GetStringValue(json);
        INIT_ERROR_CHECK(str != NULL, return SERVICE_FAILURE, "Invalid str");
        *uid = DecodeUid(str);
    } else if (cJSON_IsNumber(json)) {
        *uid = (uid_t)cJSON_GetNumberValue(json);
M
codex  
Mupceet 已提交
234 235
    } else {
        *uid = (uid_t)(-1);
236
    }
X
add ut  
xionglei6 已提交
237
    INIT_CHECK_RETURN_VALUE(*uid != (uid_t)(-1), SERVICE_FAILURE);
238 239 240
    return SERVICE_SUCCESS;
}

M
initgid  
Mupceet 已提交
241 242 243 244 245 246 247 248 249
static int GetGid(cJSON *json, gid_t *gid, Service *curServ)
{
    INIT_CHECK_RETURN_VALUE(json != NULL, SERVICE_SUCCESS);
    if (cJSON_IsString(json)) {
        char *str = cJSON_GetStringValue(json);
        INIT_ERROR_CHECK(str != NULL, return SERVICE_FAILURE, "Failed to get gid for %s", curServ->name);
        *gid = DecodeGid(str);
    } else if (cJSON_IsNumber(json)) {
        *gid = (gid_t)cJSON_GetNumberValue(json);
C
cheng_jinsong 已提交
250 251 252
    } else {
        INIT_LOGW("Service %s with invalid gid configuration", curServ->name);
        *gid = -1; // Invalid gid, set as -1
M
initgid  
Mupceet 已提交
253 254 255 256 257
    }
    INIT_ERROR_CHECK(*gid != (gid_t)(-1), return SERVICE_FAILURE, "Failed to get gid for %s", curServ->name);
    return SERVICE_SUCCESS;
}

258 259
static int GetServiceGids(const cJSON *curArrItem, Service *curServ)
{
X
xionglei6 已提交
260
    int gidCount;
261
    cJSON *arrItem = cJSON_GetObjectItemCaseSensitive(curArrItem, GID_STR_IN_CFG);
262 263 264
    if (!arrItem) {
        return SERVICE_SUCCESS;
    } else if (!cJSON_IsArray(arrItem)) {
265 266 267 268
        gidCount = 1;
    } else {
        gidCount = cJSON_GetArraySize(arrItem);
    }
X
add ut  
xionglei6 已提交
269 270
    INIT_ERROR_CHECK((gidCount != 0) && (gidCount <= NGROUPS_MAX + 1), return SERVICE_FAILURE,
        "Invalid gid count %d", gidCount);
271 272 273
    if (curServ->servPerm.gIDArray != NULL) {
        free(curServ->servPerm.gIDArray);
    }
274
    curServ->servPerm.gIDArray = (gid_t *)malloc(sizeof(gid_t) * gidCount);
C
fix log  
cheng_jinsong 已提交
275
    INIT_ERROR_CHECK(curServ->servPerm.gIDArray != NULL, return SERVICE_FAILURE, "Failed to malloc err=%d", errno);
276 277 278 279
    curServ->servPerm.gIDCnt = gidCount;

    gid_t gid;
    if (!cJSON_IsArray(arrItem)) {
M
initgid  
Mupceet 已提交
280
        int ret = GetGid(arrItem, &gid, curServ);
C
fix log  
cheng_jinsong 已提交
281
        INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Parse service %s gid failed.", curServ->name);
282 283 284
        curServ->servPerm.gIDArray[0] = gid;
        return SERVICE_SUCCESS;
    }
285
    int gidArrayIndex = 0;
286 287
    for (int i = 0; i < gidCount; ++i) {
        cJSON *item = cJSON_GetArrayItem(arrItem, i);
M
initgid  
Mupceet 已提交
288
        int ret = GetGid(item, &gid, curServ);
289
        if (ret != 0) {
C
fix log  
cheng_jinsong 已提交
290
            INIT_LOGW("Parse service %s gid failed from item %s.", curServ->name, cJSON_Print(item));
291 292
            continue;
        }
293
        curServ->servPerm.gIDArray[gidArrayIndex++] = gid;
294
    }
295
    curServ->servPerm.gIDCnt = gidArrayIndex;
296 297 298 299 300 301 302 303 304 305
    return SERVICE_SUCCESS;
}

static int GetServiceAttr(const cJSON *curArrItem, Service *curServ, const char *attrName, int flag,
    int (*processAttr)(Service *curServ, const char *attrName, int value, int flag))
{
    cJSON *filedJ = cJSON_GetObjectItem(curArrItem, attrName);
    if (filedJ == NULL) {
        return SERVICE_SUCCESS;
    }
X
add ut  
xionglei6 已提交
306 307
    INIT_ERROR_CHECK(cJSON_IsNumber(filedJ), return SERVICE_FAILURE,
        "%s is null or is not a number, service name is %s", attrName, curServ->name);
308
    curServ->attribute &= ~flag;
309 310 311 312 313 314 315 316 317 318
    int value = (int)cJSON_GetNumberValue(filedJ);
    if (processAttr == NULL) {
        if (value == 1) {
            curServ->attribute |= flag;
        }
        return 0;
    }
    return processAttr(curServ, attrName, value, flag);
}

319
static int ParseSocketFamily(cJSON *json, ServiceSocket *sockopt)
320
{
321 322 323 324 325
    sockopt->family = AF_UNIX;
    size_t strLen = 0;
    char *stringValue = GetStringValue(json, "family", &strLen);
    INIT_ERROR_CHECK((stringValue != NULL) && (strLen > 0), return SERVICE_FAILURE,
        "Failed to get string for family");
C
cheng_jinsong 已提交
326
    if (strcmp(stringValue, "AF_UNIX") == 0) {
327 328 329
        sockopt->family = AF_UNIX;
    } else if (strncmp(stringValue, "AF_NETLINK", strLen) == 0) {
        sockopt->family = AF_NETLINK;
330
    }
331 332
    return 0;
}
333

334 335
static int ParseSocketType(cJSON *json, ServiceSocket *sockopt)
{
336
    sockopt->type = SOCK_SEQPACKET;
337 338 339 340 341 342 343
    size_t strLen = 0;
    char *stringValue = GetStringValue(json, "type", &strLen);
    INIT_ERROR_CHECK((stringValue != NULL) && (strLen > 0), return SERVICE_FAILURE,
        "Failed to get string for type");
    if (strncmp(stringValue, "SOCK_SEQPACKET", strLen) == 0) {
        sockopt->type = SOCK_SEQPACKET;
    } else if (strncmp(stringValue, "SOCK_STREAM", strLen) == 0) {
344
        sockopt->type = SOCK_STREAM;
345
    } else if (strncmp(stringValue, "SOCK_DGRAM", strLen) == 0) {
346 347
        sockopt->type = SOCK_DGRAM;
    }
348 349 350 351 352 353 354 355 356 357 358 359 360
    return 0;
}

static int ParseSocketProtocol(cJSON *json, ServiceSocket *sockopt)
{
    sockopt->protocol = 0;
    size_t strLen = 0;
    char *stringValue = GetStringValue(json, "protocol", &strLen);
    INIT_ERROR_CHECK((stringValue != NULL) && (strLen > 0), return SERVICE_FAILURE,
        "Failed to get string for protocol");
    if (strncmp(stringValue, "default", strLen) == 0) {
        sockopt->protocol = 0;
    } else if (strncmp(stringValue, "NETLINK_KOBJECT_UEVENT", strLen) == 0) {
M
Mupceet 已提交
361
#ifndef __LITEOS_A__
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
        sockopt->protocol = NETLINK_KOBJECT_UEVENT;
#else
        return -1;
#endif
    }
    return 0;
}

static int ParseSocketOption(cJSON *json, ServiceSocket *sockopt)
{
    sockopt->option = 0;
    unsigned int tempType = 0;
    int typeCnt = 0;
    char *stringValue = NULL;
    cJSON *typeItem = NULL;
    cJSON *typeArray = GetArrayItem(json, &typeCnt, "option");
    INIT_CHECK((typeArray != NULL) && (typeCnt > 0), return 0);
    for (int i = 0; i < typeCnt; ++i) {
        typeItem = cJSON_GetArrayItem(typeArray, i);
        INIT_CHECK_RETURN_VALUE(cJSON_IsString(typeItem), SERVICE_FAILURE);
        stringValue = cJSON_GetStringValue(typeItem);
        INIT_ERROR_CHECK(stringValue != NULL, return SERVICE_FAILURE, "Failed to get string for type");
        if (strncmp(stringValue, "SOCKET_OPTION_PASSCRED", strlen(stringValue)) == 0) {
            sockopt->option |= SOCKET_OPTION_PASSCRED;
        } else if (strncmp(stringValue, "SOCKET_OPTION_RCVBUFFORCE", strlen(stringValue)) == 0) {
            sockopt->option |= SOCKET_OPTION_RCVBUFFORCE;
        } else if (strncmp(stringValue, "SOCK_CLOEXEC", strlen(stringValue)) == 0) {
            tempType |= SOCK_CLOEXEC;
        } else if (strncmp(stringValue, "SOCK_NONBLOCK", strlen(stringValue)) == 0) {
            tempType |= SOCK_NONBLOCK;
        }
393
    }
394 395
    if (tempType != 0) {
        sockopt->type |= tempType;
396
    }
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    return 0;
}

static int AddServiceSocket(cJSON *json, Service *service)
{
    size_t strLen = 0;
    char* fieldStr = GetStringValue(json, "name", &strLen);
    INIT_ERROR_CHECK(fieldStr != NULL, return SERVICE_FAILURE, "Failed to get socket name");
    INIT_ERROR_CHECK(strLen <= MAX_SERVICE_NAME, return SERVICE_FAILURE, "socket name exceeds length limit");
    ServiceSocket *sockopt = (ServiceSocket *)calloc(1, sizeof(ServiceSocket) + strLen + 1);
    INIT_INFO_CHECK(sockopt != NULL, return SERVICE_FAILURE, "Failed to malloc for service %s", service->name);

    int ret = strcpy_s(sockopt->name, strLen + 1, fieldStr);
    INIT_INFO_CHECK(ret == 0, free(sockopt); sockopt = NULL; return SERVICE_FAILURE,
        "Failed to copy socket name %s", fieldStr);
X
xionglei6 已提交
412
    sockopt->sockFd = -1;
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    sockopt->watcher = NULL;

    ret = ParseSocketFamily(json, sockopt);
    INIT_ERROR_CHECK(ret == 0, free(sockopt); sockopt = NULL; return SERVICE_FAILURE,
        "Failed to parse socket family");
    ret = ParseSocketType(json, sockopt);
    INIT_ERROR_CHECK(ret == 0, free(sockopt); sockopt = NULL; return SERVICE_FAILURE,
        "Failed to parse socket type");
    ret = ParseSocketProtocol(json, sockopt);
    INIT_ERROR_CHECK(ret == 0, free(sockopt); sockopt = NULL; return SERVICE_FAILURE,
        "Failed to parse socket protocol");

    char *stringValue = GetStringValue(json, "permissions", &strLen);
    INIT_ERROR_CHECK((stringValue != NULL) && (strLen > 0), free(sockopt); sockopt = NULL; return SERVICE_FAILURE,
        "Failed to get string for permissions");
    sockopt->perm = strtoul(stringValue, 0, OCTAL_BASE);
    stringValue = GetStringValue(json, "uid", &strLen);
    INIT_ERROR_CHECK((stringValue != NULL) && (strLen > 0), free(sockopt); sockopt = NULL; return SERVICE_FAILURE,
        "Failed to get string for uid");
    sockopt->uid = DecodeUid(stringValue);
    stringValue = GetStringValue(json, "gid", &strLen);
    INIT_ERROR_CHECK((stringValue != NULL) && (strLen > 0), free(sockopt); sockopt = NULL; return SERVICE_FAILURE,
        "Failed to get string for gid");
M
Mupceet 已提交
436
    sockopt->gid = DecodeGid(stringValue);
437 438 439 440 441 442
    INIT_ERROR_CHECK((sockopt->uid != (uid_t)-1) && (sockopt->gid != (uid_t)-1),
        free(sockopt); sockopt = NULL; return SERVICE_FAILURE, "Invalid uid or gid");
    ret = ParseSocketOption(json, sockopt);
    INIT_ERROR_CHECK(ret == 0, free(sockopt); sockopt = NULL; return SERVICE_FAILURE,
        "Failed to parse socket option");

443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    sockopt->next = NULL;
    if (service->socketCfg == NULL) {
        service->socketCfg = sockopt;
    } else {
        sockopt->next = service->socketCfg->next;
        service->socketCfg->next = sockopt;
    }
    return SERVICE_SUCCESS;
}

static int ParseServiceSocket(const cJSON *curArrItem, Service *curServ)
{
    int sockCnt = 0;
    cJSON *filedJ = GetArrayItem(curArrItem, &sockCnt, "socket");
    INIT_CHECK(filedJ != NULL && sockCnt > 0, return SERVICE_FAILURE);
458 459 460

    CloseServiceSocket(curServ);
    FreeServiceSocket(curServ->socketCfg);
461 462 463 464 465 466
    int ret = 0;
    curServ->socketCfg = NULL;
    for (int i = 0; i < sockCnt; ++i) {
        cJSON *sockJ = cJSON_GetArrayItem(filedJ, i);
        ret = AddServiceSocket(sockJ, curServ);
        if (ret != 0) {
467
            return ret;
468 469
        }
    }
470 471 472
    if (IsOnDemandService(curServ)) {
        ret = CreateServiceSocket(curServ);
    }
473 474 475
    return ret;
}

X
xionglei6 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489
static int AddServiceFile(cJSON *json, Service *service)
{
    if (!cJSON_IsString(json) || !cJSON_GetStringValue(json)) {
        return SERVICE_FAILURE;
    }
    char *fileStr = cJSON_GetStringValue(json);
    char *opt[FILE_OPT_NUMS] = {
        NULL,
    };
    int num = SplitString(fileStr, " ", opt, FILE_OPT_NUMS);
    if (num != FILE_OPT_NUMS) {
        return SERVICE_FAILURE;
    }
    if (opt[SERVICE_FILE_NAME] == NULL || opt[SERVICE_FILE_FLAGS] == NULL || opt[SERVICE_FILE_PERM] == NULL ||
X
xionglei6 已提交
490
        opt[SERVICE_FILE_UID] == NULL || opt[SERVICE_FILE_GID] == NULL) {
X
xionglei6 已提交
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
        INIT_LOGE("Invalid file opt");
        return SERVICE_FAILURE;
    }
    ServiceFile *fileOpt = (ServiceFile *)calloc(1, sizeof(ServiceFile) + strlen(opt[SERVICE_FILE_NAME]) + 1);
    INIT_INFO_CHECK(fileOpt != NULL, return SERVICE_FAILURE, "Failed to calloc for file %s", opt[SERVICE_FILE_NAME]);
    int ret = strcpy_s(fileOpt->fileName, strlen(opt[SERVICE_FILE_NAME]) + 1, opt[SERVICE_FILE_NAME]);
    INIT_INFO_CHECK(ret == 0, free(fileOpt);
        return SERVICE_FAILURE, "Failed to copy file name %s", opt[SERVICE_FILE_NAME]);
    if (strcmp(opt[SERVICE_FILE_FLAGS], "rd") == 0) {
        fileOpt->flags = O_RDONLY;
    } else if (strcmp(opt[SERVICE_FILE_FLAGS], "wd") == 0) {
        fileOpt->flags = O_WRONLY;
    } else if (strcmp(opt[SERVICE_FILE_FLAGS], "rw") == 0) {
        fileOpt->flags = O_RDWR;
    } else {
        INIT_LOGE("Failed file flags %s", opt[SERVICE_FILE_FLAGS]);
        return SERVICE_FAILURE;
    }
    fileOpt->perm = strtoul(opt[SERVICE_FILE_PERM], 0, OCTAL_BASE);
    fileOpt->uid = DecodeUid(opt[SERVICE_FILE_UID]);
M
Mupceet 已提交
511
    fileOpt->gid = DecodeGid(opt[SERVICE_FILE_GID]);
X
xionglei6 已提交
512 513
    if (fileOpt->uid == (uid_t)-1 || fileOpt->gid == (gid_t)-1) {
        free(fileOpt);
X
xionglei6 已提交
514
        fileOpt = NULL;
X
xionglei6 已提交
515
        INIT_LOGE("Invalid uid or gid");
X
xionglei6 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
        return SERVICE_FAILURE;
    }
    fileOpt->fd = -1;
    fileOpt->next = NULL;
    if (service->fileCfg == NULL) {
        service->fileCfg = fileOpt;
    } else {
        fileOpt->next = service->fileCfg->next;
        service->fileCfg->next = fileOpt;
    }
    return SERVICE_SUCCESS;
}

static int ParseServiceFile(const cJSON *curArrItem, Service *curServ)
{
    int fileCnt = 0;
    cJSON *filedJ = GetArrayItem(curArrItem, &fileCnt, "file");
    INIT_CHECK(filedJ != NULL && fileCnt > 0, return SERVICE_FAILURE);
534
    FreeServiceFile(curServ->fileCfg);
X
xionglei6 已提交
535 536 537 538 539 540 541 542 543 544 545 546
    int ret = 0;
    curServ->fileCfg = NULL;
    for (int i = 0; i < fileCnt; ++i) {
        cJSON *fileJ = cJSON_GetArrayItem(filedJ, i);
        ret = AddServiceFile(fileJ, curServ);
        if (ret != 0) {
            break;
        }
    }
    return ret;
}

X
xionglei6 已提交
547 548 549 550 551 552 553 554 555
static int GetServiceOnDemand(const cJSON *curArrItem, Service *curServ)
{
    cJSON *item = cJSON_GetObjectItem(curArrItem, "ondemand");
    if (item == NULL) {
        return SERVICE_SUCCESS;
    }

    INIT_ERROR_CHECK(cJSON_IsBool(item), return SERVICE_FAILURE,
        "Service : %s ondemand value only support bool.", curServ->name);
556 557
    curServ->attribute &= ~SERVICE_ATTR_ONDEMAND;

X
xionglei6 已提交
558
    INIT_INFO_CHECK(cJSON_IsTrue(item), return SERVICE_SUCCESS,
X
xionglei6 已提交
559
        "Service : %s ondemand value is false, it should be pulled up by init", curServ->name);
X
xionglei6 已提交
560 561 562 563
    if (curServ->attribute & SERVICE_ATTR_CRITICAL) {
        INIT_LOGE("Service : %s is invalid which has both critical and ondemand attribute", curServ->name);
        return SERVICE_FAILURE;
    }
X
xionglei6 已提交
564 565 566 567 568

    curServ->attribute |= SERVICE_ATTR_ONDEMAND;
    return SERVICE_SUCCESS;
}

M
Mupceet 已提交
569 570 571 572 573 574 575 576 577 578 579 580 581
static int GetMapValue(const char *name, const InitArgInfo *infos, int argNum, int defValue)
{
    if ((argNum == 0) || (infos == NULL) || (name == NULL)) {
        return defValue;
    }
    for (int i = 0; i < argNum; i++) {
        if (strcmp(infos[i].name, name) == 0) {
            return infos[i].value;
        }
    }
    return defValue;
}

X
xionglei6 已提交
582 583 584 585 586
static int GetServiceMode(Service *service, const cJSON *json)
{
    const InitArgInfo startModeMap[] = {
        {"condition", START_MODE_CONDITION},
        {"boot", START_MODE_BOOT},
M
Mupceet 已提交
587
        {"normal", START_MODE_NORMAL}
X
xionglei6 已提交
588 589 590 591 592 593 594
    };
    const InitArgInfo endModeMap[] = {
        {"pre-fork", END_PRE_FORK},
        {"after-fork", END_AFTER_FORK},
        {"after-exec", END_AFTER_EXEC},
        {"ready", END_RECV_READY}
    };
M
Mupceet 已提交
595
    service->startMode = START_MODE_NORMAL;
X
xionglei6 已提交
596 597 598 599
    service->endMode = END_AFTER_EXEC;
    char *value = cJSON_GetStringValue(cJSON_GetObjectItem(json, "start-mode"));
    if (value != NULL) {
        service->startMode = GetMapValue(value,
M
Mupceet 已提交
600
            (InitArgInfo *)startModeMap, (int)ARRAY_LENGTH(startModeMap), START_MODE_NORMAL);
X
xionglei6 已提交
601 602 603 604
    }
    value = cJSON_GetStringValue(cJSON_GetObjectItem(json, "end-mode"));
    if (value != NULL) {
        service->endMode = GetMapValue(value,
X
xionglei6 已提交
605
            (InitArgInfo *)endModeMap, (int)ARRAY_LENGTH(endModeMap), END_AFTER_EXEC);
X
xionglei6 已提交
606 607 608 609 610 611 612 613 614 615 616 617
    }
    return 0;
}

static int GetServiceJobs(Service *service, cJSON *json)
{
    const char *jobTypes[] = {
        "on-boot", "on-start", "on-stop", "on-restart"
    };
    for (int i = 0; i < (int)ARRAY_LENGTH(jobTypes); i++) {
        char *jobName = cJSON_GetStringValue(cJSON_GetObjectItem(json, jobTypes[i]));
        if (jobName != NULL) {
618 619 620 621
            if (service->serviceJobs.jobsName[i] != NULL) {
                DelGroupNode(NODE_TYPE_JOBS, service->serviceJobs.jobsName[i]);
                free(service->serviceJobs.jobsName[i]);
            }
X
xionglei6 已提交
622
            service->serviceJobs.jobsName[i] = strdup(jobName);
X
xionglei6 已提交
623 624
            // save job name for group job check
            AddGroupNode(NODE_TYPE_JOBS, jobName);
X
xionglei6 已提交
625 626 627 628 629
        }
    }
    return SERVICE_SUCCESS;
}

X
xionglei6 已提交
630 631 632 633 634 635 636 637
int  GetCritical(const cJSON *curArrItem, Service *curServ, const char *attrName, int flag)
{
    int criticalSize = 0;
    curServ->crashCount = CRITICAL_DEFAULT_CRASH_COUNT;
    curServ->crashTime = CRITICAL_DEFAULT_CRASH_TIME;
    cJSON *arrItem = cJSON_GetObjectItem(curArrItem, attrName);
    if (arrItem == NULL) {
        return SERVICE_SUCCESS;
X
xionglei6 已提交
638
    }
X
xionglei6 已提交
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 671 672 673 674 675 676 677 678 679 680 681 682

    if (cJSON_IsNumber(arrItem)) {
        return GetServiceAttr(curArrItem, curServ, attrName, flag, NULL);
    } else if (cJSON_IsArray(arrItem)) {
        criticalSize = cJSON_GetArraySize(arrItem);
        cJSON *attrItem = cJSON_GetArrayItem(arrItem, 0); // 0 : critical attribute index
        if (attrItem == NULL || !cJSON_IsNumber(attrItem)) {
            INIT_LOGE("%s critical invalid", curServ->name);
            return SERVICE_FAILURE;
        }
        int attrValue = (int)cJSON_GetNumberValue(attrItem);
        curServ->attribute &= ~flag;
        if (criticalSize == 1) {
            if (attrValue == 1) {
                curServ->attribute |= flag;
            }
        } else if (criticalSize == CRITICAL_CONFIG_ARRAY_LEN) {
            cJSON *crashCountItem = cJSON_GetArrayItem(arrItem, 1); // 1 : critical crash count index
            INIT_ERROR_CHECK(crashCountItem != NULL, return SERVICE_FAILURE, "%s critical invalid", curServ->name);
            int value = (int)cJSON_GetNumberValue(crashCountItem);
            INIT_ERROR_CHECK(value > 0, return SERVICE_FAILURE, "%s critical crashc ount invalid", curServ->name);
            curServ->crashCount = value;

            cJSON *crashTimeItem = cJSON_GetArrayItem(arrItem, 2); // 2 : critical crash time index
            INIT_ERROR_CHECK(crashTimeItem != NULL, return SERVICE_FAILURE, "%s critical invalid", curServ->name);
            value = (int)cJSON_GetNumberValue(crashTimeItem);
            INIT_ERROR_CHECK(value > 0, return SERVICE_FAILURE, "%s critical crash time invalid", curServ->name);
            curServ->crashTime = value;

            if (attrValue == 1) {
                curServ->attribute |= flag;
            }
        } else {
            curServ->attribute &= ~flag;
            INIT_LOGE("%s critical param invalid", curServ->name);
            return SERVICE_FAILURE;
        }
    } else {
        INIT_LOGE("%s critical type error", curServ->name);
        return SERVICE_FAILURE;
    }
    return SERVICE_SUCCESS;
}

X
xlei1030 已提交
683
static int GetCpuArgs(const cJSON *argJson, const char *name, Service *service)
684 685 686 687 688 689 690 691
{
    INIT_ERROR_CHECK(argJson != NULL, return SERVICE_FAILURE, "Invalid argJson");
    cJSON *obj = cJSON_GetObjectItem(argJson, name);
    INIT_CHECK(obj != NULL, return SERVICE_FAILURE);

    int ret = cJSON_IsArray(obj);
    INIT_ERROR_CHECK(ret, return SERVICE_FAILURE, "Invalid type");
    int count = cJSON_GetArraySize(obj);
X
xlei1030 已提交
692 693
    int cpus = -1;
    int cpuNumMax = sysconf(_SC_NPROCESSORS_CONF);
C
cheng_jinsong 已提交
694 695 696 697 698
    if (count > 0 && service->cpuSet == NULL) {
        service->cpuSet = malloc(sizeof(cpu_set_t));
        INIT_ERROR_CHECK(service->cpuSet != NULL, return SERVICE_FAILURE, "Failed to malloc for cpuset");
    }
    CPU_ZERO(service->cpuSet);
699 700 701
    for (int i = 0; i < count; ++i) {
        cJSON *item = cJSON_GetArrayItem(obj, i);
        INIT_ERROR_CHECK(item != NULL, return SERVICE_FAILURE, "prase invalid");
X
xlei1030 已提交
702 703 704
        cpus = (int)cJSON_GetNumberValue(item);
        if (cpuNumMax <= cpus) {
            INIT_LOGW("%s core number %d of CPU cores does not exist", service->name, cpus);
705 706
            continue;
        }
C
cheng_jinsong 已提交
707
        if (CPU_ISSET(cpus, service->cpuSet)) {
X
xlei1030 已提交
708
            continue;
709
        }
C
cheng_jinsong 已提交
710
        CPU_SET(cpus, service->cpuSet);
711 712 713 714
    }
    return SERVICE_SUCCESS;
}

X
xionglei6 已提交
715 716 717 718 719 720 721 722 723 724
static int GetServiceSandbox(const cJSON *curItem, Service *service)
{
    cJSON *item = cJSON_GetObjectItem(curItem, "sandbox");
    if (item == NULL) {
        return SERVICE_SUCCESS;
    }

    INIT_ERROR_CHECK(cJSON_IsNumber(item), return SERVICE_FAILURE,
        "Service : %s sandbox value only support number.", service->name);
    int isSandbox = (int)cJSON_GetNumberValue(item);
725 726
    if (isSandbox == 0) {
        MarkServiceWithoutSandbox(service);
X
xionglei6 已提交
727
    } else {
728
        MarkServiceWithSandbox(service);
X
xionglei6 已提交
729 730 731 732 733
    }

    return SERVICE_SUCCESS;
}

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
#ifdef ASAN_DETECTOR
static int WrapPath(char *dest, size_t len, char *source, int i)
{
    char *q = source;
    char *p = dest;
    if (q == NULL) {
        return -1;
    }

    while (*p != '\0') {
        if (--i <= 0) {
            int ret = memmove_s(p + strlen(source), len, p, strlen(p) + 1);
            INIT_ERROR_CHECK(ret == 0, return -1, "Dest is %s, source is %s, ret is %d.", dest, source, ret);
            break;
        }
        p++;
    }
    while (*q != '\0') {
        *p = *q;
        p++;
        q++;
    }

    return 0;
}

static int GetWrapServiceNameValue(const char *serviceName)
{
    char wrapServiceNameKey[PARAM_VALUE_LEN_MAX] = {0};
    char wrapServiceNameValue[PARAM_VALUE_LEN_MAX] = {0};
    unsigned int valueLen = PARAM_VALUE_LEN_MAX;

    int len = sprintf_s(wrapServiceNameKey, PARAM_VALUE_LEN_MAX, "wrap.%s", serviceName);
    INIT_INFO_CHECK(len > 0 && (len < PARAM_VALUE_LEN_MAX), return -1, "Invalid to format wrapServiceNameKey");

    int ret = SystemReadParam(wrapServiceNameKey, wrapServiceNameValue, &valueLen);
    INIT_INFO_CHECK(ret == 0, return -1, "Not wrap %s.", serviceName);
    INIT_LOGI("Asan: GetParameter %s the value is %s.", serviceName, wrapServiceNameValue);
    return 0;
}

void SetServicePathWithAsan(Service *service)
{
    char tmpPathName[MAX_ONE_ARG_LEN] = {0};
    int anchorPos = -1;

    if (GetWrapServiceNameValue(service->name) != 0) {
        return;
    }

    int ret = strcpy_s(tmpPathName, MAX_ONE_ARG_LEN, service->pathArgs.argv[0]);
    INIT_ERROR_CHECK(ret == 0, return, "Asan: failed to copy service path %s", service->pathArgs.argv[0]);

    if (strstr(tmpPathName, "/system/bin") != NULL) {
        anchorPos = strlen("/system") + 1;
    } else if (strstr(tmpPathName, "/vendor/bin") != NULL) {
        anchorPos = strlen("/vendor") + 1;
    } else {
        INIT_LOGE("Asan: %s is not a system or vendor binary", tmpPathName);
        return;
    }

    ret = WrapPath(tmpPathName, MAX_ONE_ARG_LEN, "/asan", anchorPos);
    INIT_ERROR_CHECK(ret == 0, return, "Asan: failed to add asan path.");
    free(service->pathArgs.argv[0]);
    service->pathArgs.argv[0] = strdup(tmpPathName);
    INIT_LOGI("Asan: replace module %s with %s successfully.", service->name, service->pathArgs.argv[0]);

    return;
}
#endif

M
codex  
Mupceet 已提交
806 807 808 809 810 811
static void ParseOneServiceArgs(const cJSON *curItem, Service *service)
{
    (void)GetServiceArgs(curItem, "writepid", MAX_WRITEPID_FILES, &service->writePidArgs);
    (void)GetServiceArgs(curItem, D_CAPS_STR_IN_CFG, MAX_WRITEPID_FILES, &service->capsArgs);
    (void)GetServiceArgs(curItem, "permission", MAX_WRITEPID_FILES, &service->permArgs);
    (void)GetServiceArgs(curItem, "permission_acls", MAX_WRITEPID_FILES, &service->permAclsArgs);
812 813 814 815 816 817 818 819 820
    size_t strLen = 0;
    char *fieldStr = GetStringValue(curItem, APL_STR_IN_CFG, &strLen);
    if (fieldStr != NULL) {
        if (service->apl != NULL) {
            free(service->apl);
        }
        service->apl = strdup(fieldStr);
        INIT_CHECK(service->apl != NULL, return);
    }
M
codex  
Mupceet 已提交
821 822 823
    (void)GetCpuArgs(curItem, CPU_CORE_STR_IN_CFG, service);
}

X
add ut  
xionglei6 已提交
824
int ParseOneService(const cJSON *curItem, Service *service)
825
{
X
add ut  
xionglei6 已提交
826
    INIT_CHECK_RETURN_VALUE(curItem != NULL && service != NULL, SERVICE_FAILURE);
C
cheng_jinsong 已提交
827
    int ret = GetServiceArgs(curItem, "path", MAX_PATH_ARGS_CNT, &service->pathArgs);
828 829 830 831 832
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get path for service %s", service->name);
    if ((service->pathArgs.count > 0) && IsForbidden(service->pathArgs.argv[0])) {
        INIT_LOGE("Service %s is forbidden.", service->name);
        return SERVICE_FAILURE;
    }
833 834 835
#ifdef ASAN_DETECTOR
    SetServicePathWithAsan(service);
#endif
836 837 838 839 840 841 842 843 844
    ret = GetUid(cJSON_GetObjectItem(curItem, UID_STR_IN_CFG), &service->servPerm.uID);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get uid for service %s", service->name);
    ret = GetServiceGids(curItem, service);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get gid for service %s", service->name);

    ret = GetServiceAttr(curItem, service, ONCE_STR_IN_CFG, SERVICE_ATTR_ONCE, NULL);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get once flag for service %s", service->name);
    ret = GetServiceAttr(curItem, service, IMPORTANT_STR_IN_CFG, SERVICE_ATTR_IMPORTANT, SetImportantValue);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get import flag for service %s", service->name);
X
xionglei6 已提交
845
    ret = GetCritical(curItem, service, CRITICAL_STR_IN_CFG, SERVICE_ATTR_CRITICAL);
846 847 848 849 850
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get critical flag for service %s", service->name);
    ret = GetServiceAttr(curItem, service, DISABLED_STR_IN_CFG, SERVICE_ATTR_DISABLED, NULL);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get disabled flag for service %s", service->name);
    ret = GetServiceAttr(curItem, service, CONSOLE_STR_IN_CFG, SERVICE_ATTR_CONSOLE, NULL);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get console for service %s", service->name);
C
cheng_jinsong 已提交
851 852
    ret = GetServiceAttr(curItem, service, "notify-state", SERVICE_ATTR_NOTIFY_STATE, NULL);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get notify-state for service %s", service->name);
853 854
    ret = GetServiceAttr(curItem, service, MODULE_UPDATE_STR_IN_CFG, SERVICE_ATTR_MODULE_UPDATE, NULL);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get module-update for service %s", service->name);
855

M
codex  
Mupceet 已提交
856
    ParseOneServiceArgs(curItem, service);
X
xionglei6 已提交
857 858
    ret = GetServiceSandbox(curItem, service);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get sandbox for service %s", service->name);
C
cheng_jinsong 已提交
859
    ret = InitServiceCaps(curItem, service);
860
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get caps for service %s", service->name);
X
xionglei6 已提交
861 862
    ret = GetServiceOnDemand(curItem, service);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get ondemand flag for service %s", service->name);
X
xionglei6 已提交
863 864 865 866
    ret = GetServiceMode(service, curItem);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get start/end mode for service %s", service->name);
    ret = GetServiceJobs(service, cJSON_GetObjectItem(curItem, "jobs"));
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get jobs for service %s", service->name);
867 868 869
    return ret;
}

870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
#ifndef OHOS_LITE
/**
 * Service Config File Parse Hooking
 */
static int ServiceParseHookWrapper(const HOOK_INFO *hookInfo, void *executionContext)
{
    SERVICE_PARSE_CTX *serviceParseContext = (SERVICE_PARSE_CTX *)executionContext;
    ServiceParseHook realHook = (ServiceParseHook)hookInfo->hookCookie;

    realHook(serviceParseContext);
    return 0;
};

int InitAddServiceParseHook(ServiceParseHook hook)
{
    HOOK_INFO info;

    info.stage = INIT_SERVICE_PARSE;
    info.prio = 0;
    info.hook = ServiceParseHookWrapper;
    info.hookCookie = (void *)hook;

    return HookMgrAddEx(GetBootStageHookMgr(), &info);
}

static void ParseServiceHookExecute(const char *name, const cJSON *serviceNode)
{
    SERVICE_PARSE_CTX context;

    context.serviceName = name;
    context.serviceNode = serviceNode;

    (void)HookMgrExecute(GetBootStageHookMgr(), INIT_SERVICE_PARSE, (void *)(&context), NULL);
}
#endif

C
cheng_jinsong 已提交
906 907 908 909 910 911 912 913
static void ProcessConsoleEvent(const WatcherHandle handler, int fd, uint32_t *events, const void *context)
{
    Service *service = (Service *)context;
    LE_RemoveWatcher(LE_GetDefaultLoop(), (WatcherHandle)handler);
    if (fd < 0 || service == NULL) {
        INIT_LOGE("Process console event with invalid arguments");
        return;
    }
C
cheng_jinsong 已提交
914 915 916
    // Since we've got event from console device
    // the fd related to '/dev/console' does not need anymore, close it.
    close(fd);
C
cheng_jinsong 已提交
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
    if (strcmp(service->name, "console") != 0) {
        INIT_LOGE("Process console event with invalid service %s, only console service should do this", service->name);
        return;
    }

    // Check if debuggable
    char value[MAX_BUFFER_LEN] = {0};
    unsigned int len = MAX_BUFFER_LEN;
    if (SystemReadParam("const.debuggable", value, &len) != 0) {
        INIT_LOGE("Failed to read parameter \'const.debuggable\', prevent console service starting");
        return;
    }

    int isDebug = StringToInt(value, 0);
    if (isDebug != 1) {
        INIT_LOGI("Non-debuggable system, prevent console service starting");
        return;
    }
    if (ServiceStart(service) != SERVICE_SUCCESS) {
        INIT_LOGE("Start console service failed");
    }
    return;
}

static int AddFileDescriptorToWatcher(int fd, Service *service)
{
    if (fd < 0 || service == NULL) {
        return -1;
    }

    WatcherHandle watcher = NULL;
    LE_WatchInfo info = {};
    info.fd = fd;
    info.flags = 0; // WATCHER_ONCE;
    info.events = Event_Read;
    info.processEvent = ProcessConsoleEvent;
    int ret = LE_StartWatcher(LE_GetDefaultLoop(), &watcher, &info, service);
    if (ret != LE_SUCCESS) {
        INIT_LOGE("Failed to watch console device for service \' %s \'", service->name);
        return -1;
    }
    return 0;
}

int WatchConsoleDevice(Service *service)
{
    if (service == NULL) {
        return -1;
    }

    int fd = open("/dev/console", O_RDWR);
    if (fd < 0) {
        if (errno == ENOENT) {
            INIT_LOGW("/dev/console is not exist, wait for it...");
            WaitForFile("/dev/console", WAIT_MAX_SECOND);
C
cheng_jinsong 已提交
972 973 974 975 976 977 978 979
        } else {
            INIT_LOGE("Failed to open /dev/console, err = %d", errno);
            return -1;
        }
        fd = open("/dev/console", O_RDWR);
        if (fd < 0) {
            INIT_LOGW("Failed to open /dev/console after try 1 time, err = %d", errno);
            return -1;
C
cheng_jinsong 已提交
980 981 982 983 984 985 986 987 988 989
        }
    }

    if (AddFileDescriptorToWatcher(fd, service) < 0) {
        close(fd);
        return -1;
    }
    return 0;
}

990 991 992 993
void ParseAllServices(const cJSON *fileRoot)
{
    int servArrSize = 0;
    cJSON *serviceArr = GetArrayItem(fileRoot, &servArrSize, SERVICES_ARR_NAME_IN_JSON);
X
xionglei6 已提交
994
    INIT_CHECK(serviceArr != NULL, return);
995 996 997 998 999

    INIT_ERROR_CHECK(servArrSize <= MAX_SERVICES_CNT_IN_FILE, return,
        "Too many services[cnt %d] detected, should not exceed %d.",
        servArrSize, MAX_SERVICES_CNT_IN_FILE);

1000
    size_t strLen = 0;
1001 1002
    for (int i = 0; i < servArrSize; ++i) {
        cJSON *curItem = cJSON_GetArrayItem(serviceArr, i);
1003 1004
        char *fieldStr = GetStringValue(curItem, "name", &strLen);
        if (fieldStr == NULL) {
M
codex  
Mupceet 已提交
1005
            INIT_LOGE("Failed to get service name");
1006 1007
            continue;
        }
1008
        Service *service = GetServiceByName(fieldStr);
1009
        if (service == NULL) {
C
cheng_jinsong 已提交
1010
            service = AddService(fieldStr);
C
fix ut  
cheng_jinsong 已提交
1011 1012 1013
            if (service == NULL) {
                INIT_LOGE("Failed to add service name %s", fieldStr);
                continue;
C
codex  
chengjinsong 已提交
1014
            }
C
cheng_jinsong 已提交
1015 1016
        } else {
            INIT_LOGI("Service %s already exists, updating.", fieldStr);
C
cheng_jinsong 已提交
1017 1018 1019
#ifndef __MUSL__
            continue;
#endif
1020
        }
C
cheng_jinsong 已提交
1021

1022 1023
        service->pid = -1;
        int ret = ParseOneService(curItem, service);
1024 1025
        if (ret != SERVICE_SUCCESS) {
            ReleaseService(service);
X
add ut  
xionglei6 已提交
1026
            service = NULL;
1027 1028
            continue;
        }
C
cheng_jinsong 已提交
1029 1030 1031 1032
        ret = ParseServiceSocket(curItem, service);
        INIT_CHECK(ret == 0, FreeServiceSocket(service->socketCfg); service->socketCfg = NULL);
        ret = ParseServiceFile(curItem, service);
        INIT_CHECK(ret == 0, FreeServiceFile(service->fileCfg); service->fileCfg = NULL);
C
cheng_jinsong 已提交
1033 1034 1035 1036 1037 1038
        // Watch "/dev/console" node for starting console service ondemand.
        if ((strcmp(service->name, "console") == 0) && IsOnDemandService(service)) {
            if (WatchConsoleDevice(service) < 0) {
                INIT_LOGW("Failed to watch \'/dev/console\' device");
            }
        }
1039 1040 1041 1042
#ifndef OHOS_LITE
        /*
         * Execute service parsing hooks
         */
1043
        ParseServiceHookExecute(fieldStr, curItem);
1044 1045
#endif

1046
        ret = GetCmdLinesFromJson(cJSON_GetObjectItem(curItem, "onrestart"), &service->restartArg);
X
add ut  
xionglei6 已提交
1047
        INIT_CHECK(ret == SERVICE_SUCCESS, service->restartArg = NULL);
1048 1049 1050
    }
}

X
xionglei6 已提交
1051 1052 1053
static Service *GetServiceByExtServName(const char *fullServName)
{
    INIT_ERROR_CHECK(fullServName != NULL, return NULL, "Failed get parameters");
C
cheng_jinsong 已提交
1054 1055 1056 1057
    Service *service = GetServiceByName(fullServName);
    if (service != NULL) { // none parameter in fullServName
        return service;
    }
X
xionglei6 已提交
1058 1059 1060 1061 1062 1063 1064
    char *tmpServName = strdup(fullServName);
    char *dstPtr[MAX_PATH_ARGS_CNT] = {NULL};
    int returnCount = SplitString(tmpServName, "|", dstPtr, MAX_PATH_ARGS_CNT);
    if (returnCount == 0) {
        free(tmpServName);
        return NULL;
    }
C
cheng_jinsong 已提交
1065
    service = GetServiceByName(dstPtr[0]);
X
xionglei6 已提交
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    if (service == NULL) {
        free(tmpServName);
        return NULL;
    }
    service->extraArgs.count = service->pathArgs.count + returnCount - 1;
    service->extraArgs.argv = (char **)calloc(service->extraArgs.count + 1, sizeof(char *));
    INIT_ERROR_CHECK(service->extraArgs.argv != NULL, free(tmpServName);
        return NULL, "Failed calloc err=%d", errno);
    int argc;
    for (argc = 0; argc < (service->pathArgs.count - 1); argc++) {
        service->extraArgs.argv[argc] = strdup(service->pathArgs.argv[argc]);
    }
    int extArgc;
    for (extArgc = 0; extArgc < (returnCount - 1); extArgc++) {
        service->extraArgs.argv[extArgc + argc] = strdup(dstPtr[extArgc + 1]);
    }
    service->extraArgs.argv[service->extraArgs.count] = NULL;
    free(tmpServName);
    return service;
}

X
xionglei6 已提交
1087
void StartServiceByName(const char *servName)
1088
{
C
fix log  
cheng_jinsong 已提交
1089
    INIT_LOGI("Start service %s", servName);
1090
    Service *service = GetServiceByName(servName);
X
xionglei6 已提交
1091 1092 1093
    if (service == NULL) {
        service = GetServiceByExtServName(servName);
    }
1094 1095 1096 1097 1098
    INIT_ERROR_CHECK(service != NULL, return, "Cannot find service %s.", servName);

    if (ServiceStart(service) != SERVICE_SUCCESS) {
        INIT_LOGE("Service %s start failed!", servName);
    }
X
xionglei6 已提交
1099
    // After starting, clear the extra parameters.
X
xionglei6 已提交
1100 1101 1102
    FreeStringVector(service->extraArgs.argv, service->extraArgs.count);
    service->extraArgs.argv = NULL;
    service->extraArgs.count = 0;
1103 1104 1105 1106 1107 1108 1109 1110 1111
    return;
}

void StopServiceByName(const char *servName)
{
    Service *service = GetServiceByName(servName);
    INIT_ERROR_CHECK(service != NULL, return, "Cannot find service %s.", servName);

    if (ServiceStop(service) != SERVICE_SUCCESS) {
C
fix log  
cheng_jinsong 已提交
1112
        INIT_LOGE("Service %s stop failed!", servName);
1113 1114 1115 1116
    }
    return;
}

X
xionglei6 已提交
1117 1118
void StopAllServices(int flags, const char **exclude, int size,
    int (*filter)(const Service *service, const char **exclude, int size))
1119
{
1120
    Service *service = GetServiceByName("appspawn");
C
cheng_jinsong 已提交
1121
    if (service != NULL && service->pid > 0) { // notify appspawn stop
L
laiguizhong 已提交
1122
#ifndef STARTUP_INIT_TEST
X
xlei1030 已提交
1123
        kill(service->pid, SIGTERM);
1124
        waitpid(service->pid, 0, 0);
X
xlei1030 已提交
1125
        service->pid = -1;
L
laiguizhong 已提交
1126
#endif
1127 1128
    }

X
xionglei6 已提交
1129 1130 1131
    InitGroupNode *node = GetNextGroupNode(NODE_TYPE_SERVICES, NULL);
    while (node != NULL) {
        Service *service = node->data.service;
X
xionglei6 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140
        if (service == NULL) {
            node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
            continue;
        }
        INIT_LOGI("StopAllServices stop service %s ", service->name);
        if (filter != NULL && filter(service, exclude, size) != 0) {
            node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
            continue;
        }
X
xionglei6 已提交
1141
        service->attribute |= (flags & SERVICE_ATTR_INVALID);
X
xionglei6 已提交
1142 1143 1144
        int ret = ServiceStop(service);
        if (ret != SERVICE_SUCCESS) {
            INIT_LOGE("Service %s stop failed!", service->name);
1145
        }
X
xionglei6 已提交
1146
        node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
1147 1148 1149 1150 1151
    }
}

Service *GetServiceByPid(pid_t pid)
{
X
xionglei6 已提交
1152 1153 1154 1155
    InitGroupNode *node = GetNextGroupNode(NODE_TYPE_SERVICES, NULL);
    while (node != NULL) {
        Service *service = node->data.service;
        if (service != NULL && service->pid == pid) {
1156 1157
            return service;
        }
X
xionglei6 已提交
1158
        node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
1159 1160 1161 1162
    }
    return NULL;
}

X
xionglei6 已提交
1163
Service *GetServiceByName(const char *servName)
X
xionglei6 已提交
1164
{
X
xionglei6 已提交
1165 1166 1167 1168
    INIT_ERROR_CHECK(servName != NULL, return NULL, "Failed get servName");
    InitGroupNode *groupNode = GetGroupNode(NODE_TYPE_SERVICES, servName);
    if (groupNode != NULL) {
        return groupNode->data.service;
X
xionglei6 已提交
1169
    }
X
xionglei6 已提交
1170
    return NULL;
X
xionglei6 已提交
1171 1172
}

1173 1174 1175 1176
void LoadAccessTokenId(void)
{
    GetAccessToken();
}
C
cheng_jinsong 已提交
1177 1178 1179 1180 1181 1182 1183

int GetKillServiceSig(const char *name)
{
    if (strcmp(name, "appspawn") == 0 || strcmp(name, "nwebspawn") == 0) {
        return SIGTERM;
    }
    return SIGKILL;
C
cheng_jinsong 已提交
1184
}