1 /*
2 * Copyright (c) 2020-2021 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 #include "init_cmds.h"
16
17 #include <ctype.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <net/if.h>
21 #include <stdbool.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/ioctl.h>
25 #include <sys/mount.h>
26 #include <sys/resource.h>
27 #include <sys/stat.h>
28 #include <sys/syscall.h>
29 #include <sys/sysmacros.h>
30 #include <sys/wait.h>
31 #include <unistd.h>
32
33 #include "init.h"
34 #include "init_jobs_internal.h"
35 #include "init_log.h"
36 #include "init_cmdexecutor.h"
37 #include "init_service_manager.h"
38 #include "init_utils.h"
39 #include "securec.h"
40
41 #ifndef OHOS_LITE
42 #include "hookmgr.h"
43 #include "bootstage.h"
44
45 /**
46 * init cmd hooking execute
47 */
InitCmdHookExecute(const char * cmdName,const char * cmdContent,INIT_TIMING_STAT * cmdTimer)48 static void InitCmdHookExecute(const char *cmdName, const char *cmdContent, INIT_TIMING_STAT *cmdTimer)
49 {
50 INIT_CMD_INFO context;
51
52 context.cmdName = cmdName;
53 context.cmdContent = cmdContent;
54 context.reserved = (const char *)cmdTimer;
55
56 (void)HookMgrExecute(GetBootStageHookMgr(), INIT_CMD_RECORD, (void *)(&context), NULL);
57 }
58 #endif
59
AddOneArg(const char * param,size_t paramLen)60 static char *AddOneArg(const char *param, size_t paramLen)
61 {
62 int valueCount = 1;
63 char *begin = strchr(param, '$');
64 while (begin != NULL) {
65 valueCount++;
66 begin = strchr(begin + 1, '$');
67 }
68 size_t allocSize = paramLen + (PARAM_VALUE_LEN_MAX * valueCount) + 1;
69 char *arg = calloc(allocSize, sizeof(char));
70 INIT_CHECK(arg != NULL, return NULL);
71 int ret = GetParamValue(param, paramLen, arg, allocSize);
72 INIT_ERROR_CHECK(ret == 0, free(arg);
73 return NULL, "Failed to get value for %s", param);
74 return arg;
75 }
76
BuildStringFromCmdArg(const struct CmdArgs * ctx,int startIndex)77 char *BuildStringFromCmdArg(const struct CmdArgs *ctx, int startIndex)
78 {
79 INIT_ERROR_CHECK(ctx != NULL, return NULL, "Failed to get cmd args ");
80 char *options = (char *)calloc(1, OPTIONS_SIZE + 1);
81 INIT_ERROR_CHECK(options != NULL, return NULL, "Failed to get memory ");
82 options[0] = '\0';
83 int curr = 0;
84 for (int i = startIndex; i < ctx->argc; i++) { // save opt
85 if (ctx->argv[i] == NULL) {
86 continue;
87 }
88 int len = snprintf_s(options + curr, OPTIONS_SIZE - curr, OPTIONS_SIZE - 1 - curr, "%s ", ctx->argv[i]);
89 if (len <= 0) {
90 INIT_LOGE("Failed to format other opt");
91 options[0] = '\0';
92 return options;
93 }
94 curr += len;
95 }
96 if ((curr > 0) && (curr < OPTIONS_SIZE)) {
97 options[curr - 1] = '\0';
98 }
99 return options;
100 }
101
GetCmdArg(const char * cmdContent,const char * delim,int argsCount)102 const struct CmdArgs *GetCmdArg(const char *cmdContent, const char *delim, int argsCount)
103 {
104 INIT_CHECK_RETURN_VALUE(cmdContent != NULL, NULL);
105 INIT_CHECK_RETURN_VALUE(delim != NULL, NULL);
106 INIT_WARNING_CHECK(argsCount <= SPACES_CNT_IN_CMD_MAX, argsCount = SPACES_CNT_IN_CMD_MAX,
107 "Too much arguments for command, max number is %d", SPACES_CNT_IN_CMD_MAX);
108 struct CmdArgs *ctx = (struct CmdArgs *)calloc(1, sizeof(struct CmdArgs) + sizeof(char *) * (argsCount + 1));
109 INIT_ERROR_CHECK(ctx != NULL, return NULL, "Failed to malloc memory for arg");
110 ctx->argc = 0;
111 const char *p = cmdContent;
112 const char *end = cmdContent + strlen(cmdContent);
113 const char *token = NULL;
114 do {
115 // Skip lead whitespaces
116 while (isspace(*p)) {
117 p++;
118 }
119 if (end == p) { // empty cmd content
120 break;
121 }
122 token = strstr(p, delim);
123 if (token == NULL) {
124 ctx->argv[ctx->argc] = AddOneArg(p, end - p);
125 INIT_CHECK(ctx->argv[ctx->argc] != NULL, FreeCmdArg(ctx);
126 return NULL);
127 } else {
128 ctx->argv[ctx->argc] = AddOneArg(p, token - p);
129 INIT_CHECK(ctx->argv[ctx->argc] != NULL, FreeCmdArg(ctx);
130 return NULL);
131 }
132 ctx->argc++;
133 ctx->argv[ctx->argc] = NULL;
134 if (ctx->argc == argsCount) {
135 break;
136 }
137 p = token;
138 } while (token != NULL);
139 return ctx;
140 }
141
FreeCmdArg(struct CmdArgs * cmd)142 void FreeCmdArg(struct CmdArgs *cmd)
143 {
144 INIT_CHECK_ONLY_RETURN(cmd != NULL);
145 for (int i = 0; i < cmd->argc; ++i) {
146 if (cmd->argv[i] != NULL) {
147 free(cmd->argv[i]);
148 }
149 }
150 free(cmd);
151 return;
152 }
153
ExecCmd(const struct CmdTable * cmd,const char * cmdContent)154 void ExecCmd(const struct CmdTable *cmd, const char *cmdContent)
155 {
156 INIT_ERROR_CHECK(cmd != NULL, return, "Invalid cmd.");
157 const struct CmdArgs *ctx = GetCmdArg(cmdContent, " ", cmd->maxArg);
158 if (ctx == NULL) {
159 INIT_LOGE("Invalid arguments cmd: %s content: %s", cmd->name, cmdContent);
160 } else if ((ctx->argc <= cmd->maxArg) && (ctx->argc >= cmd->minArg)) {
161 cmd->DoFuncion(ctx);
162 } else {
163 INIT_LOGE("Invalid arguments cmd: %s content: %s argc: %d %d", cmd->name, cmdContent, ctx->argc, cmd->maxArg);
164 }
165 FreeCmdArg((struct CmdArgs *)ctx);
166 }
167
SetProcName(const struct CmdArgs * ctx,const char * procFile)168 static void SetProcName(const struct CmdArgs *ctx, const char *procFile)
169 {
170 int fd = open(procFile, O_WRONLY | O_CREAT | O_CLOEXEC | O_TRUNC, S_IRUSR | S_IWUSR);
171 INIT_ERROR_CHECK(fd >= 0, return, "Failed to set %s errno: %d", procFile, errno);
172
173 size_t size = strlen(ctx->argv[0]);
174 ssize_t n = write(fd, ctx->argv[0], size);
175 INIT_ERROR_CHECK(n == (ssize_t)size, close(fd);
176 return, "Failed to write domainname errno: %d", errno);
177 close(fd);
178 }
179
DoSetDomainname(const struct CmdArgs * ctx)180 static void DoSetDomainname(const struct CmdArgs *ctx)
181 {
182 SetProcName(ctx, "/proc/sys/kernel/domainname");
183 }
184
DoSetHostname(const struct CmdArgs * ctx)185 static void DoSetHostname(const struct CmdArgs *ctx)
186 {
187 SetProcName(ctx, "/proc/sys/kernel/hostname");
188 }
189
DoSleep(const struct CmdArgs * ctx)190 static void DoSleep(const struct CmdArgs *ctx)
191 {
192 errno = 0;
193 unsigned long sleepTime = strtoul(ctx->argv[0], NULL, DECIMAL_BASE);
194 INIT_ERROR_CHECK(errno == 0, return, "cannot convert sleep time in command \" sleep \"");
195
196 // Limit sleep time in 5 seconds
197 const unsigned long sleepTimeLimit = 5;
198 INIT_CHECK(sleepTime <= sleepTimeLimit, sleepTime = sleepTimeLimit);
199 INIT_LOGI("Sleeping %d second(s)", sleepTime);
200 sleep((unsigned int)sleepTime);
201 }
202
DoWait(const struct CmdArgs * ctx)203 static void DoWait(const struct CmdArgs *ctx)
204 {
205 const int filePos = 0;
206 const int timePos = 1;
207 unsigned long waitSecond = WAIT_MAX_SECOND;
208
209 if (ctx->argc == timePos + 1) {
210 errno = 0;
211 waitSecond = strtoul(ctx->argv[timePos], NULL, DECIMAL_BASE);
212 INIT_ERROR_CHECK(errno == 0,
213 return, "cannot convert sleep time in command \" wait \"");
214 }
215
216 INIT_LOGI("Waiting %s %lu second(s)", ctx->argv[filePos], waitSecond);
217 WaitForFile(ctx->argv[filePos], waitSecond);
218 }
219
DoStart(const struct CmdArgs * ctx)220 static void DoStart(const struct CmdArgs *ctx)
221 {
222 INIT_LOGV("DoStart %s", ctx->argv[0]);
223 StartServiceByName(ctx->argv[0]);
224 }
225
DoStop(const struct CmdArgs * ctx)226 static void DoStop(const struct CmdArgs *ctx)
227 {
228 INIT_LOGV("DoStop %s", ctx->argv[0]);
229 StopServiceByName(ctx->argv[0]);
230 return;
231 }
232
DoReset(const struct CmdArgs * ctx)233 static void DoReset(const struct CmdArgs *ctx)
234 {
235 INIT_LOGV("DoReset %s", ctx->argv[0]);
236 Service *service = GetServiceByName(ctx->argv[0]);
237 if (service == NULL) {
238 INIT_LOGE("Reset cmd cannot find service %s.", ctx->argv[0]);
239 return;
240 }
241 if (service->pid > 0) {
242 #ifndef OHOS_LITE
243 SERVICE_RESTART_CTX context;
244 int pid = service->pid;
245 context.serviceName = service->name;
246 context.serviceNode = (const char *)&pid;
247 (void)HookMgrExecute(GetBootStageHookMgr(), INIT_SERVICE_RESTART, (void *)(&context), NULL);
248 #endif
249 if (kill(service->pid, GetKillServiceSig(ctx->argv[0])) != 0) {
250 INIT_LOGE("stop service %s pid %d failed! err %d.", service->name, service->pid, errno);
251 return;
252 }
253 } else {
254 StartServiceByName(ctx->argv[0]);
255 }
256 return;
257 }
258
DoCopy(const struct CmdArgs * ctx)259 static void DoCopy(const struct CmdArgs *ctx)
260 {
261 int srcFd = -1;
262 int dstFd = -1;
263 char buf[MAX_COPY_BUF_SIZE] = { 0 };
264 char *realPath1 = NULL;
265 char *realPath2 = NULL;
266 do {
267 realPath1 = GetRealPath(ctx->argv[0]);
268 if (realPath1 == NULL) {
269 INIT_LOGE("Failed to get real path %s", ctx->argv[0]);
270 break;
271 }
272
273 srcFd = open(realPath1, O_RDONLY);
274 if (srcFd < 0) {
275 INIT_LOGE("Failed to open source path %s %d", ctx->argv[0], errno);
276 break;
277 }
278
279 struct stat fileStat = { 0 };
280 if (stat(ctx->argv[0], &fileStat) != 0) {
281 INIT_LOGE("Failed to state source path %s %d", ctx->argv[0], errno);
282 break;
283 }
284 mode_t mode = fileStat.st_mode;
285 realPath2 = GetRealPath(ctx->argv[1]);
286 if (realPath2 != NULL) {
287 dstFd = open(realPath2, O_WRONLY | O_TRUNC | O_CREAT, mode);
288 } else {
289 dstFd = open(ctx->argv[1], O_WRONLY | O_TRUNC | O_CREAT, mode);
290 }
291 if (dstFd < 0) {
292 INIT_LOGE("Failed to open dest path %s %d", ctx->argv[1], errno);
293 break;
294 }
295 int rdLen = 0;
296 while ((rdLen = read(srcFd, buf, sizeof(buf) - 1)) > 0) {
297 int rtLen = write(dstFd, buf, rdLen);
298 if (rtLen != rdLen) {
299 INIT_LOGE("Failed to write to dest path %s %d", ctx->argv[1], errno);
300 break;
301 }
302 }
303 fsync(dstFd);
304 } while (0);
305 INIT_CHECK(srcFd < 0, close(srcFd));
306 INIT_CHECK(dstFd < 0, close(dstFd));
307 INIT_CHECK(realPath1 == NULL, free(realPath1));
308 INIT_CHECK(realPath2 == NULL, free(realPath2));
309 }
310
SetOwner(const char * file,const char * ownerStr,const char * groupStr)311 static int SetOwner(const char *file, const char *ownerStr, const char *groupStr)
312 {
313 INIT_ERROR_CHECK(file != NULL, return -1, "SetOwner invalid file.");
314 INIT_ERROR_CHECK(ownerStr != NULL, return -1, "SetOwner invalid file.");
315 INIT_ERROR_CHECK(groupStr != NULL, return -1, "SetOwner invalid file.");
316
317 uid_t owner = DecodeUid(ownerStr);
318 INIT_ERROR_CHECK(owner != (uid_t)-1, return -1, "SetOwner invalid uid : %s.", ownerStr);
319 gid_t group = DecodeGid(groupStr);
320 INIT_ERROR_CHECK(group != (gid_t)-1, return -1, "SetOwner invalid gid : %s.", groupStr);
321 return (chown(file, owner, group) != 0) ? -1 : 0;
322 }
323
DoChown(const struct CmdArgs * ctx)324 static void DoChown(const struct CmdArgs *ctx)
325 {
326 // format: chown owner group /xxx/xxx/xxx
327 const int pathPos = 2;
328 int ret = SetOwner(ctx->argv[pathPos], ctx->argv[0], ctx->argv[1]);
329 if (ret != 0) {
330 INIT_LOGE("Failed to change owner for %s, err %d.", ctx->argv[pathPos], errno);
331 }
332 return;
333 }
334
DoMkDir(const struct CmdArgs * ctx)335 static void DoMkDir(const struct CmdArgs *ctx)
336 {
337 // mkdir support format:
338 // 1.mkdir path
339 // 2.mkdir path mode
340 // 3.mkdir path mode owner group
341 const int ownerPos = 2;
342 const int groupPos = 3;
343 if (ctx->argc != 1 && ctx->argc != (groupPos + 1) && ctx->argc != ownerPos) {
344 INIT_LOGE("DoMkDir invalid arguments.");
345 return;
346 }
347 mode_t mode = DEFAULT_DIR_MODE;
348 if (mkdir(ctx->argv[0], mode) != 0 && errno != EEXIST) {
349 INIT_LOGE("Create directory '%s' failed, err=%d.", ctx->argv[0], errno);
350 return;
351 }
352
353 /*
354 * Skip restoring default SELinux security contexts if the the folder already
355 * existed and its under /dev. These files will be proceed by loadSelinuxPolicy.
356 */
357 if (errno != EEXIST || strncmp(ctx->argv[0], "/dev", strlen("/dev")) != 0) {
358 PluginExecCmdByName("restoreContentRecurse", ctx->argv[0]);
359 }
360
361 if (ctx->argc <= 1) {
362 return;
363 }
364
365 mode = strtoul(ctx->argv[1], NULL, OCTAL_TYPE);
366 INIT_CHECK_ONLY_ELOG(chmod(ctx->argv[0], mode) == 0, "DoMkDir failed for '%s', err %d.", ctx->argv[0], errno);
367
368 if (ctx->argc <= ownerPos) {
369 return;
370 }
371 int ret = SetOwner(ctx->argv[0], ctx->argv[ownerPos], ctx->argv[groupPos]);
372 if (ret != 0) {
373 INIT_LOGE("Failed to change owner %s, err %d.", ctx->argv[0], errno);
374 }
375 ret = SetFileCryptPolicy(ctx->argv[0]);
376 INIT_CHECK_ONLY_ELOG(ret == 0, "Failed to set file fscrypt");
377 return;
378 }
379
DoChmod(const struct CmdArgs * ctx)380 static void DoChmod(const struct CmdArgs *ctx)
381 {
382 // format: chmod xxxx /xxx/xxx/xxx
383 mode_t mode = strtoul(ctx->argv[0], NULL, OCTAL_TYPE);
384 if (mode == 0) {
385 INIT_LOGE("DoChmod, strtoul failed for %s, er %d.", ctx->argv[1], errno);
386 return;
387 }
388
389 if (chmod(ctx->argv[1], mode) != 0) {
390 INIT_LOGE("Failed to change mode \" %s \" to %04o, err=%d", ctx->argv[1], mode, errno);
391 }
392 }
393
GetMountFlag(unsigned long * mountflag,const char * targetStr,const char * source)394 static int GetMountFlag(unsigned long *mountflag, const char *targetStr, const char *source)
395 {
396 INIT_CHECK_RETURN_VALUE(targetStr != NULL && mountflag != NULL, 0);
397 struct {
398 char *flagName;
399 unsigned long value;
400 } mountFlagMap[] = {
401 { "noatime", MS_NOATIME },
402 { "noexec", MS_NOEXEC },
403 { "nosuid", MS_NOSUID },
404 { "nodev", MS_NODEV },
405 { "nodiratime", MS_NODIRATIME },
406 { "ro", MS_RDONLY },
407 { "rdonly", MS_RDONLY },
408 { "rw", 0 },
409 { "sync", MS_SYNCHRONOUS },
410 { "remount", MS_REMOUNT },
411 { "bind", MS_BIND },
412 { "rec", MS_REC },
413 { "unbindable", MS_UNBINDABLE },
414 { "private", MS_PRIVATE },
415 { "slave", MS_SLAVE },
416 { "shared", MS_SHARED },
417 { "defaults", 0 },
418 };
419 for (unsigned int i = 0; i < ARRAY_LENGTH(mountFlagMap); i++) {
420 if (strncmp(targetStr, mountFlagMap[i].flagName, strlen(mountFlagMap[i].flagName)) == 0) {
421 *mountflag |= mountFlagMap[i].value;
422 return 1;
423 }
424 }
425 if (strncmp(targetStr, "wait", strlen("wait")) == 0) {
426 WaitForFile(source, WAIT_MAX_SECOND);
427 return 1;
428 }
429
430 return 0;
431 }
432
DoMount(const struct CmdArgs * ctx)433 static void DoMount(const struct CmdArgs *ctx)
434 {
435 INIT_ERROR_CHECK(ctx->argc <= SPACES_CNT_IN_CMD_MAX, return, "Invalid arg number");
436 // format: fileSystemType source target mountFlag1 mountFlag2... data
437 int index = 0;
438 char *fileSysType = (ctx->argc > index) ? ctx->argv[index] : NULL;
439 INIT_ERROR_CHECK(fileSysType != NULL, return, "Failed to get fileSysType.");
440 index++;
441
442 char *source = (ctx->argc > index) ? ctx->argv[index] : NULL;
443 INIT_ERROR_CHECK(source != NULL, return, "Failed to get source.");
444 index++;
445
446 // maybe only has "filesystype source target", 2 spaces
447 char *target = (ctx->argc > index) ? ctx->argv[index] : NULL;
448 INIT_ERROR_CHECK(target != NULL, return, "Failed to get target.");
449 ++index;
450
451 int ret = 0;
452 unsigned long mountflags = 0;
453 while (index < ctx->argc) {
454 ret = GetMountFlag(&mountflags, ctx->argv[index], source);
455 if (ret == 0) {
456 break;
457 }
458 index++;
459 }
460 if (index >= ctx->argc) {
461 ret = mount(source, target, fileSysType, mountflags, NULL);
462 } else {
463 char *data = BuildStringFromCmdArg(ctx, index);
464 INIT_ERROR_CHECK(data != NULL, return, "Failed to get data.");
465 ret = mount(source, target, fileSysType, mountflags, data);
466 free(data);
467 }
468 if (ret != 0) {
469 INIT_LOGE("Failed to mount for %s, err %d.", target, errno);
470 }
471 }
472
DoWriteWithMultiArgs(const struct CmdArgs * ctx,int fd)473 static int DoWriteWithMultiArgs(const struct CmdArgs *ctx, int fd)
474 {
475 char buf[MAX_CMD_CONTENT_LEN];
476
477 /* Write to proc files should be done at once */
478 buf[0] = '\0';
479 INIT_ERROR_CHECK(strcat_s(buf, sizeof(buf), ctx->argv[1]) == 0, return -1, "Failed to format buf");
480 int idx = 2;
481 while (idx < ctx->argc) {
482 INIT_ERROR_CHECK(strcat_s(buf, sizeof(buf), " ") == 0, return -1, "Failed to format buf");
483 INIT_ERROR_CHECK(strcat_s(buf, sizeof(buf), ctx->argv[idx]) == 0, return -1, "Failed to format buf");
484 idx++;
485 }
486 return write(fd, buf, strlen(buf));
487 }
488
DoWrite(const struct CmdArgs * ctx)489 static void DoWrite(const struct CmdArgs *ctx)
490 {
491 // format: write path content
492 char *realPath = GetRealPath(ctx->argv[0]);
493 int fd = -1;
494 if (realPath != NULL) {
495 fd = open(realPath, O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC, S_IRUSR | S_IWUSR);
496 free(realPath);
497 realPath = NULL;
498 } else {
499 fd = open(ctx->argv[0], O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC, S_IRUSR | S_IWUSR);
500 }
501 if (fd < 0) {
502 return;
503 }
504 ssize_t ret;
505 if (ctx->argc > 2) {
506 ret = DoWriteWithMultiArgs(ctx, fd);
507 } else {
508 ret = write(fd, ctx->argv[1], strlen(ctx->argv[1]));
509 }
510 INIT_CHECK_ONLY_ELOG(ret >= 0, "DoWrite: write to file %s failed: %d", ctx->argv[0], errno);
511 close(fd);
512 }
513
DoRmdir(const struct CmdArgs * ctx)514 static void DoRmdir(const struct CmdArgs *ctx)
515 {
516 // format: rmdir path
517 int ret = rmdir(ctx->argv[0]);
518 if (ret == -1) {
519 INIT_LOGE("DoRmdir: remove %s failed: %d.", ctx->argv[0], errno);
520 }
521 return;
522 }
523
DoRebootCmd(const struct CmdArgs * ctx)524 static void DoRebootCmd(const struct CmdArgs *ctx)
525 {
526 ExecReboot(ctx->argv[0]);
527 return;
528 }
529
DoSetrlimit(const struct CmdArgs * ctx)530 static void DoSetrlimit(const struct CmdArgs *ctx)
531 {
532 static const char *resource[] = {
533 "RLIMIT_CPU", "RLIMIT_FSIZE", "RLIMIT_DATA", "RLIMIT_STACK", "RLIMIT_CORE", "RLIMIT_RSS",
534 "RLIMIT_NPROC", "RLIMIT_NOFILE", "RLIMIT_MEMLOCK", "RLIMIT_AS", "RLIMIT_LOCKS", "RLIMIT_SIGPENDING",
535 "RLIMIT_MSGQUEUE", "RLIMIT_NICE", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", "RLIM_NLIMITS"
536 };
537 // format: setrlimit resource curValue maxValue
538 const int rlimMaxPos = 2;
539 struct rlimit limit;
540 if (strcmp(ctx->argv[1], "unlimited") == 0) {
541 limit.rlim_cur = RLIM_INFINITY;
542 } else {
543 limit.rlim_cur = (rlim_t)atoi(ctx->argv[1]);
544 }
545 if (strcmp(ctx->argv[rlimMaxPos], "unlimited") == 0) {
546 limit.rlim_max = RLIM_INFINITY;
547 } else {
548 limit.rlim_max = (rlim_t)atoi(ctx->argv[rlimMaxPos]);
549 }
550 int rcs = -1;
551 for (unsigned int i = 0; i < ARRAY_LENGTH(resource); ++i) {
552 if (strcmp(ctx->argv[0], resource[i]) == 0) {
553 rcs = (int)i;
554 break;
555 }
556 }
557 if (rcs == -1) {
558 INIT_LOGE("DoSetrlimit failed, resources :%s not support.", ctx->argv[0]);
559 return;
560 }
561 INIT_CHECK_ONLY_ELOG(setrlimit(rcs, &limit) == 0, "Failed setrlimit err=%d", errno);
562 return;
563 }
564
DoRm(const struct CmdArgs * ctx)565 static void DoRm(const struct CmdArgs *ctx)
566 {
567 // format: rm /xxx/xxx/xxx
568 INIT_CHECK_ONLY_ELOG(unlink(ctx->argv[0]) != -1, "Failed unlink %s err=%d.", ctx->argv[0], errno);
569 return;
570 }
571
DoExport(const struct CmdArgs * ctx)572 static void DoExport(const struct CmdArgs *ctx)
573 {
574 // format: export xxx /xxx/xxx/xxx
575 INIT_CHECK_ONLY_ELOG(setenv(ctx->argv[0], ctx->argv[1], 1) == 0, "Failed setenv %s with %s err=%d.",
576 ctx->argv[0], ctx->argv[1], errno);
577 return;
578 }
579
580 static const struct CmdTable g_cmdTable[] = {
581 { "start ", 0, 1, 0, DoStart },
582 { "mkdir ", 1, 4, 1, DoMkDir },
583 { "chmod ", 2, 2, 1, DoChmod },
584 { "chown ", 3, 3, 1, DoChown },
585 { "mount ", 1, 10, 0, DoMount },
586 { "export ", 2, 2, 0, DoExport },
587 { "rm ", 1, 1, 1, DoRm },
588 { "rmdir ", 1, 1, 1, DoRmdir },
589 { "write ", 2, 10, 1, DoWrite },
590 { "stop ", 1, 1, 0, DoStop },
591 { "reset ", 1, 1, 0, DoReset },
592 { "copy ", 2, 2, 1, DoCopy },
593 { "reboot ", 0, 1, 0, DoRebootCmd },
594 { "setrlimit ", 3, 3, 0, DoSetrlimit },
595 { "sleep ", 1, 1, 0, DoSleep },
596 { "wait ", 1, 2, 1, DoWait },
597 { "hostname ", 1, 1, 1, DoSetHostname },
598 { "domainname ", 1, 1, 1, DoSetDomainname }
599 };
600
GetCommCmdTable(int * number)601 static const struct CmdTable *GetCommCmdTable(int *number)
602 {
603 *number = (int)ARRAY_LENGTH(g_cmdTable);
604 return g_cmdTable;
605 }
606
GetCmdStart(const char * cmdContent)607 static char *GetCmdStart(const char *cmdContent)
608 {
609 // Skip lead whitespaces
610 char *p = (char *)cmdContent;
611 while (p != NULL && isspace(*p)) {
612 p++;
613 }
614 if (p == NULL) {
615 return NULL;
616 }
617 if (*p == '#') { // start with #
618 return NULL;
619 }
620 return p;
621 }
622
GetCmdByName(const char * name)623 const struct CmdTable *GetCmdByName(const char *name)
624 {
625 INIT_CHECK_RETURN_VALUE(name != NULL, NULL);
626 char *startCmd = GetCmdStart(name);
627 INIT_CHECK_RETURN_VALUE(startCmd != NULL, NULL);
628 int cmdCnt = 0;
629 const struct CmdTable *commCmds = GetCommCmdTable(&cmdCnt);
630 for (int i = 0; i < cmdCnt; ++i) {
631 if (strncmp(startCmd, commCmds[i].name, strlen(commCmds[i].name)) == 0) {
632 return &commCmds[i];
633 }
634 }
635 int number = 0;
636 const struct CmdTable *cmds = GetCmdTable(&number);
637 for (int i = 0; i < number; ++i) {
638 if (strncmp(startCmd, cmds[i].name, strlen(cmds[i].name)) == 0) {
639 return &cmds[i];
640 }
641 }
642 return NULL;
643 }
644
GetMatchCmd(const char * cmdStr,int * index)645 const char *GetMatchCmd(const char *cmdStr, int *index)
646 {
647 INIT_CHECK_RETURN_VALUE(cmdStr != NULL && index != NULL, NULL);
648 char *startCmd = GetCmdStart(cmdStr);
649 INIT_CHECK_RETURN_VALUE(startCmd != NULL, NULL);
650
651 int cmdCnt = 0;
652 const struct CmdTable *commCmds = GetCommCmdTable(&cmdCnt);
653 for (int i = 0; i < cmdCnt; ++i) {
654 if (strncmp(startCmd, commCmds[i].name, strlen(commCmds[i].name)) == 0) {
655 *index = i;
656 return commCmds[i].name;
657 }
658 }
659 int number = 0;
660 const struct CmdTable *cmds = GetCmdTable(&number);
661 for (int i = 0; i < number; ++i) {
662 if (strncmp(startCmd, cmds[i].name, strlen(cmds[i].name)) == 0) {
663 *index = cmdCnt + i;
664 return cmds[i].name;
665 }
666 }
667 return PluginGetCmdIndex(startCmd, index);
668 }
669
GetCmdTableByIndex(int index)670 static const struct CmdTable *GetCmdTableByIndex(int index)
671 {
672 int cmdCnt = 0;
673 const struct CmdTable *commCmds = GetCommCmdTable(&cmdCnt);
674 const struct CmdTable *cmdTable = NULL;
675 if (index < cmdCnt) {
676 cmdTable = &commCmds[index];
677 } else {
678 int number = 0;
679 const struct CmdTable *cmds = GetCmdTable(&number);
680 if (index < (cmdCnt + number)) {
681 cmdTable = &cmds[index - cmdCnt];
682 }
683 }
684 return cmdTable;
685 }
686
GetCmdKey(int index)687 const char *GetCmdKey(int index)
688 {
689 const struct CmdTable *cmdTable = GetCmdTableByIndex(index);
690 if (cmdTable != NULL) {
691 return cmdTable->name;
692 }
693 return GetPluginCmdNameByIndex(index);
694 }
695
GetCmdLinesFromJson(const cJSON * root,CmdLines ** cmdLines)696 int GetCmdLinesFromJson(const cJSON *root, CmdLines **cmdLines)
697 {
698 INIT_CHECK(root != NULL, return -1);
699 INIT_CHECK(cmdLines != NULL, return -1);
700 *cmdLines = NULL;
701 if (!cJSON_IsArray(root)) {
702 return -1;
703 }
704 int cmdCnt = cJSON_GetArraySize(root);
705 INIT_CHECK_RETURN_VALUE(cmdCnt > 0, -1);
706
707 *cmdLines = (CmdLines *)calloc(1, sizeof(CmdLines) + sizeof(CmdLine) * cmdCnt);
708 INIT_CHECK_RETURN_VALUE(*cmdLines != NULL, -1);
709 (*cmdLines)->cmdNum = 0;
710 for (int i = 0; i < cmdCnt; ++i) {
711 cJSON *line = cJSON_GetArrayItem(root, i);
712 if (!cJSON_IsString(line)) {
713 continue;
714 }
715
716 char *tmp = cJSON_GetStringValue(line);
717 if (tmp == NULL) {
718 continue;
719 }
720
721 int index = 0;
722 const char *cmd = GetMatchCmd(tmp, &index);
723 if (cmd == NULL) {
724 INIT_LOGE("Cannot support command: %s", tmp);
725 continue;
726 }
727
728 int ret = strcpy_s((*cmdLines)->cmds[(*cmdLines)->cmdNum].cmdContent, MAX_CMD_CONTENT_LEN, tmp + strlen(cmd));
729 if (ret != EOK) {
730 INIT_LOGE("Invalid cmd arg: %s", tmp);
731 continue;
732 }
733
734 (*cmdLines)->cmds[(*cmdLines)->cmdNum].cmdIndex = index;
735 (*cmdLines)->cmdNum++;
736 }
737 return 0;
738 }
739
DoCmdByIndex(int index,const char * cmdContent,const ConfigContext * context)740 void DoCmdByIndex(int index, const char *cmdContent, const ConfigContext *context)
741 {
742 if (cmdContent == NULL) {
743 return;
744 }
745 INIT_TIMING_STAT cmdTimer;
746 (void)clock_gettime(CLOCK_MONOTONIC, &cmdTimer.startTime);
747
748 const char *cmdName = NULL;
749 const struct CmdTable *cmdTable = GetCmdTableByIndex(index);
750 if (cmdTable != NULL) {
751 cmdName = cmdTable->name;
752 if (!cmdTable->careContext || !CheckExecuteInSubInit(context)) {
753 ExecCmd(cmdTable, cmdContent);
754 } else {
755 ExecuteCmdInSubInit(context, cmdTable->name, cmdContent);
756 }
757 } else {
758 PluginExecCmdByCmdIndex(index, cmdContent, context);
759 cmdName = GetPluginCmdNameByIndex(index);
760 if (cmdName == NULL) {
761 cmdName = "Unknown";
762 }
763 }
764
765 (void)clock_gettime(CLOCK_MONOTONIC, &cmdTimer.endTime);
766 long long diff = InitDiffTime(&cmdTimer);
767 #ifndef OHOS_LITE
768 InitCmdHookExecute(cmdName, cmdContent, &cmdTimer);
769 #endif
770 if (diff > 200000) { // 200000 > 200ms
771 INIT_LOGI("Execute command \"%s %s\" took %lld ms", cmdName, cmdContent, diff / BASE_MS_UNIT);
772 } else {
773 INIT_LOGV("Execute command \"%s %s\" took %lld ms", cmdName, cmdContent, diff / BASE_MS_UNIT);
774 }
775 }
776