init_service_manager.c 33.1 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 21 22 23 24
 * 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>
#include <unistd.h>

#include "cJSON.h"
#include "init.h"
X
xionglei6 已提交
25
#include "init_group_manager.h"
Z
zhong_ning 已提交
26
#include "init_jobs_internal.h"
27
#include "init_log.h"
X
xionglei6 已提交
28
#include "init_service_file.h"
29 30 31
#include "init_service_socket.h"
#include "init_utils.h"
#include "securec.h"
Q
Qin Fandong 已提交
32 33 34
#ifdef WITH_SELINUX
#   include "init_selinux_param.h"
#endif // WITH_SELINUX
35 36

// All serivce processes that init will fork+exec.
X
xionglei6 已提交
37
static ServiceSpace g_serviceSpace = { 0 };
X
xionglei6 已提交
38 39 40 41
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;
42 43 44 45

#ifdef OHOS_SERVICE_DUMP
static void DumpServiceArgs(const char *info, const ServiceArgs *args)
{
X
xionglei6 已提交
46
    INIT_LOGI("\t\t%s count %d", info, args->count);
47 48
    for (int j = 0; j < args->count; j++) {
        if (args->argv[j] != NULL) {
X
xionglei6 已提交
49
            INIT_LOGI("\t\tinfo [%d] %s", j, args->argv[j]);
50 51 52 53 54 55
        }
    }
}

void DumpAllServices()
{
X
xionglei6 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    INIT_LOGI("Ready to dump all services:");
    INIT_LOGI("total service number: %d", g_serviceSpace.serviceCount);
    InitGroupNode *node = GetNextGroupNode(NODE_TYPE_SERVICES, NULL);
    while (node != NULL) {
        if (node->data.service == NULL) {
            node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
            continue;
        }
        Service *service = node->data.service;
        INIT_LOGI("\tservice name: [%s]", service->name);
        INIT_LOGI("\tservice pid: [%d]", service->pid);
        INIT_LOGI("\tservice crashCnt: [%d]", service->crashCnt);
        INIT_LOGI("\tservice attribute: [%d]", service->attribute);
        INIT_LOGI("\tservice importance: [%d]", service->importance);
        INIT_LOGI("\tservice perms uID [%d]", service->servPerm.uID);
71 72 73
        DumpServiceArgs("path arg", &service->pathArgs);
        DumpServiceArgs("writepid file", &service->writePidArgs);

X
xionglei6 已提交
74
        INIT_LOGI("\tservice perms groupId %d", service->servPerm.gIDCnt);
75
        for (int i = 0; i < service->servPerm.gIDCnt; i++) {
X
xionglei6 已提交
76
            INIT_LOGI("\t\tservice perms groupId %d", service->servPerm.gIDArray[i]);
77 78
        }

X
xionglei6 已提交
79 80 81
        INIT_LOGI("\tservice perms capability %d", service->servPerm.capsCnt);
        for (int i = 0; i < (int)service->servPerm.capsCnt; i++) {
            INIT_LOGI("\t\tservice perms capability %d", service->servPerm.caps[i]);
82 83 84 85
        }
        if (service->restartArg != NULL) {
            for (int j = 0; j < service->restartArg->cmdNum; j++) {
                CmdLine *cmd = &service->restartArg->cmds[j];
X
xionglei6 已提交
86
                INIT_LOGI("\t\tcmd arg: %s %s", GetCmdKey(cmd->cmdIndex), cmd->cmdContent);
87 88 89
            }
        }
        if (service->socketCfg != NULL) {
X
xionglei6 已提交
90 91 92 93
            INIT_LOGI("\tservice socket name: %s", service->socketCfg->name);
            INIT_LOGI("\tservice socket type: %d", service->socketCfg->type);
            INIT_LOGI("\tservice socket uid: %d", service->socketCfg->uid);
            INIT_LOGI("\tservice socket gid: %d", service->socketCfg->gid);
94
        }
X
xionglei6 已提交
95
        node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
96
    }
X
xionglei6 已提交
97
    INIT_LOGI("Dump all services finished");
98 99 100 101 102
}
#endif

