param_service.c 28.5 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_LOGD("OnClose %p", client);
S
sun_fan 已提交
39 40 41 42
    ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client);
    ClearWatcherTrigger(watcher);
    ListRemove(&watcher->node);
}
Z
zhong_ning 已提交
43

S
sun_fan 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56
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 已提交
57

4
411148299@qq.com 已提交
58
static int UpdateParam(const WorkSpace *workSpace, uint32_t *dataIndex, const char *name, const char *value)
Z
zhong_ning 已提交
59
{
S
sun_fan 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    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 已提交
77 78
}

4
411148299@qq.com 已提交
79
static int CheckParamValue(const WorkSpace *workSpace, const ParamTrieNode *node, const char *name, const char *value)
Z
zhong_ning 已提交
80
{
S
sun_fan 已提交
81 82 83 84 85 86 87 88 89 90 91
    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 已提交
92
    }
S
sun_fan 已提交
93 94
    return 0;
}
S
sun_fan 已提交
95

4
411148299@qq.com 已提交
96
int WriteParam(const WorkSpace *workSpace, const char *name, const char *value, uint32_t *dataIndex, int onlyAdd)
S
sun_fan 已提交
97 98 99 100 101 102 103 104 105 106
{
    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 已提交
107
        }
S
sun_fan 已提交
108 109
        return UpdateParam(workSpace, &node->dataIndex, name, value);
    }
4
411148299@qq.com 已提交
110
    return AddParam((WorkSpace *)workSpace, name, value, dataIndex);
S
sun_fan 已提交
111
}
Z
zhong_ning 已提交
112

S
sun_fan 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
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;
134 135
        label->uid = auditData->dacData.uid;
        label->gid = auditData->dacData.gid;
S
sun_fan 已提交
136 137 138
#endif
        PARAM_LOGE("Error, repeate to add label for name %s", auditData->name);
    }
X
add ut  
xionglei6 已提交
139
    PARAM_LOGD("AddSecurityLabel label gid %d uid %d mode %o name: %s", auditData->dacData.gid, auditData->dacData.uid,
S
sun_fan 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152
               auditData->dacData.mode, auditData->name);
    return 0;
}

static char *GetServiceCtrlName(const char *name, const char *value)
{
    static char *ctrlParam[] = {
        "ohos.ctl.start",
        "ohos.ctl.stop"
    };
    static char *powerCtrlArg[][2] = {
        {"reboot,shutdown", "reboot.shutdown"},
        {"reboot,updater", "reboot.updater"},
X
add ut  
xionglei6 已提交
153
        {"reboot,flashd", "reboot.flashd"},
S
sun_fan 已提交
154 155 156
        {"reboot", "reboot"},
    };
    char *key = NULL;
X
add ut  
xionglei6 已提交
157
    if (strcmp("ohos.startup.powerctrl", name) == 0) {
158
        for (size_t i = 0; i < ARRAY_LENGTH(powerCtrlArg); i++) {
S
sun_fan 已提交
159 160 161 162 163
            if (strncmp(value, powerCtrlArg[i][0], strlen(powerCtrlArg[i][0])) == 0) {
                uint32_t keySize = strlen(powerCtrlArg[i][1]) + strlen(OHOS_SERVICE_CTRL_PREFIX) + 1;
                key = (char *)malloc(keySize + 1);
                PARAM_CHECK(key != NULL, return NULL, "Failed to alloc memory for %s", name);
                int ret = sprintf_s(key, keySize, "%s%s", OHOS_SERVICE_CTRL_PREFIX, powerCtrlArg[i][1]);
4
411148299@qq.com 已提交
164 165
                PARAM_CHECK(ret > EOK, free(key);
                    return NULL, "Failed to format key for %s", name);
S
sun_fan 已提交
166 167
                return key;
            }
Z
zhong_ning 已提交
168
        }
S
sun_fan 已提交
169
    } else {
170
        for (size_t i = 0; i < ARRAY_LENGTH(ctrlParam); i++) {
S
sun_fan 已提交
171 172 173 174 175
            if (strcmp(name, ctrlParam[i]) == 0) {
                uint32_t keySize = strlen(value) + strlen(OHOS_SERVICE_CTRL_PREFIX) + 1;
                key = (char *)malloc(keySize + 1);
                PARAM_CHECK(key != NULL, return NULL, "Failed to alloc memory for %s", name);
                int ret = sprintf_s(key, keySize, "%s%s", OHOS_SERVICE_CTRL_PREFIX, value);
4
411148299@qq.com 已提交
176 177
                PARAM_CHECK(ret > EOK, free(key);
                    return NULL, "Failed to format key for %s", name);
S
sun_fan 已提交
178 179
                return key;
            }
Z
zhong_ning 已提交
180
        }
S
sun_fan 已提交
181 182 183
    }
    return key;
}
Z
zhong_ning 已提交
184

