param_service.c 30.3 KB
Newer Older
Z
zhong_ning 已提交
1
/*
S
sun_fan 已提交
2
 * Copyright (c) 2021 Huawei Device Co., Ltd.
Z
zhong_ning 已提交
3 4 5 6
 * 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
 *
S
sun_fan 已提交
7
 *     http://www.apache.org/licenses/LICENSE-2.0
Z
zhong_ning 已提交
8 9 10 11 12 13 14 15 16
 *
 * 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 "param_service.h"
4
411148299@qq.com 已提交
17

S
sun_fan 已提交
18 19
#include <errno.h>
#include <fcntl.h>
Z
zhong_ning 已提交
20 21
#include <stdio.h>
#include <string.h>
S
sun_fan 已提交
22 23 24
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/stat.h>
Z
zhong_ning 已提交
25 26
#include <unistd.h>

S
sun_fan 已提交
27
#include "init_param.h"
28
#include "init_utils.h"
S
sun_fan 已提交
29
#include "param_message.h"
Z
zhong_ning 已提交
30 31
#include "param_manager.h"
#include "param_request.h"
S
sun_fan 已提交
32
#include "trigger_manager.h"
Z
zhong_ning 已提交
33

S
sun_fan 已提交
34
static ParamWorkSpace g_paramWorkSpace = { 0, {}, NULL, {}, NULL, NULL };
Z
zhong_ning 已提交
35

S
sun_fan 已提交
36 37
static void OnClose(ParamTaskPtr client)
{
X
xionglei6 已提交
38
    PARAM_LOGV("OnClose %p", client);
S
sun_fan 已提交
39
    ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client);
X
xionglei6 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    if (client == g_paramWorkSpace.watcherTask) {
        ClearWatchTrigger(watcher, TRIGGER_PARAM_WATCH);
    } else {
        ClearWatchTrigger(watcher, TRIGGER_PARAM_WAIT);
    }
}

static void TimerCallback(const ParamTaskPtr timer, void *context)
{
    UNUSED(context);
    UNUSED(timer);
    int ret = CheckWatchTriggerTimeout();
    // no wait node
    if (ret == 0 && g_paramWorkSpace.timer != NULL) {
        ParamTaskClose(g_paramWorkSpace.timer);
        g_paramWorkSpace.timer = NULL;
    }
S
sun_fan 已提交
57
}
Z
zhong_ning 已提交
58

S
sun_fan 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71
static int AddParam(WorkSpace *workSpace, const char *name, const char *value, uint32_t *dataIndex)
{
    ParamTrieNode *node = AddTrieNode(workSpace, name, strlen(name));
    PARAM_CHECK(node != NULL, return PARAM_CODE_REACHED_MAX, "Failed to add node");
    ParamNode *entry = (ParamNode *)GetTrieNode(workSpace, node->dataIndex);
    if (entry == NULL) {
        uint32_t offset = AddParamNode(workSpace, name, strlen(name), value, strlen(value));
        PARAM_CHECK(offset > 0, return PARAM_CODE_REACHED_MAX, "Failed to allocate name %s", name);
        SaveIndex(&node->dataIndex, offset);
    }
    *dataIndex = node->dataIndex;
    return 0;
}
Z
zhong_ning 已提交
72

4
411148299@qq.com 已提交
73
static int UpdateParam(const WorkSpace *workSpace, uint32_t *dataIndex, const char *name, const char *value)
Z
zhong_ning 已提交
74
{
S
sun_fan 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    ParamNode *entry = (ParamNode *)GetTrieNode(workSpace, *dataIndex);
    PARAM_CHECK(entry != NULL, return PARAM_CODE_REACHED_MAX, "Failed to update param value %s %u", name, *dataIndex);
    PARAM_CHECK(entry->keyLength == strlen(name), return PARAM_CODE_INVALID_NAME, "Failed to check name len %s", name);

    uint32_t valueLen = strlen(value);
    uint32_t commitId = atomic_load_explicit(&entry->commitId, memory_order_relaxed);
    atomic_store_explicit(&entry->commitId, commitId | PARAM_FLAGS_MODIFY, memory_order_relaxed);

    if (entry->valueLength < PARAM_VALUE_LEN_MAX && valueLen < PARAM_VALUE_LEN_MAX) {
        int ret = memcpy_s(entry->data + entry->keyLength + 1, PARAM_VALUE_LEN_MAX, value, valueLen + 1);
        PARAM_CHECK(ret == EOK, return PARAM_CODE_INVALID_VALUE, "Failed to copy value");
        entry->valueLength = valueLen;
    }
    uint32_t flags = commitId & ~PARAM_FLAGS_COMMITID;
    atomic_store_explicit(&entry->commitId, (++commitId) | flags, memory_order_release);
    futex_wake(&entry->commitId, INT_MAX);
    return 0;
Z
zhong_ning 已提交
92 93
}

4
411148299@qq.com 已提交
94
static int CheckParamValue(const WorkSpace *workSpace, const ParamTrieNode *node, const char *name, const char *value)
Z
zhong_ning 已提交
95
{
S
sun_fan 已提交
96 97 98 99 100 101 102 103 104 105 106
    if (IS_READY_ONLY(name)) {
        PARAM_CHECK(strlen(value) < PARAM_CONST_VALUE_LEN_MAX,
            return PARAM_CODE_INVALID_VALUE, "Illegal param value %s", value);
        if (node != NULL && node->dataIndex != 0) {
            PARAM_LOGE("Read-only param was already set %s", name);
            return PARAM_CODE_READ_ONLY;
        }
    } else {
        // 限制非read only的参数,防止参数值修改后,原空间不能保存
        PARAM_CHECK(strlen(value) < PARAM_VALUE_LEN_MAX,
            return PARAM_CODE_INVALID_VALUE, "Illegal param value %s", value);
Z
zhong_ning 已提交
107
    }
S
sun_fan 已提交
108 109
    return 0;
}
S
sun_fan 已提交
110

4
411148299@qq.com 已提交
111
int WriteParam(const WorkSpace *workSpace, const char *name, const char *value, uint32_t *dataIndex, int onlyAdd)
S
sun_fan 已提交
112 113 114 115 116 117 118 119 120 121
{
    PARAM_CHECK(workSpace != NULL && dataIndex != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid workSpace");
    PARAM_CHECK(value != NULL && name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid name or value");
    ParamTrieNode *node = FindTrieNode(workSpace, name, strlen(name), NULL);
    int ret = CheckParamValue(workSpace, node, name, value);
    PARAM_CHECK(ret == 0, return ret, "Invalid param value param: %s=%s", name, value);
    if (node != NULL && node->dataIndex != 0) {
        *dataIndex = node->dataIndex;
        if (onlyAdd) {
            return 0;
Z
zhong_ning 已提交
122
        }
S
sun_fan 已提交
123 124
        return UpdateParam(workSpace, &node->dataIndex, name, value);
    }
4
411148299@qq.com 已提交
125
    return AddParam((WorkSpace *)workSpace, name, value, dataIndex);
S
sun_fan 已提交
126
}
Z
zhong_ning 已提交
127

S
sun_fan 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
PARAM_STATIC int AddSecurityLabel(const ParamAuditData *auditData, void *context)
{
    PARAM_CHECK(auditData != NULL && auditData->name != NULL, return -1, "Invalid auditData");
    PARAM_CHECK(context != NULL, return -1, "Invalid context");
    ParamWorkSpace *workSpace = (ParamWorkSpace *)context;
    int ret = CheckParamName(auditData->name, 1);
    PARAM_CHECK(ret == 0, return ret, "Illegal param name %s", auditData->name);

    ParamTrieNode *node = FindTrieNode(&workSpace->paramSpace, auditData->name, strlen(auditData->name), NULL);
    if (node == NULL) {
        node = AddTrieNode(&workSpace->paramSpace, auditData->name, strlen(auditData->name));
    }
    PARAM_CHECK(node != NULL, return PARAM_CODE_REACHED_MAX, "Failed to add node %s", auditData->name);
    if (node->labelIndex == 0) { // can not support update for label
        uint32_t offset = AddParamSecruityNode(&workSpace->paramSpace, auditData);
        PARAM_CHECK(offset != 0, return PARAM_CODE_REACHED_MAX, "Failed to add label");
        SaveIndex(&node->labelIndex, offset);
    } else {
#ifdef STARTUP_INIT_TEST
        ParamSecruityNode *label = (ParamSecruityNode *)GetTrieNode(&workSpace->paramSpace, node->labelIndex);
        label->mode = auditData->dacData.mode;
149 150
        label->uid = auditData->dacData.uid;
        label->gid = auditData->dacData.gid;
S
sun_fan 已提交
151 152 153
#endif
        PARAM_LOGE("Error, repeate to add label for name %s", auditData->name);
    }
X
xionglei6 已提交
154
    PARAM_LOGV("AddSecurityLabel label gid %d uid %d mode %o name: %s", auditData->dacData.gid, auditData->dacData.uid,
S
sun_fan 已提交
155 156 157 158
               auditData->dacData.mode, auditData->name);
    return 0;
}

X
xionglei6 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
static char *BuildKey(ParamWorkSpace *workSpace, const char *format, ...)
{
    va_list vargs;
    va_start(vargs, format);
    size_t buffSize = sizeof(workSpace->buffer);
    int len = vsnprintf_s(workSpace->buffer, buffSize, buffSize - 1, format, vargs);
    va_end(vargs);
    if (len > 0 && len < buffSize) {
        workSpace->buffer[len] = '\0';
        for (int i = 0; i < len; i++) {
            if (workSpace->buffer[i] == '|') {
                workSpace->buffer[i] = '\0';
            }
        }
        return workSpace->buffer;
    }
    return NULL;
}

static char *GetServiceCtrlName(ParamWorkSpace *workSpace, const char *name, const char *value)
S
sun_fan 已提交
179 180 181 182 183
{
    static char *ctrlParam[] = {
        "ohos.ctl.start",
        "ohos.ctl.stop"
    };
X
xionglei6 已提交
184
    static char *installParam[] = {
185
        "ohos.servicectrl."
X
xionglei6 已提交
186
    };
S
sun_fan 已提交
187 188 189
    static char *powerCtrlArg[][2] = {
        {"reboot,shutdown", "reboot.shutdown"},
        {"reboot,updater", "reboot.updater"},
X
add ut  
xionglei6 已提交
190
        {"reboot,flashd", "reboot.flashd"},
S
sun_fan 已提交
191 192 193
        {"reboot", "reboot"},
    };
    char *key = NULL;
X
add ut  
xionglei6 已提交
194
    if (strcmp("ohos.startup.powerctrl", name) == 0) {
195
        for (size_t i = 0; i < ARRAY_LENGTH(powerCtrlArg); i++) {
S
sun_fan 已提交
196
            if (strncmp(value, powerCtrlArg[i][0], strlen(powerCtrlArg[i][0])) == 0) {
X
xionglei6 已提交
197
                return BuildKey(workSpace, "%s%s", OHOS_SERVICE_CTRL_PREFIX, powerCtrlArg[i][1]);
S
sun_fan 已提交
198
            }
Z
zhong_ning 已提交
199
        }
X
xionglei6 已提交
200 201 202 203 204 205 206 207 208
        return key;
    }
    for (size_t i = 0; i < ARRAY_LENGTH(ctrlParam); i++) {
        if (strcmp(name, ctrlParam[i]) == 0) {
            return BuildKey(workSpace, "%s%s", OHOS_SERVICE_CTRL_PREFIX, value);
        }
    }

    for (size_t i = 0; i < ARRAY_LENGTH(installParam); i++) {
209
        if (strncmp(name, installParam[i], strlen(installParam[i])) == 0) {
X
xionglei6 已提交
210
            return BuildKey(workSpace, "%s.%s", name, value);
Z
zhong_ning 已提交
211
        }
S
sun_fan 已提交
212 213 214
    }
    return key;
}
Z
zhong_ning 已提交
215

S
sun_fan 已提交
216 217 218 219 220 221
static void CheckAndSendTrigger(ParamWorkSpace *workSpace, uint32_t dataIndex, const char *name, const char *value)
{
    ParamNode *entry = (ParamNode *)GetTrieNode(&workSpace->paramSpace, dataIndex);
    PARAM_CHECK(entry != NULL, return, "Failed to get data %s ", name);
    uint32_t trigger = 1;
    if ((atomic_load_explicit(&entry->commitId, memory_order_relaxed) & PARAM_FLAGS_TRIGGED) != PARAM_FLAGS_TRIGGED) {
4
411148299@qq.com 已提交
222
        trigger = (CheckAndMarkTrigger(TRIGGER_PARAM, name) != 0) ? 1 : 0;
Z
zhong_ning 已提交
223
    }
S
sun_fan 已提交
224 225 226 227 228 229 230 231 232
    if (trigger) {
        atomic_store_explicit(&entry->commitId,
            atomic_load_explicit(&entry->commitId, memory_order_relaxed) | PARAM_FLAGS_TRIGGED, memory_order_release);
        // notify event to process trigger
        PostParamTrigger(EVENT_TRIGGER_PARAM, name, value);
    }

    int wait = 1;
    if ((atomic_load_explicit(&entry->commitId, memory_order_relaxed) & PARAM_FLAGS_WAITED) != PARAM_FLAGS_WAITED) {
4
411148299@qq.com 已提交
233
        wait = (CheckAndMarkTrigger(TRIGGER_PARAM_WAIT, name) != 0) ? 1 : 0;
S
sun_fan 已提交
234 235 236 237 238 239 240
    }
    if (wait) {
        atomic_store_explicit(&entry->commitId,
            atomic_load_explicit(&entry->commitId, memory_order_relaxed) | PARAM_FLAGS_WAITED, memory_order_release);
        PostParamTrigger(EVENT_TRIGGER_PARAM_WAIT, name, value);
    }
    PostParamTrigger(EVENT_TRIGGER_PARAM_WATCH, name, value);
Z
zhong_ning 已提交
241 242
}

S
sun_fan 已提交
243
static int SystemSetParam(const char *name, const char *value, const ParamSecurityLabel *srcLabel)
Z
zhong_ning 已提交
244
{
X
xionglei6 已提交
245
    PARAM_LOGV("SystemSetParam name %s value: %s", name, value);
S
sun_fan 已提交
246 247
    int ret = CheckParamName(name, 0);
    PARAM_CHECK(ret == 0, return ret, "Illegal param name %s", name);
X
xionglei6 已提交
248
    char *key = GetServiceCtrlName(&g_paramWorkSpace, name, value);
S
sun_fan 已提交
249 250
    if (srcLabel != NULL) {
        ret = CheckParamPermission(&g_paramWorkSpace, srcLabel, (key == NULL) ? name : key, DAC_WRITE);
Z
zhong_ning 已提交
251
    }
4
411148299@qq.com 已提交
252
    PARAM_CHECK(ret == 0, return ret, "Forbit to set parameter %s", name);
253

X
xionglei6 已提交
254
    if (key != NULL) { // ctrl param
X
add ut  
xionglei6 已提交
255 256
        ret = CheckParamValue(&g_paramWorkSpace.paramSpace, NULL, name, value);
        PARAM_CHECK(ret == 0, return ret, "Invalid param value param: %s=%s", name, value);
S
sun_fan 已提交
257 258
        PostParamTrigger(EVENT_TRIGGER_PARAM, name, value);
    } else {
259 260 261 262 263
        uint32_t dataIndex = 0;
        ret = WriteParam(&g_paramWorkSpace.paramSpace, name, value, &dataIndex, 0);
        PARAM_CHECK(ret == 0, return ret, "Failed to set param %d name %s %s", ret, name, value);
        ret = WritePersistParam(&g_paramWorkSpace, name, value);
        PARAM_CHECK(ret == 0, return ret, "Failed to set persist param name %s", name);
S
sun_fan 已提交
264 265 266
        CheckAndSendTrigger(&g_paramWorkSpace, dataIndex, name, value);
    }
    return ret;
Z
zhong_ning 已提交
267 268
}

S
sun_fan 已提交
269
static int SendResponseMsg(ParamTaskPtr worker, const ParamMessage *msg, int result)
Z
zhong_ning 已提交
270
{
S
sun_fan 已提交
271 272 273 274 275 276 277 278 279
    ParamResponseMessage *response = NULL;
    response = (ParamResponseMessage *)CreateParamMessage(msg->type, msg->key, sizeof(ParamResponseMessage));
    PARAM_CHECK(response != NULL, return PARAM_CODE_ERROR, "Failed to alloc memory for response");
    response->msg.id.msgId = msg->id.msgId;
    response->result = result;
    response->msg.msgSize = sizeof(ParamResponseMessage);
    ParamTaskSendMsg(worker, (ParamMessage *)response);
    return 0;
}
Z
zhong_ning 已提交
280

X
xionglei6 已提交
281
static int SendWatcherNotifyMessage(const TriggerExtInfo *extData, const char *content, uint32_t size)
S
sun_fan 已提交
282 283
{
    PARAM_CHECK(content != NULL, return -1, "Invalid content");
X
xionglei6 已提交
284
    PARAM_CHECK(extData != NULL && extData->stream != NULL, return -1, "Invalid extData");
S
sun_fan 已提交
285 286 287 288 289
    uint32_t msgSize = sizeof(ParamMessage) + PARAM_ALIGN(strlen(content) + 1);
    ParamMessage *msg = (ParamMessage *)CreateParamMessage(MSG_NOTIFY_PARAM, "*", msgSize);
    PARAM_CHECK(msg != NULL, return -1, "Failed to create msg ");

    uint32_t offset = 0;
4
411148299@qq.com 已提交
290
    int ret;
S
sun_fan 已提交
291 292 293 294 295 296 297 298 299
    char *tmp = strstr(content, "=");
    if (tmp != NULL) {
        ret = strncpy_s(msg->key, sizeof(msg->key) - 1, content, tmp - content);
        PARAM_CHECK(ret == 0, free(msg);
            return -1, "Failed to fill value");
        tmp++;
        ret = FillParamMsgContent(msg, &offset, PARAM_VALUE, tmp, strlen(tmp));
        PARAM_CHECK(ret == 0, free(msg);
            return -1, "Failed to fill value");
X
xionglei6 已提交
300 301
    } else if (content != NULL && strlen(content) > 0) {
        ret = FillParamMsgContent(msg, &offset, PARAM_VALUE, content, strlen(content));
S
sun_fan 已提交
302 303 304
        PARAM_CHECK(ret == 0, free(msg);
            return -1, "Failed to fill value");
    }
Z
zhong_ning 已提交
305

X
xionglei6 已提交
306 307 308 309 310 311
    msg->id.msgId = 0;
    if (extData->type == TRIGGER_PARAM_WAIT) {
        msg->id.msgId = extData->info.waitInfo.waitId;
    } else {
        msg->id.msgId = extData->info.watchInfo.watchId;
    }
S
sun_fan 已提交
312
    msg->msgSize = sizeof(ParamMessage) + offset;
X
xionglei6 已提交
313 314 315 316
    PARAM_LOGV("SendWatcherNotifyMessage cmd %s, id %d msgSize %d para: %s",
        (extData->type == TRIGGER_PARAM_WAIT) ? "wait" : "watcher",
        msg->id.msgId, msg->msgSize, content);
    ParamTaskSendMsg(extData->stream, msg);
Z
zhong_ning 已提交
317 318 319
    return 0;
}

S
sun_fan 已提交
320
static int HandleParamSet(const ParamTaskPtr worker, const ParamMessage *msg)
Z
zhong_ning 已提交
321
{
S
sun_fan 已提交
322 323 324
    uint32_t offset = 0;
    ParamMsgContent *valueContent = GetNextContent(msg, &offset);
    PARAM_CHECK(valueContent != NULL, return -1, "Invalid msg for %s", msg->key);
4
411148299@qq.com 已提交
325
    int ret;
S
sun_fan 已提交
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    ParamMsgContent *lableContent =  GetNextContent(msg, &offset);
    ParamSecurityLabel *srcLabel = NULL;
    if (lableContent != NULL && lableContent->contentSize != 0) {
        PARAM_CHECK(g_paramWorkSpace.paramSecurityOps.securityDecodeLabel != NULL,
            return -1, "Can not get decode function");
        ret = g_paramWorkSpace.paramSecurityOps.securityDecodeLabel(&srcLabel,
            lableContent->content, lableContent->contentSize);
        PARAM_CHECK(ret == 0, return ret,
            "Failed to decode param %d name %s %s", ret, msg->key, valueContent->content);
    }

    ret = SystemSetParam(msg->key, valueContent->content, srcLabel);
    if (srcLabel != NULL && g_paramWorkSpace.paramSecurityOps.securityFreeLabel != NULL) {
        g_paramWorkSpace.paramSecurityOps.securityFreeLabel(srcLabel);
    }
    return SendResponseMsg(worker, msg, ret);
Z
zhong_ning 已提交
342 343
}

4
411148299@qq.com 已提交
344
static ParamNode *CheckMatchParamWait(const ParamWorkSpace *worksapce, const char *name, const char *value)
Z
zhong_ning 已提交
345
{
S
sun_fan 已提交
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
    uint32_t nameLength = strlen(name);
    ParamTrieNode *node = FindTrieNode(&worksapce->paramSpace, name, nameLength, NULL);
    if (node == NULL || node->dataIndex == 0) {
        return NULL;
    }
    ParamNode *param = (ParamNode *)GetTrieNode(&worksapce->paramSpace, node->dataIndex);
    if (param == NULL) {
        return NULL;
    }
    if ((param->keyLength != nameLength) || (strncmp(param->data, name, nameLength) != 0)) { // compare name
        return NULL;
    }
    atomic_store_explicit(&param->commitId,
        atomic_load_explicit(&param->commitId, memory_order_relaxed) | PARAM_FLAGS_WAITED, memory_order_release);
    if ((strncmp(value, "*", 1) == 0) || (strcmp(param->data + nameLength + 1, value) == 0)) { // compare value
        return param;
    }
    char *tmp = strstr(value, "*");
    if (tmp != NULL && (strncmp(param->data + nameLength + 1, value, tmp - value) == 0)) {
        return param;
    }
    return NULL;
Z
zhong_ning 已提交
368 369
}

X
xionglei6 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
static int32_t AddWatchNode(struct tagTriggerNode_ *trigger, const struct TriggerExtInfo_ *extInfo)
{
    ParamWatcher *watcher = NULL;
    if (extInfo != NULL && extInfo->stream != NULL) {
        watcher = (ParamWatcher *)ParamGetTaskUserData(extInfo->stream);
    }
    PARAM_CHECK(watcher != NULL, return -1, "Failed to get param watcher data");
    if (extInfo->type == TRIGGER_PARAM_WAIT) {
        WaitNode *node = (WaitNode *)trigger;
        ListInit(&node->item);
        node->timeout = extInfo->info.waitInfo.timeout;
        node->stream = extInfo->stream;
        node->waitId = extInfo->info.waitInfo.waitId;
        ListAddTail(&watcher->triggerHead, &node->item);
    } else {
        WatchNode *node = (WatchNode *)trigger;
        ListInit(&node->item);
        node->watchId = extInfo->info.watchInfo.watchId;
        ListAddTail(&watcher->triggerHead, &node->item);
    }
    return 0;
}

static TriggerNode *AddWatcherTrigger(int triggerType, const char *condition, const TriggerExtInfo *extData)
{
    TriggerWorkSpace *workSpace = GetTriggerWorkSpace();
    TriggerHeader *header = (TriggerHeader *)&workSpace->triggerHead[extData->type];
    return header->addTrigger(workSpace, condition, extData);
}

static int32_t ExecuteWatchTrigger_(const struct tagTriggerNode_ *trigger, const char *content, uint32_t size)
{
    TriggerExtInfo extData = {};
    extData.type = trigger->type;
    if (trigger->type == TRIGGER_PARAM_WAIT) {
        WaitNode *node = (WaitNode *)trigger;
        extData.stream = node->stream;
        extData.info.waitInfo.waitId = node->waitId;
        extData.info.waitInfo.timeout = node->timeout;
    } else {
        WatchNode *node = (WatchNode *)trigger;
        extData.stream = g_paramWorkSpace.watcherTask;
        extData.info.watchInfo.watchId = node->watchId;
    }
    if (content == NULL) {
        return SendWatcherNotifyMessage(&extData, "", 0);
    }
    return SendWatcherNotifyMessage(&extData, content, size);
}

4
411148299@qq.com 已提交
420
static int HandleParamWaitAdd(const ParamWorkSpace *worksapce, const ParamTaskPtr worker, const ParamMessage *msg)
Z
zhong_ning 已提交
421
{
S
sun_fan 已提交
422 423 424 425 426
    PARAM_CHECK(msg != NULL, return -1, "Invalid message");
    uint32_t offset = 0;
    uint32_t timeout = DEFAULT_PARAM_WAIT_TIMEOUT;
    ParamMsgContent *valueContent = GetNextContent(msg, &offset);
    PARAM_CHECK(valueContent != NULL, return -1, "Invalid msg");
4
411148299@qq.com 已提交
427
    PARAM_CHECK(valueContent->contentSize <= PARAM_CONST_VALUE_LEN_MAX, return -1, "Invalid msg");
S
sun_fan 已提交
428 429 430 431 432
    ParamMsgContent *timeoutContent = GetNextContent(msg, &offset);
    if (timeoutContent != NULL) {
        timeout = *((uint32_t *)(timeoutContent->content));
    }

X
xionglei6 已提交
433 434 435 436 437 438 439
    PARAM_LOGV("HandleParamWaitAdd name %s timeout %d", msg->key, timeout);
    TriggerExtInfo extData = {};
    extData.addNode = AddWatchNode;
    extData.type = TRIGGER_PARAM_WAIT;
    extData.stream = worker;
    extData.info.waitInfo.waitId = msg->id.watcherId;
    extData.info.waitInfo.timeout = timeout;
S
sun_fan 已提交
440 441 442
    // first check match, if match send response to client
    ParamNode *param = CheckMatchParamWait(worksapce, msg->key, valueContent->content);
    if (param != NULL) {
X
xionglei6 已提交
443
        SendWatcherNotifyMessage(&extData, param->data, param->valueLength);
S
sun_fan 已提交
444 445 446 447
        return 0;
    }

    uint32_t buffSize = strlen(msg->key) + valueContent->contentSize + 1 + 1;
4
411148299@qq.com 已提交
448
    char *condition = calloc(1, buffSize);
S
sun_fan 已提交
449 450 451 452
    PARAM_CHECK(condition != NULL, return -1, "Failed to create condition for %s", msg->key);
    int ret = sprintf_s(condition, buffSize - 1, "%s=%s", msg->key, valueContent->content);
    PARAM_CHECK(ret > EOK, free(condition);
        return -1, "Failed to copy name for %s", msg->key);
X
xionglei6 已提交
453
    TriggerNode *trigger = AddWatcherTrigger(TRIGGER_PARAM_WAIT, condition, &extData);
S
sun_fan 已提交
454 455 456
    PARAM_CHECK(trigger != NULL, free(condition);
        return -1, "Failed to add trigger for %s", msg->key);
    free(condition);
X
xionglei6 已提交
457 458 459 460 461 462 463 464 465 466
    if (g_paramWorkSpace.timer == NULL) {
        ret = ParamTimerCreate(&g_paramWorkSpace.timer, TimerCallback, &g_paramWorkSpace);
        PARAM_CHECK(ret == 0, return 0, "Failed to create timer %s", msg->key);
        ret = ParamTimerStart(g_paramWorkSpace.timer, MS_UNIT, (uint64_t)-1);
        PARAM_CHECK(ret == 0,
            ParamTaskClose(g_paramWorkSpace.timer);
            g_paramWorkSpace.timer = NULL;
            return 0, "Failed to set timer %s", msg->key);
        PARAM_LOGI("Start timer %p", g_paramWorkSpace.timer);
    }
S
sun_fan 已提交
467
    return 0;
Z
zhong_ning 已提交
468 469
}

S
sun_fan 已提交
470
static int HandleParamWatcherAdd(ParamWorkSpace *workSpace, const ParamTaskPtr worker, const ParamMessage *msg)
Z
zhong_ning 已提交
471
{
S
sun_fan 已提交
472
    PARAM_CHECK(msg != NULL, return -1, "Invalid message");
X
xionglei6 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    PARAM_CHECK((g_paramWorkSpace.watcherTask == NULL) ||
        (g_paramWorkSpace.watcherTask == worker), return -1, "Invalid watcher worker");
    g_paramWorkSpace.watcherTask = worker;
    TriggerExtInfo extData = {};
    extData.type = TRIGGER_PARAM_WATCH;
    extData.addNode = AddWatchNode;
    extData.stream = worker;
    extData.info.watchInfo.watchId = msg->id.watcherId;
    TriggerNode *trigger = AddWatcherTrigger(TRIGGER_PARAM_WATCH, msg->key, &extData);
    if (trigger == NULL) {
        PARAM_LOGE("Failed to add trigger for %s", msg->key);
        return SendResponseMsg(worker, msg, -1);
    }
    PARAM_LOGV("HandleParamWatcherAdd name %s watcher: %d", msg->key, msg->id.watcherId);
    return SendResponseMsg(worker, msg, 0);
S
sun_fan 已提交
488 489 490 491 492
}

static int HandleParamWatcherDel(ParamWorkSpace *workSpace, const ParamTaskPtr worker, const ParamMessage *msg)
{
    PARAM_CHECK(msg != NULL, return -1, "Invalid message");
X
xionglei6 已提交
493 494
    PARAM_LOGV("HandleParamWatcherDel name %s watcher: %d", msg->key, msg->id.watcherId);
    DelWatchTrigger(TRIGGER_PARAM_WATCH, (const void *)&msg->id.watcherId);
S
sun_fan 已提交
495 496 497 498 499 500 501
    return SendResponseMsg(worker, msg, 0);
}

PARAM_STATIC int ProcessMessage(const ParamTaskPtr worker, const ParamMessage *msg)
{
    PARAM_CHECK(msg != NULL, return -1, "Invalid msg");
    PARAM_CHECK(worker != NULL, return -1, "Invalid worker");
4
411148299@qq.com 已提交
502
    int ret = PARAM_CODE_INVALID_PARAM;
Z
zhong_ning 已提交
503
    switch (msg->type) {
S
sun_fan 已提交
504 505 506 507 508 509 510
        case MSG_SET_PARAM:
            ret = HandleParamSet(worker, msg);
            break;
        case MSG_WAIT_PARAM:
            ret = HandleParamWaitAdd(&g_paramWorkSpace, worker, msg);
            break;
        case MSG_ADD_WATCHER:
X
xionglei6 已提交
511
            ret = HandleParamWatcherAdd(&g_paramWorkSpace, worker, msg);
S
sun_fan 已提交
512 513
            break;
        case MSG_DEL_WATCHER:
X
xionglei6 已提交
514
            ret = HandleParamWatcherDel(&g_paramWorkSpace, worker, msg);
Z
zhong_ning 已提交
515 516 517 518
            break;
        default:
            break;
    }
S
sun_fan 已提交
519 520
    PARAM_CHECK(ret == 0, return -1, "Failed to process message ret %d", ret);
    return 0;
Z
zhong_ning 已提交
521 522
}

4
411148299@qq.com 已提交
523
static int LoadDefaultParam_(const char *fileName, uint32_t mode, const char *exclude[], uint32_t count)
Z
zhong_ning 已提交
524
{
S
sun_fan 已提交
525 526 527
    uint32_t paramNum = 0;
    FILE *fp = fopen(fileName, "r");
    PARAM_CHECK(fp != NULL, return -1, "Open file %s fail", fileName);
4
411148299@qq.com 已提交
528
    char *buff = calloc(1, sizeof(SubStringInfo) * (SUBSTR_INFO_VALUE + 1) + PARAM_BUFFER_SIZE);
S
sun_fan 已提交
529 530 531 532 533
    PARAM_CHECK(buff != NULL, (void)fclose(fp);
        return -1, "Failed to alloc memory for load %s", fileName);

    SubStringInfo *info = (SubStringInfo *)(buff + PARAM_BUFFER_SIZE);
    while (fgets(buff, PARAM_BUFFER_SIZE, fp) != NULL) {
4
411148299@qq.com 已提交
534
        buff[PARAM_BUFFER_SIZE - 1] = '\0';
S
sun_fan 已提交
535 536 537 538 539 540 541 542 543 544 545 546 547
        int subStrNumber = GetSubStringInfo(buff, strlen(buff), '=', info, SUBSTR_INFO_VALUE + 1);
        if (subStrNumber <= SUBSTR_INFO_VALUE) {
            continue;
        }
        // 过滤
        for (uint32_t i = 0; i < count; i++) {
            if (strncmp(info[0].value, exclude[i], strlen(exclude[i])) == 0) {
                PARAM_LOGI("Do not set %s parameters", info[0].value);
                continue;
            }
        }
        int ret = CheckParamName(info[0].value, 0);
        PARAM_CHECK(ret == 0, continue, "Illegal param name %s", info[0].value);
X
xionglei6 已提交
548
        PARAM_LOGV("Add default parameter %s  %s", info[0].value, info[1].value);
S
sun_fan 已提交
549 550 551 552 553 554 555 556 557 558 559
        uint32_t dataIndex = 0;
        ret = WriteParam(&g_paramWorkSpace.paramSpace,
            info[0].value, info[1].value, &dataIndex, mode & LOAD_PARAM_ONLY_ADD);
        PARAM_CHECK(ret == 0, continue, "Failed to set param %d %s", ret, buff);
        paramNum++;
    }
    (void)fclose(fp);
    free(buff);
    PARAM_LOGI("Load parameters success %s total %u", fileName, paramNum);
    return 0;
}
Z
zhong_ning 已提交
560

X
xionglei6 已提交
561
PARAM_STATIC int OnIncomingConnect(LoopHandle loop, TaskHandle server)
S
sun_fan 已提交
562 563 564 565 566 567 568 569 570 571 572
{
    ParamStreamInfo info = {};
    info.server = NULL;
    info.close = OnClose;
    info.recvMessage = ProcessMessage;
    info.incomingConnect = NULL;
    ParamTaskPtr client = NULL;
    int ret = ParamStreamCreate(&client, server, &info, sizeof(ParamWatcher));
    PARAM_CHECK(ret == 0, return -1, "Failed to create client");

    ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client);
X
xionglei6 已提交
573 574
    PARAM_CHECK(watcher != NULL, return -1, "Failed to get watcher");
    ListInit(&watcher->triggerHead);
S
sun_fan 已提交
575
    watcher->stream = client;
X
xionglei6 已提交
576 577 578
#ifdef STARTUP_INIT_TEST
    GetParamWorkSpace()->watcherTask = client;
#endif
S
sun_fan 已提交
579 580
    return 0;
}
Z
zhong_ning 已提交
581

582 583 584
static int GetParamValueFromBuffer(const char *name, const char *buffer, char *value, int length)
{
    size_t bootLen = strlen(OHOS_BOOT);
X
xionglei6 已提交
585 586 587
    const char *tmpName = name + bootLen;
    int ret = GetProcCmdlineValue(tmpName, buffer, value, length);
    return ret;
588 589 590 591 592 593
}

static int LoadParamFromCmdLine(void)
{
    static const char *cmdLines[] = {
        OHOS_BOOT"hardware",
X
xionglei6 已提交
594
        OHOS_BOOT"bootgroup",
595 596 597 598 599 600 601 602 603
#ifdef STARTUP_INIT_TEST
        OHOS_BOOT"mem",
        OHOS_BOOT"console",
        OHOS_BOOT"mmz",
        OHOS_BOOT"androidboot.selinux",
        OHOS_BOOT"init",
        OHOS_BOOT"root",
        OHOS_BOOT"uuid",
        OHOS_BOOT"rootfstype",
X
xionglei6 已提交
604
        OHOS_BOOT"blkdevparts"
605 606 607 608
#endif
    };
    char *data = ReadFileData(PARAM_CMD_LINE);
    PARAM_CHECK(data != NULL, return -1, "Failed to read file %s", PARAM_CMD_LINE);
X
xionglei6 已提交
609
    char *value = calloc(1, PARAM_CONST_VALUE_LEN_MAX + 1);
610 611 612 613 614 615
    PARAM_CHECK(value != NULL, free(data);
        return -1, "Failed to read file %s", PARAM_CMD_LINE);

    for (size_t i = 0; i < ARRAY_LENGTH(cmdLines); i++) {
        int ret = GetParamValueFromBuffer(cmdLines[i], data, value, PARAM_CONST_VALUE_LEN_MAX);
        if (ret == 0) {
X
xionglei6 已提交
616
            PARAM_LOGV("Add param from cmdline %s %s", cmdLines[i], value);
617
            ret = CheckParamName(cmdLines[i], 0);
X
xionglei6 已提交
618
            PARAM_CHECK(ret == 0, break, "Invalid name %s", cmdLines[i]);
619
            uint32_t dataIndex = 0;
X
xionglei6 已提交
620
            PARAM_LOGV("**** cmdLines[%d] %s, value %s", i, cmdLines[i], value);
621
            ret = WriteParam(&g_paramWorkSpace.paramSpace, cmdLines[i], value, &dataIndex, 0);
X
xionglei6 已提交
622
            PARAM_CHECK(ret == 0, break, "Failed to write param %s %s", cmdLines[i], value);
623 624 625 626
        } else {
            PARAM_LOGE("Can not find arrt %s", cmdLines[i]);
        }
    }
X
xionglei6 已提交
627
    PARAM_LOGV("Parse cmdline finish %s", PARAM_CMD_LINE);
628 629 630 631 632
    free(data);
    free(value);
    return 0;
}

Z
zhong_ning 已提交
633 634 635
int SystemWriteParam(const char *name, const char *value)
{
    PARAM_CHECK(name != NULL && value != NULL, return -1, "The name is null");
S
sun_fan 已提交
636
    return SystemSetParam(name, value, g_paramWorkSpace.securityLabel);
Z
zhong_ning 已提交
637 638 639 640 641 642
}

int SystemReadParam(const char *name, char *value, unsigned int *len)
{
    PARAM_CHECK(name != NULL && len != NULL, return -1, "The name is null");
    ParamHandle handle = 0;
S
sun_fan 已提交
643
    int ret = ReadParamWithCheck(&g_paramWorkSpace, name, DAC_READ, &handle);
Z
zhong_ning 已提交
644 645 646 647 648 649
    if (ret == 0) {
        ret = ReadParamValue(&g_paramWorkSpace, handle, value, len);
    }
    return ret;
}

S
sun_fan 已提交
650
int LoadPersistParams(void)
Z
zhong_ning 已提交
651
{
S
sun_fan 已提交
652
    return LoadPersistParam(&g_paramWorkSpace);
Z
zhong_ning 已提交
653 654
}

S
sun_fan 已提交
655
static int ProcessParamFile(const char *fileName, void *context)
Z
zhong_ning 已提交
656
{
S
sun_fan 已提交
657
    static const char *exclude[] = {"ctl.", "selinux.restorecon_recursive"};
4
411148299@qq.com 已提交
658
    uint32_t mode = *(int *)context;
659
    return LoadDefaultParam_(fileName, mode, exclude, ARRAY_LENGTH(exclude));
S
sun_fan 已提交
660 661
}

4
411148299@qq.com 已提交
662
int LoadDefaultParams(const char *fileName, uint32_t mode)
S
sun_fan 已提交
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
{
    PARAM_CHECK(fileName != NULL, return -1, "Invalid fielname for load");
    if (!PARAM_TEST_FLAG(g_paramWorkSpace.flags, WORKSPACE_FLAGS_INIT)) {
        return PARAM_CODE_NOT_INIT;
    }
    PARAM_LOGI("load default parameters %s.", fileName);
    int ret = 0;
    struct stat st;
    if ((stat(fileName, &st) == 0) && !S_ISDIR(st.st_mode)) {
        ret = ProcessParamFile(fileName, &mode);
    } else {
        ret = ReadFileInDir(fileName, ".para", ProcessParamFile, &mode);
    }

    // load security label
    ParamSecurityOps *ops = &g_paramWorkSpace.paramSecurityOps;
    if (ops->securityGetLabel != NULL) {
        ret = ops->securityGetLabel(AddSecurityLabel, fileName, (void *)&g_paramWorkSpace);
    }
    return ret;
}

void InitParamService(void)
{
    PARAM_LOGI("InitParamService pipe: %s.", PIPE_NAME);
    CheckAndCreateDir(PIPE_NAME);
    int ret = InitParamWorkSpace(&g_paramWorkSpace, 0);
    PARAM_CHECK(ret == 0, return, "Init parameter workspace fail");
    ret = InitPersistParamWorkSpace(&g_paramWorkSpace);
    PARAM_CHECK(ret == 0, return, "Init persist parameter workspace fail");
    if (g_paramWorkSpace.serverTask == NULL) {
        ParamStreamInfo info = {};
        info.server = PIPE_NAME;
        info.close = NULL;
        info.recvMessage = NULL;
        info.incomingConnect = OnIncomingConnect;
        ret = ParamServerCreate(&g_paramWorkSpace.serverTask, &info);
        PARAM_CHECK(ret == 0, return, "Failed to create server");
    }
    ret = InitTriggerWorkSpace();
    PARAM_CHECK(ret == 0, return, "Failed to init trigger");

X
xionglei6 已提交
705 706
    RegisterTriggerExec(TRIGGER_PARAM_WAIT, ExecuteWatchTrigger_);
    RegisterTriggerExec(TRIGGER_PARAM_WATCH, ExecuteWatchTrigger_);
S
sun_fan 已提交
707 708 709 710 711 712 713 714
    ParamAuditData auditData = {};
    auditData.name = "#";
    auditData.label = NULL;
    auditData.dacData.gid = getegid();
    auditData.dacData.uid = geteuid();
    auditData.dacData.mode = DAC_ALL_PERMISSION;
    ret = AddSecurityLabel(&auditData, (void *)&g_paramWorkSpace);
    PARAM_CHECK(ret == 0, return, "Failed to add default dac label");
715 716 717

    // 读取cmdline的参数
    LoadParamFromCmdLine();
S
sun_fan 已提交
718 719 720 721
}

int StartParamService(void)
{
S
sun_fan 已提交
722
    return ParamServiceStart();
S
sun_fan 已提交
723 724 725 726 727
}

void StopParamService(void)
{
    PARAM_LOGI("StopParamService.");
S
sun_fan 已提交
728
    ClosePersistParamWorkSpace();
S
sun_fan 已提交
729 730
    CloseParamWorkSpace(&g_paramWorkSpace);
    CloseTriggerWorkSpace();
4
411148299@qq.com 已提交
731
    ParamTaskClose(g_paramWorkSpace.serverTask);
S
sun_fan 已提交
732 733 734 735 736 737 738 739
    g_paramWorkSpace.serverTask = NULL;
    ParamServiceStop();
}

ParamWorkSpace *GetParamWorkSpace(void)
{
    return &g_paramWorkSpace;
}
740 741 742 743 744 745 746 747

void DumpParametersAndTriggers(void)
{
    DumpParameters(&g_paramWorkSpace, 1);
    if (GetTriggerWorkSpace() != NULL) {
        DumpTrigger(GetTriggerWorkSpace());
    }
}