static void FreeServiceArg(ServiceArgs *arg)
{
X
add ut  
xionglei6 已提交
103
    if (arg == NULL) {
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
        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 已提交
131
static Service *AddService(const char *name)
132
{
X
xionglei6 已提交
133 134 135 136 137 138 139 140
    // check service in group
    if (CheckNodeValid(NODE_TYPE_SERVICES, name) != 0) {
        return NULL;
    }
    InitGroupNode *node = AddGroupNode(NODE_TYPE_SERVICES, name);
    if (node == NULL) {
        return NULL;
    }
141 142
    Service *service = (Service *)calloc(1, sizeof(Service));
    INIT_ERROR_CHECK(service != NULL, return NULL, "Failed to malloc for service");
X
xionglei6 已提交
143 144
    node->data.service = service;
    service->name = node->name;
145
    g_serviceSpace.serviceCount++;
X
xionglei6 已提交
146
    INIT_LOGV("AddService %s", node->name);
147 148 149
    return service;
}

X
xionglei6 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163
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 已提交
164
void ReleaseService(Service *service)
165 166 167 168 169 170
{
    if (service == NULL) {
        return;
    }
    FreeServiceArg(&service->pathArgs);
    FreeServiceArg(&service->writePidArgs);
171
    FreeServiceArg(&service->capsArgs);
172 173 174 175 176 177 178 179 180 181 182 183

    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 已提交
184
    FreeServiceFile(service->fileCfg);
185

X
xionglei6 已提交
186 187 188 189
    g_serviceSpace.serviceCount--;
    InitGroupNode *groupNode = GetGroupNode(NODE_TYPE_SERVICES, service->name);
    if (groupNode != NULL) {
        groupNode->data.service = NULL;
190 191 192 193 194 195 196 197
    }
    free(service);
}

static int GetStringItem(const cJSON *json, const char *name, char *buffer, int buffLen)
{
    INIT_ERROR_CHECK(json != NULL, return SERVICE_FAILURE, "Invalid json for %s", name);
    char *fieldStr = cJSON_GetStringValue(cJSON_GetObjectItem(json, name));
X
xionglei6 已提交
198 199 200
    if (fieldStr == NULL) {
        return SERVICE_FAILURE;
    }
201
    size_t strLen = strlen(fieldStr);
X
add ut  
xionglei6 已提交
202 203
    INIT_ERROR_CHECK((strLen != 0) && (strLen <= (size_t)buffLen), return SERVICE_FAILURE,
        "Invalid str filed %s for %s", fieldStr, name);
204 205 206 207 208 209 210 211 212 213
    return strcpy_s(buffer, buffLen, fieldStr);
}

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 已提交
214
    INIT_CHECK_RETURN_VALUE(*arrSize > 0, NULL);
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    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);

    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;
    }
234 235 236 237 238 239
     // ServiceArgs have a variety of uses, some requiring a NULL ending, some not
    if (strcmp(name, D_CAPS_STR_IN_CFG) != 0) {
        args->count = count + 1;
    } else {
        args->count = count;
    }
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    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);
        INIT_ERROR_CHECK(args->argv[i] != NULL, return SERVICE_FAILURE, "Failed to dupstring %s", curParam);
    }
    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);
    }
X
add ut  
xionglei6 已提交
260
    INIT_CHECK_RETURN_VALUE(*uid != (uid_t)(-1), SERVICE_FAILURE);
261 262 263 264 265
    return SERVICE_SUCCESS;
}