S
sun_fan 已提交
185 186 187 188 189 190
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 已提交
191
        trigger = (CheckAndMarkTrigger(TRIGGER_PARAM, name) != 0) ? 1 : 0;
Z
zhong_ning 已提交
192
    }
S
sun_fan 已提交
193 194 195 196 197 198 199 200 201
    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 已提交
202
        wait = (CheckAndMarkTrigger(TRIGGER_PARAM_WAIT, name) != 0) ? 1 : 0;
S
sun_fan 已提交
203 204 205 206 207 208 209
    }
    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 已提交
210 211
}

S
sun_fan 已提交
212
static int SystemSetParam(const char *name, const char *value, const ParamSecurityLabel *srcLabel)
Z
zhong_ning 已提交
213
{
S
sun_fan 已提交
214 215 216 217 218 219 220 221
    PARAM_LOGD("SystemSetParam name %s value: %s", name, value);
    int ret = CheckParamName(name, 0);
    PARAM_CHECK(ret == 0, return ret, "Illegal param name %s", name);

    int serviceCtrl = 0;
    char *key = GetServiceCtrlName(name, value);
    if (srcLabel != NULL) {
        ret = CheckParamPermission(&g_paramWorkSpace, srcLabel, (key == NULL) ? name : key, DAC_WRITE);
Z
zhong_ning 已提交
222
    }
S
sun_fan 已提交
223 224 225
    if (key != NULL) {
        serviceCtrl = 1;
        free(key);
Z
zhong_ning 已提交
226
    }
4
411148299@qq.com 已提交
227
    PARAM_CHECK(ret == 0, return ret, "Forbit to set parameter %s", name);
228

S
sun_fan 已提交
229
    if (serviceCtrl) {
X
add ut  
xionglei6 已提交
230 231
        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 已提交
232 233
        PostParamTrigger(EVENT_TRIGGER_PARAM, name, value);
    } else {
234 235 236 237 238
        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 已提交
239 240
        CheckAndSendTrigger(&g_paramWorkSpace, dataIndex, name, value);
    }
S
sun_fan 已提交
241 242 243 244

    // watcher stoped
    if (strcmp(name, "init.svc.param_watcher") == 0 && strcmp(value, "stopped") == 0) {
        ParamWatcher *watcher = GetParamWatcher(NULL);
X
xionglei6 已提交
245
        PARAM_LOGD("ClearWatcherTrigger");
S
sun_fan 已提交
246 247
        ClearWatcherTrigger(watcher);
    }
S
sun_fan 已提交
248
    return ret;
Z
zhong_ning 已提交
249 250
}

S
sun_fan 已提交
251
static int SendResponseMsg(ParamTaskPtr worker, const ParamMessage *msg, int result)
Z
zhong_ning 已提交
252
{
S
sun_fan 已提交
253 254 255 256 257 258 259 260 261
    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 已提交
262

4
411148299@qq.com 已提交
263
static int SendWatcherNotifyMessage(const TriggerExtData *extData, int cmd, const char *content)
S
sun_fan 已提交
264 265 266 267 268 269 270 271 272
{
    UNUSED(cmd);
    PARAM_CHECK(content != NULL, return -1, "Invalid content");
    PARAM_CHECK(extData != NULL && extData->watcher != NULL, return -1, "Invalid extData");
    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 已提交
273
    int ret;
S
sun_fan 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287
    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");
    } else {
        ret = FillParamMsgContent(msg, &offset, PARAM_VALUE, tmp, strlen(content));
        PARAM_CHECK(ret == 0, free(msg);
            return -1, "Failed to fill value");
    }
Z
zhong_ning 已提交
288

S
sun_fan 已提交
289 290
    msg->id.msgId = extData->watcherId;
    msg->msgSize = sizeof(ParamMessage) + offset;
X
xionglei6 已提交
291 292 293
    PARAM_LOGD("SendWatcherNotifyMessage cmd %s, watcherId %d msgSize %d para: %s",
        (cmd == CMD_INDEX_FOR_PARA_WAIT) ? "wait" : "watcher",
        extData->watcherId, msg->msgSize, content);
S
sun_fan 已提交
294
    ParamTaskSendMsg(extData->watcher->stream, msg);
Z
zhong_ning 已提交
295 296 297
    return 0;
}

