1 /*
2 * Copyright (c) 2020 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "param_adaptor.h"
17 #include <ctype.h>
18 #include <securec.h>
19 #include "ohos_errno.h"
20 #include "utils_file.h"
21
IsValidChar(const char ch)22 static boolean IsValidChar(const char ch)
23 {
24 if (islower(ch) || isdigit(ch) || (ch == '_') || (ch == '.')) {
25 return TRUE;
26 }
27 return FALSE;
28 }
29
IsValidValue(const char * value,unsigned int len)30 static boolean IsValidValue(const char* value, unsigned int len)
31 {
32 if ((value == NULL) || (*value == '\0') || (strlen(value) >= len)) {
33 return FALSE;
34 }
35 return TRUE;
36 }
37
IsValidKey(const char * key)38 static boolean IsValidKey(const char* key)
39 {
40 if (!IsValidValue(key, MAX_KEY_LEN)) {
41 return FALSE;
42 }
43 int keyLen = strlen(key);
44 for (int i = 0; i < keyLen; i++) {
45 if (!IsValidChar(key[i])) {
46 return FALSE;
47 }
48 }
49 return TRUE;
50 }
51
GetSysParam(const char * key,char * value,unsigned int len)52 int GetSysParam(const char* key, char* value, unsigned int len)
53 {
54 if (!IsValidKey(key) || (value == NULL) || (len > MAX_GET_VALUE_LEN)) {
55 return EC_INVALID;
56 }
57 unsigned int valueLen = 0;
58 if (UtilsFileStat(key, &valueLen) != EC_SUCCESS) {
59 return EC_FAILURE;
60 }
61 if (valueLen >= len) {
62 return EC_INVALID;
63 }
64 int fd = UtilsFileOpen(key, O_RDONLY_FS, 0);
65 if (fd < 0) {
66 return EC_FAILURE;
67 }
68
69 int ret = UtilsFileRead(fd, value, valueLen);
70 UtilsFileClose(fd);
71 fd = -1;
72 if (ret < 0) {
73 return EC_FAILURE;
74 }
75 value[valueLen] = '\0';
76 return valueLen;
77 }
78
SetSysParam(const char * key,const char * value)79 int SetSysParam(const char* key, const char* value)
80 {
81 if (!IsValidKey(key) || !IsValidValue(value, MAX_VALUE_LEN)) {
82 return EC_INVALID;
83 }
84 int fd = UtilsFileOpen(key, O_RDWR_FS | O_CREAT_FS | O_TRUNC_FS, 0);
85 if (fd < 0) {
86 return EC_FAILURE;
87 }
88
89 int ret = UtilsFileWrite(fd, value, strlen(value));
90 UtilsFileClose(fd);
91 fd = -1;
92 return (ret < 0) ? EC_FAILURE : EC_SUCCESS;
93 }
94
CheckPermission(void)95 boolean CheckPermission(void)
96 {
97 return TRUE;
98 }
99