static int GetServiceGids(const cJSON *curArrItem, Service *curServ)
{
X
xionglei6 已提交
266
    int gidCount;
267 268 269 270 271 272
    cJSON *arrItem = cJSON_GetObjectItemCaseSensitive(curArrItem, GID_STR_IN_CFG);
    if (!cJSON_IsArray(arrItem)) {
        gidCount = 1;
    } else {
        gidCount = cJSON_GetArraySize(arrItem);
    }
X
add ut  
xionglei6 已提交
273 274
    INIT_ERROR_CHECK((gidCount != 0) && (gidCount <= NGROUPS_MAX + 1), return SERVICE_FAILURE,
        "Invalid gid count %d", gidCount);
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    curServ->servPerm.gIDArray = (gid_t *)malloc(sizeof(gid_t) * gidCount);
    INIT_ERROR_CHECK(curServ->servPerm.gIDArray != NULL, return SERVICE_FAILURE, "Failed to malloc");
    curServ->servPerm.gIDCnt = gidCount;

    gid_t gid;
    if (!cJSON_IsArray(arrItem)) {
        int ret = GetUid(arrItem, &gid);
        INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to uid");
        curServ->servPerm.gIDArray[0] = gid;
        return SERVICE_SUCCESS;
    }

    for (int i = 0; i < gidCount; ++i) {
        cJSON *item = cJSON_GetArrayItem(arrItem, i);
        int ret = GetUid(item, &gid);
        if (ret != 0) {
            curServ->servPerm.gIDArray[i] = 0;
            continue;
        }
        curServ->servPerm.gIDArray[i] = gid;
    }
    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 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324

    int value = (int)cJSON_GetNumberValue(filedJ);
    if (processAttr == NULL) {
        curServ->attribute &= ~flag;
        if (value == 1) {
            curServ->attribute |= flag;
        }
        return 0;
    }
    return processAttr(curServ, attrName, value, flag);
}

static int AddServiceSocket(cJSON *json, Service *service)
{
    char *opt[SOCK_OPT_NUMS] = {
        NULL,
    };
X
add ut  
xionglei6 已提交
325
    INIT_CHECK_RETURN_VALUE(cJSON_IsString(json) && cJSON_GetStringValue(json), SERVICE_FAILURE);
326 327
    char *sockStr = cJSON_GetStringValue(json);
    int num = SplitString(sockStr, " ", opt, SOCK_OPT_NUMS);
X
add ut  
xionglei6 已提交
328 329
    INIT_CHECK_RETURN_VALUE(num == SOCK_OPT_NUMS, SERVICE_FAILURE);

330 331 332 333 334 335 336 337
    if (opt[SERVICE_SOCK_NAME] == NULL || opt[SERVICE_SOCK_TYPE] == NULL || opt[SERVICE_SOCK_PERM] == NULL ||
        opt[SERVICE_SOCK_UID] == NULL || opt[SERVICE_SOCK_GID] == NULL || opt[SERVICE_SOCK_SETOPT] == NULL) {
        INIT_LOGE("Invalid socket opt");
        return SERVICE_FAILURE;
    }

    ServiceSocket *sockopt = (ServiceSocket *)calloc(1, sizeof(ServiceSocket) + strlen(opt[SERVICE_SOCK_NAME]) + 1);
    INIT_INFO_CHECK(sockopt != NULL, return SERVICE_FAILURE, "Failed to malloc for socket %s", opt[SERVICE_SOCK_NAME]);
Z
zhong_ning 已提交
338
    sockopt->sockFd = -1;
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    int ret = strcpy_s(sockopt->name, strlen(opt[SERVICE_SOCK_NAME]) + 1, opt[SERVICE_SOCK_NAME]);
    INIT_INFO_CHECK(ret == 0, free(sockopt);
        return SERVICE_FAILURE, "Failed to copy socket name %s", opt[SERVICE_SOCK_NAME]);

    sockopt->type = SOCK_SEQPACKET;
    if (strncmp(opt[SERVICE_SOCK_TYPE], "stream", strlen(opt[SERVICE_SOCK_TYPE])) == 0) {
        sockopt->type = SOCK_STREAM;
    } else if (strncmp(opt[SERVICE_SOCK_TYPE], "dgram", strlen(opt[SERVICE_SOCK_TYPE])) == 0) {
        sockopt->type = SOCK_DGRAM;
    }
    sockopt->perm = strtoul(opt[SERVICE_SOCK_PERM], 0, OCTAL_BASE);
    sockopt->uid = DecodeUid(opt[SERVICE_SOCK_UID]);
    sockopt->gid = DecodeUid(opt[SERVICE_SOCK_GID]);
    if (sockopt->uid == (uid_t)-1 || sockopt->gid == (uid_t)-1) {
        free(sockopt);
X
xionglei6 已提交
354
        sockopt = NULL;
X
xionglei6 已提交
355
        INIT_LOGE("Invalid uid or gid");
356 357 358 359 360 361
        return SERVICE_FAILURE;
    }
    sockopt->passcred = false;
    if (strncmp(opt[SERVICE_SOCK_SETOPT], "passcred", strlen(opt[SERVICE_SOCK_SETOPT])) == 0) {
        sockopt->passcred = true;
    }
X
xionglei6 已提交
362
    sockopt->watcher = NULL;
X
xionglei6 已提交
363
    sockopt->sockFd = -1;
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    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);
    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) {
385
            return ret;
386 387
        }
    }