S
sun_fan 已提交
298
static int HandleParamSet(const ParamTaskPtr worker, const ParamMessage *msg)
Z
zhong_ning 已提交
299
{
S
sun_fan 已提交
300 301 302
    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 已提交
303
    int ret;
S
sun_fan 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    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 已提交
320 321
}

4
411148299@qq.com 已提交
322
static ParamNode *CheckMatchParamWait(const ParamWorkSpace *worksapce, const char *name, const char *value)
Z
zhong_ning 已提交
323
{
S
sun_fan 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    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 已提交
346 347
}

4
411148299@qq.com 已提交
348
static int HandleParamWaitAdd(const ParamWorkSpace *worksapce, const ParamTaskPtr worker, const ParamMessage *msg)
Z
zhong_ning 已提交
349
{
S
sun_fan 已提交
350 351 352 353 354
    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 已提交
355
    PARAM_CHECK(valueContent->contentSize <= PARAM_CONST_VALUE_LEN_MAX, return -1, "Invalid msg");
S
sun_fan 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    ParamMsgContent *timeoutContent = GetNextContent(msg, &offset);
    if (timeoutContent != NULL) {
        timeout = *((uint32_t *)(timeoutContent->content));
    }

    PARAM_LOGD("HandleParamWaitAdd name %s timeout %d", msg->key, timeout);
    ParamWatcher *watcher = GetParamWatcher(worker);
    PARAM_CHECK(watcher != NULL, return -1, "Failed to get param watcher data");
    watcher->timeout = timeout;

    TriggerExtData extData = {};
    extData.excuteCmd = SendWatcherNotifyMessage;
    extData.watcherId = msg->id.watcherId;
    extData.watcher = watcher;
    // first check match, if match send response to client
    ParamNode *param = CheckMatchParamWait(worksapce, msg->key, valueContent->content);
    if (param != NULL) {
        SendWatcherNotifyMessage(&extData, CMD_INDEX_FOR_PARA_WAIT, param->data);
        return 0;
    }

    uint32_t buffSize = strlen(msg->key) + valueContent->contentSize + 1 + 1;
4
411148299@qq.com 已提交
378
    char *condition = calloc(1, buffSize);
S
sun_fan 已提交
379 380 381 382 383 384 385 386 387
    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);
    TriggerNode *trigger = AddWatcherTrigger(watcher, TRIGGER_PARAM_WAIT, msg->key, condition, &extData);
    PARAM_CHECK(trigger != NULL, free(condition);
        return -1, "Failed to add trigger for %s", msg->key);
    free(condition);
    return 0;
Z
zhong_ning 已提交
388 389
}

S
sun_fan 已提交
390
static int HandleParamWatcherAdd(ParamWorkSpace *workSpace, const ParamTaskPtr worker, const ParamMessage *msg)
Z
zhong_ning 已提交
391
{
S
sun_fan 已提交
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 420 421 422 423
    PARAM_CHECK(msg != NULL, return -1, "Invalid message");
    TriggerExtData extData = {};
    extData.excuteCmd = SendWatcherNotifyMessage;
    extData.watcherId = msg->id.watcherId;
    int ret = 0;
    do {
        ParamWatcher *watcher = GetParamWatcher(NULL);
        PARAM_CHECK(watcher != NULL, ret = -1;
            break, "Failed to get param watcher data");
        watcher->stream = worker;
        TriggerNode *trigger = AddWatcherTrigger(watcher, TRIGGER_PARAM_WATCH, msg->key, NULL, &extData);
        PARAM_CHECK(trigger != NULL, ret = -1;
            break, "Failed to add trigger for %s", msg->key);
    } while (0);
    PARAM_LOGD("HandleParamWatcherAdd name %s watcher: %d", msg->key, msg->id.watcherId);
    return SendResponseMsg(worker, msg, ret);
}