388 389 390
    if (IsOnDemandService(curServ)) {
        ret = CreateServiceSocket(curServ);
    }
391 392 393
    return ret;
}

X
xionglei6 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407
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 已提交
408
        opt[SERVICE_FILE_UID] == NULL || opt[SERVICE_FILE_GID] == NULL) {
X
xionglei6 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
        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]);
    fileOpt->gid = DecodeUid(opt[SERVICE_FILE_GID]);
    if (fileOpt->uid == (uid_t)-1 || fileOpt->gid == (gid_t)-1) {
        free(fileOpt);
X
xionglei6 已提交
432
        fileOpt = NULL;
X
xionglei6 已提交
433
        INIT_LOGE("Invalid uid or gid");
X
xionglei6 已提交
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
        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);
    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;
}

464 465 466 467 468 469 470 471
static bool IsServiceInMainStrap(Service *curServ)
{
    char *mainServiceList[] = {
        "appspawn", "udevd",  "samgr",      "multimodalinput", "weston",         "installs",
        "hiview",   "hilogd", "hdf_devmgr", "distributedsche", "softbus_server", "foundation"
    };
    unsigned int length = ARRAY_LENGTH(mainServiceList);
    for (unsigned int i = 0; i < length; ++i) {
X
add ut  
xionglei6 已提交
472 473
        INIT_INFO_CHECK(strncmp(curServ->name, mainServiceList[i], strlen(mainServiceList[i])) != 0, return true,
            "%s must be main service", curServ->name);
474 475 476 477 478 479 480 481 482 483 484 485 486 487
    }
    return false;
}

static int GetDynamicService(const cJSON *curArrItem, Service *curServ)
{
    cJSON *item = cJSON_GetObjectItem(curArrItem, "dynamic");
    if (item == NULL) {
        return SERVICE_SUCCESS;
    }

    INIT_ERROR_CHECK(cJSON_IsBool(item), return SERVICE_FAILURE,
        "Service : %s dynamic value only support bool.", curServ->name);
    bool isDynamic = (bool)cJSON_GetNumberValue(item);
X
add ut  
xionglei6 已提交
488 489 490
    INIT_INFO_CHECK(isDynamic, return SERVICE_SUCCESS,
        "Service : %s dynamic value is false, it will be started with init.", curServ->name);
    INIT_CHECK_RETURN_VALUE(!IsServiceInMainStrap(curServ), SERVICE_SUCCESS);
491
    INIT_LOGI("%s is dynamic service", curServ->name);
X
add ut  
xionglei6 已提交
492

493 494 495 496 497
    curServ->attribute |= SERVICE_ATTR_DYNAMIC;
    curServ->attribute |= SERVICE_ATTR_ONCE;
    return SERVICE_SUCCESS;
}

X
xionglei6 已提交
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
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);
    bool isOnDemand = (bool)cJSON_GetNumberValue(item);
    INIT_INFO_CHECK(isOnDemand, return SERVICE_SUCCESS,
        "Service : %s ondemand value is false, it will be manage socket by itself", curServ->name);

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