static int HandleParamWatcherDel(ParamWorkSpace *workSpace, const ParamTaskPtr worker, const ParamMessage *msg)
{
    PARAM_CHECK(msg != NULL, return -1, "Invalid message");
    ParamWatcher *watcher = GetParamWatcher(NULL);
    PARAM_CHECK(watcher != NULL, return -1, "Failed to get param watcher data");
    PARAM_LOGD("HandleParamWatcherDel name %s watcher: %d", msg->key, msg->id.watcherId);
    DelWatcherTrigger(watcher, msg->id.watcherId);
    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 已提交
424
    int ret = PARAM_CODE_INVALID_PARAM;
Z
zhong_ning 已提交
425
    switch (msg->type) {
S
sun_fan 已提交
426 427 428 429 430 431 432
        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 已提交
433
            ret = HandleParamWatcherAdd(&g_paramWorkSpace, worker, msg);
S
sun_fan 已提交
434 435
            break;
        case MSG_DEL_WATCHER:
X
xionglei6 已提交
436
            ret = HandleParamWatcherDel(&g_paramWorkSpace, worker, msg);
Z
zhong_ning 已提交
437 438 439 440
            break;
        default:
            break;
    }
S
sun_fan 已提交
441 442
    PARAM_CHECK(ret == 0, return -1, "Failed to process message ret %d", ret);
    return 0;
Z
zhong_ning 已提交
443 444
}

4
411148299@qq.com 已提交
445
static int LoadDefaultParam_(const char *fileName, uint32_t mode, const char *exclude[], uint32_t count)
Z
zhong_ning 已提交
446
{
S
sun_fan 已提交
447 448 449
    uint32_t paramNum = 0;
    FILE *fp = fopen(fileName, "r");
    PARAM_CHECK(fp != NULL, return -1, "Open file %s fail", fileName);
4
411148299@qq.com 已提交
450
    char *buff = calloc(1, sizeof(SubStringInfo) * (SUBSTR_INFO_VALUE + 1) + PARAM_BUFFER_SIZE);
S
sun_fan 已提交
451 452 453 454 455
    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 已提交
456
        buff[PARAM_BUFFER_SIZE - 1] = '\0';
S
sun_fan 已提交
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        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);
        PARAM_LOGI("Add default parameter %s  %s", info[0].value, info[1].value);
        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 已提交
482

4
411148299@qq.com 已提交
483
static int OnIncomingConnect(const ParamTaskPtr server, uint32_t flags)
S
sun_fan 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496
{
    PARAM_LOGD("OnIncomingConnect %p", server);
    ParamStreamInfo info = {};
    info.flags = WORKER_TYPE_CLIENT | flags;
    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);
4
411148299@qq.com 已提交
497
    PARAM_CHECK(watcher != NULL, return -1, "Failed to get watcher");
S
sun_fan 已提交
498 499 500 501 502 503 504
    ListInit(&watcher->node);
    PARAM_TRIGGER_HEAD_INIT(watcher->triggerHead);
    ListAddTail(&GetTriggerWorkSpace()->waitList, &watcher->node);
    watcher->stream = client;
    watcher->timeout = UINT32_MAX;
    return 0;
}
Z
zhong_ning 已提交
505

S
sun_fan 已提交
506 507 508
static void TimerCallback(ParamTaskPtr timer, void *context)
{
    UNUSED(context);
4
411148299@qq.com 已提交
509
    PARAM_CHECK(GetTriggerWorkSpace() != NULL, return, "Invalid wrokspace");
S
sun_fan 已提交
510 511 512 513 514 515 516 517 518 519 520
    ParamWatcher *watcher = GetNextParamWatcher(GetTriggerWorkSpace(), NULL);
    while (watcher != NULL) {
        ParamWatcher *next = GetNextParamWatcher(GetTriggerWorkSpace(), watcher);
        if (watcher->timeout > 0) {
            watcher->timeout--;
        } else {
            PARAM_LOGD("TimerCallback watcher->timeout %p ", watcher);
            ParamTaskClose(watcher->stream);
        }
        watcher = next;
    }
Z
zhong_ning 已提交
521 522
}

523 524 525
static int GetParamValueFromBuffer(const char *name, const char *buffer, char *value, int length)
{
    size_t bootLen = strlen(OHOS_BOOT);
X
xionglei6 已提交
526 527 528
    const char *tmpName = name + bootLen;
    int ret = GetProcCmdlineValue(tmpName, buffer, value, length);
    return ret;
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
}