515 516 517 518
static int CheckServiceKeyName(const cJSON *curService)
{
    char *cfgServiceKeyList[] = {
        "name", "path", "uid", "gid", "once", "importance", "caps", "disabled",
X
xionglei6 已提交
519
        "writepid", "critical", "socket", "console", "dynamic", "file", "ondemand",
520
        "d-caps", "apl", "jobs", "start-mode", "end-mode",
Q
Qin Fandong 已提交
521 522 523
#ifdef WITH_SELINUX
        SECON_STR_IN_CFG,
#endif // WITH_SELINUX
524
    };
X
add ut  
xionglei6 已提交
525
    INIT_CHECK_RETURN_VALUE(curService != NULL, SERVICE_FAILURE);
526
    cJSON *child = curService->child;
X
add ut  
xionglei6 已提交
527
    INIT_CHECK_RETURN_VALUE(child != NULL, SERVICE_FAILURE);
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    while (child != NULL) {
        int i = 0;
        int keyListSize = ARRAY_LENGTH(cfgServiceKeyList);
        for (; i < keyListSize; i++) {
            if (strcmp(child->string, cfgServiceKeyList[i]) == 0) {
                break;
            }
        }
        if (i < keyListSize) {
            child = child->next;
        } else {
            INIT_LOGE("CheckServiceKeyName, key name %s is not found. error.", child->string);
            return SERVICE_FAILURE;
        }
    }
    return SERVICE_SUCCESS;
}

X
xionglei6 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
static int GetServiceMode(Service *service, const cJSON *json)
{
    const InitArgInfo startModeMap[] = {
        {"condition", START_MODE_CONDITION},
        {"boot", START_MODE_BOOT},
        {"normal", START_MODE_NARMAL}
    };
    const InitArgInfo endModeMap[] = {
        {"pre-fork", END_PRE_FORK},
        {"after-fork", END_AFTER_FORK},
        {"after-exec", END_AFTER_EXEC},
        {"ready", END_RECV_READY}
    };
    service->startMode = START_MODE_NARMAL;
    service->endMode = END_AFTER_EXEC;
    char *value = cJSON_GetStringValue(cJSON_GetObjectItem(json, "start-mode"));
    if (value != NULL) {
        service->startMode = GetMapValue(value,
            (InitArgInfo *)&startModeMap, (int)ARRAY_LENGTH(startModeMap), START_MODE_NARMAL);
    }
    value = cJSON_GetStringValue(cJSON_GetObjectItem(json, "end-mode"));
    if (value != NULL) {
        service->endMode = GetMapValue(value,
            (InitArgInfo *)&endModeMap, (int)ARRAY_LENGTH(endModeMap), END_AFTER_EXEC);
    }
    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) {
            service->serviceJobs.jobsName[i] = strdup(jobName);
        }
    }
    return SERVICE_SUCCESS;
}

X
xionglei6 已提交
588 589 590 591 592 593 594 595
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 已提交
596
    }
X
xionglei6 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640

    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
add ut  
xionglei6 已提交
641
int ParseOneService(const cJSON *curItem, Service *service)
642
{
X
add ut  
xionglei6 已提交
643
    INIT_CHECK_RETURN_VALUE(curItem != NULL && service != NULL, SERVICE_FAILURE);
X
xionglei6 已提交
644
    int ret = 0;
Q
Qin Fandong 已提交
645 646 647 648
#ifdef WITH_SELINUX
    ret = GetStringItem(curItem, SECON_STR_IN_CFG, service->secon, MAX_SECON_LEN);
    INIT_CHECK_ONLY_ELOG(ret == 0, "GetServiceSecon %s section not found, skip", SECON_STR_IN_CFG);
#endif // WITH_SELINUX
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
    ret = GetServiceArgs(curItem, "path", MAX_PATH_ARGS_CNT, &service->pathArgs);
    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;
    }
    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 已提交
664
    ret = GetCritical(curItem, service, CRITICAL_STR_IN_CFG, SERVICE_ATTR_CRITICAL);
665 666 667 668 669 670
    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);