static int LoadParamFromCmdLine(void)
{
    static const char *cmdLines[] = {
        OHOS_BOOT"hardware",
#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"aaaaa",
        OHOS_BOOT"rootfstype",
X
xionglei6 已提交
545
        OHOS_BOOT"blkdevparts"
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
#endif
    };
    char *data = ReadFileData(PARAM_CMD_LINE);
    PARAM_CHECK(data != NULL, return -1, "Failed to read file %s", PARAM_CMD_LINE);
    char *value = malloc(PARAM_CONST_VALUE_LEN_MAX);
    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) {
            PARAM_LOGD("Add param from cmdline %s %s", cmdLines[i], value);
            ret = CheckParamName(cmdLines[i], 0);
            PARAM_CHECK(ret == 0, return -1, "Invalid name %s", cmdLines[i]);
            uint32_t dataIndex = 0;
X
xionglei6 已提交
561
            PARAM_LOGE("**** cmdLines[%d] %s, value %s", i, cmdLines[i], value);
562 563 564 565 566 567 568 569 570 571 572 573
            ret = WriteParam(&g_paramWorkSpace.paramSpace, cmdLines[i], value, &dataIndex, 0);
            PARAM_CHECK(ret == 0, return -1, "Failed to write param %s %s", cmdLines[i], value);
        } else {
            PARAM_LOGE("Can not find arrt %s", cmdLines[i]);
        }
    }
    PARAM_LOGD("Parse cmdline finish %s", PARAM_CMD_LINE);
    free(data);
    free(value);
    return 0;
}

Z
zhong_ning 已提交
574 575 576
int SystemWriteParam(const char *name, const char *value)
{
    PARAM_CHECK(name != NULL && value != NULL, return -1, "The name is null");
S
sun_fan 已提交
577
    return SystemSetParam(name, value, g_paramWorkSpace.securityLabel);
Z
zhong_ning 已提交
578 579 580 581 582 583
}

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 已提交
584
    int ret = ReadParamWithCheck(&g_paramWorkSpace, name, DAC_READ, &handle);
Z
zhong_ning 已提交
585 586 587 588 589 590
    if (ret == 0) {
        ret = ReadParamValue(&g_paramWorkSpace, handle, value, len);
    }
    return ret;
}

S
sun_fan 已提交
591
int LoadPersistParams(void)
Z
zhong_ning 已提交
592
{
S
sun_fan 已提交
593
    return LoadPersistParam(&g_paramWorkSpace);
Z
zhong_ning 已提交
594 595
}

S
sun_fan 已提交
596
static int ProcessParamFile(const char *fileName, void *context)
Z
zhong_ning 已提交
597
{
S
sun_fan 已提交
598
    static const char *exclude[] = {"ctl.", "selinux.restorecon_recursive"};
4
411148299@qq.com 已提交
599
    uint32_t mode = *(int *)context;
600
    return LoadDefaultParam_(fileName, mode, exclude, ARRAY_LENGTH(exclude));
S
sun_fan 已提交
601 602
}

4
411148299@qq.com 已提交
603
int LoadDefaultParams(const char *fileName, uint32_t mode)
S
sun_fan 已提交
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 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
{
    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.flags = WORKER_TYPE_SERVER;
        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");
        PARAM_LOGD("OnIncomingConnect %p", g_paramWorkSpace.serverTask);
    }

    if (g_paramWorkSpace.timer == NULL) {
        ParamTimerCreate(&g_paramWorkSpace.timer, TimerCallback, &g_paramWorkSpace);
        ParamTimerStart(g_paramWorkSpace.timer, 1, MS_UNIT);
        PARAM_LOGD("Start timer %p", g_paramWorkSpace.timer);
    }
    ret = InitTriggerWorkSpace();
    PARAM_CHECK(ret == 0, return, "Failed to init trigger");

    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");
662 663 664

    // 读取cmdline的参数
    LoadParamFromCmdLine();
S
sun_fan 已提交
665 666 667 668
}

int StartParamService(void)
{
S
sun_fan 已提交
669
    return ParamServiceStart();
S
sun_fan 已提交
670 671 672 673 674
}

void StopParamService(void)
{
    PARAM_LOGI("StopParamService.");
S
sun_fan 已提交
675
    ClosePersistParamWorkSpace();
S
sun_fan 已提交
676 677
    CloseParamWorkSpace(&g_paramWorkSpace);
    CloseTriggerWorkSpace();
4
411148299@qq.com 已提交
678
    ParamTaskClose(g_paramWorkSpace.serverTask);
S
sun_fan 已提交
679 680 681 682 683 684 685 686
    g_paramWorkSpace.serverTask = NULL;
    ParamServiceStop();
}

ParamWorkSpace *GetParamWorkSpace(void)
{
    return &g_paramWorkSpace;
}
687 688 689 690 691 692 693 694

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