671 672 673
    (void)GetServiceArgs(curItem, "writepid", MAX_WRITEPID_FILES, &service->writePidArgs);
    (void)GetServiceArgs(curItem, D_CAPS_STR_IN_CFG, MAX_WRITEPID_FILES, &service->capsArgs);
    (void)GetStringItem(curItem, APL_STR_IN_CFG, service->apl, MAX_APL_NAME);
674 675 676 677
    ret = GetServiceCaps(curItem, service);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get caps for service %s", service->name);
    ret = GetDynamicService(curItem, service);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get dynamic flag for service %s", service->name);
X
xionglei6 已提交
678 679
    ret = GetServiceOnDemand(curItem, service);
    INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get ondemand flag for service %s", service->name);
X
xionglei6 已提交
680 681 682 683
    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);
684 685 686 687 688 689 690
    return ret;
}

void ParseAllServices(const cJSON *fileRoot)
{
    int servArrSize = 0;
    cJSON *serviceArr = GetArrayItem(fileRoot, &servArrSize, SERVICES_ARR_NAME_IN_JSON);
X
xionglei6 已提交
691
    INIT_CHECK(serviceArr != NULL, return);
692 693 694 695 696

    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);

X
xionglei6 已提交
697
    char serviceName[MAX_SERVICE_NAME] = {};
698 699
    for (int i = 0; i < servArrSize; ++i) {
        cJSON *curItem = cJSON_GetArrayItem(serviceArr, i);
X
xionglei6 已提交
700
        int ret = GetStringItem(curItem, "name", serviceName, MAX_SERVICE_NAME);
701
        if (ret != 0) {
X
xionglei6 已提交
702
            INIT_LOGE("Failed to get service name %s", serviceName);
703 704 705
            continue;
        }
        if (CheckServiceKeyName(curItem) != SERVICE_SUCCESS) { // invalid service
X
xionglei6 已提交
706
            INIT_LOGE("Invalid service name %s", serviceName);
707 708
            continue;
        }
X
xionglei6 已提交
709
        Service *service = GetServiceByName(serviceName);
710
        if (service != NULL) {
X
xionglei6 已提交
711
            INIT_LOGE("Service name %s has been exist", serviceName);
712 713
            continue;
        }
X
xionglei6 已提交
714
        service = AddService(serviceName);
715
        if (service == NULL) {
X
xionglei6 已提交
716
            INIT_LOGE("Failed to create service name %s", serviceName);
717 718 719 720 721 722
            continue;
        }

        ret = ParseOneService(curItem, service);
        if (ret != SERVICE_SUCCESS) {
            ReleaseService(service);
X
add ut  
xionglei6 已提交
723
            service = NULL;
724 725
            continue;
        }
X
xionglei6 已提交
726
        if (ParseServiceSocket(curItem, service) != SERVICE_SUCCESS) {
727 728 729
            FreeServiceSocket(service->socketCfg);
            service->socketCfg = NULL;
        }
X
xionglei6 已提交
730 731 732 733
        if (ParseServiceFile(curItem, service) != SERVICE_SUCCESS) {
            FreeServiceFile(service->fileCfg);
            service->fileCfg = NULL;
        }
734
        ret = GetCmdLinesFromJson(cJSON_GetObjectItem(curItem, "onrestart"), &service->restartArg);
X
add ut  
xionglei6 已提交
735
        INIT_CHECK(ret == SERVICE_SUCCESS, service->restartArg = NULL);
736 737 738
    }
}

X
xionglei6 已提交
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
static Service *GetServiceByExtServName(const char *fullServName)
{
    INIT_ERROR_CHECK(fullServName != NULL, return NULL, "Failed get parameters");
    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;
    }
    Service *service = GetServiceByName(dstPtr[0]);
    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]);
    }
    for (int i = 0; i < service->extraArgs.count - 1; i++) {
        INIT_LOGI("service->extraArgs.argv[%d] is %s", i, service->extraArgs.argv[i]);
    }
    service->extraArgs.argv[service->extraArgs.count] = NULL;
    free(tmpServName);
    return service;
}

774 775
void StartServiceByName(const char *servName, bool checkDynamic)
{
X
xionglei6 已提交
776
    INIT_LOGE("StartServiceByName Service %s", servName);
777
    Service *service = GetServiceByName(servName);
X
xionglei6 已提交
778 779 780
    if (service == NULL) {
        service = GetServiceByExtServName(servName);
    }
781 782 783 784
    INIT_ERROR_CHECK(service != NULL, return, "Cannot find service %s.", servName);

    if (checkDynamic && (service->attribute & SERVICE_ATTR_DYNAMIC)) {
        INIT_LOGI("%s is dynamic service.", servName);
X
xionglei6 已提交
785
        NotifyServiceChange(servName, "stopped");
786 787 788 789 790
        return;
    }
    if (ServiceStart(service) != SERVICE_SUCCESS) {
        INIT_LOGE("Service %s start failed!", servName);
    }
X
xionglei6 已提交
791
    // After starting, clear the extra parameters.
X
xionglei6 已提交
792 793 794
    FreeStringVector(service->extraArgs.argv, service->extraArgs.count);
    service->extraArgs.argv = NULL;
    service->extraArgs.count = 0;
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
    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) {
        INIT_LOGE("Service %s start failed!", servName);
    }
    return;
}

void StopAllServices(int flags)
{
X
xionglei6 已提交
811 812 813 814 815 816 817 818 819
    InitGroupNode *node = GetNextGroupNode(NODE_TYPE_SERVICES, NULL);
    while (node != NULL) {
        Service *service = node->data.service;
        if (service != NULL) {
            service->attribute |= flags;
            int ret = ServiceStop(service);
            if (ret != SERVICE_SUCCESS) {
                INIT_LOGE("Service %s stop failed!", service->name);
            }
820
        }
X
xionglei6 已提交
821
        node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
822 823 824 825 826
    }
}

Service *GetServiceByPid(pid_t pid)
{
X
xionglei6 已提交
827 828 829 830
    InitGroupNode *node = GetNextGroupNode(NODE_TYPE_SERVICES, NULL);
    while (node != NULL) {
        Service *service = node->data.service;
        if (service != NULL && service->pid == pid) {
831 832
            return service;
        }
X
xionglei6 已提交
833
        node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
834 835 836 837
    }
    return NULL;
}

X
xionglei6 已提交
838
Service *GetServiceByName(const char *servName)
X
xionglei6 已提交
839
{
X
xionglei6 已提交
840 841 842 843
    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 已提交
844
    }
X
xionglei6 已提交
845
    return NULL;
X
xionglei6 已提交
846 847
}

X
xionglei6 已提交
848
void StartAllServices(int startMode)
849
{
X
xionglei6 已提交
850 851 852 853 854 855 856 857 858 859 860 861
    INIT_LOGI("StartAllServices %d", startMode);
#ifdef SUPPORT_GROUP_SERVICE_START
    InitGroupNode *node = GetNextGroupNode(NODE_TYPE_SERVICES, NULL);
    while (node != NULL) {
        Service *service = node->data.service;
        if (service == NULL || service->startMode != startMode) {
            node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
            continue;
        }
        if (IsOnDemandService(service)) {
            if (CreateServiceSocket(service) != 0) {
                INIT_LOGE("service %s exit! create socket failed!", service->name);
X
xionglei6 已提交
862
            }
X
xionglei6 已提交
863 864 865 866 867 868 869 870
            node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
            continue;
        }
        if (service->attribute & SERVICE_ATTR_DYNAMIC) {
            INIT_LOGI("%s is dynamic service.", service->name);
            NotifyServiceChange(service->name, "stopped");
            node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
            continue;
X
xionglei6 已提交
871
        }
X
xionglei6 已提交
872 873 874 875
        if (ServiceStart(service) != SERVICE_SUCCESS) {
            INIT_LOGE("Service %s start failed!", service->name);
        }
        node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
876
    }
X
xionglei6 已提交
877 878
#endif
    INIT_LOGI("StartAllServices %d finsh", startMode);
879 880 881 882 883 884
}

void LoadAccessTokenId(void)
{
    GetAccessToken();
}