提交 17d558ae 编写于 作者: X xionglei6

init: add func

Signed-off-by: Nxionglei6 <xionglei6@huawei.com>
上级 abb195cc
......@@ -13,4 +13,5 @@
declare_args() {
param_feature_watcher = true
param_test = false
}
......@@ -24,6 +24,7 @@ shared_library("libinitsync_shared") {
"//base/startup/init_lite/initsync/include",
"//base/startup/init_lite/interfaces/kits",
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/interfaces/innerkits/include",
]
public_deps = [
"//base/startup/init_lite/services/log:init_log",
......@@ -38,6 +39,7 @@ static_library("libinitsync_static") {
"//base/startup/init_lite/initsync/include",
"//base/startup/init_lite/interfaces/kits",
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/interfaces/innerkits/include",
]
public_deps = [ "//third_party/bounds_checking_function:libsec_static" ]
}
......@@ -20,13 +20,13 @@ config("exported_header_files") {
}
fs_manager_sources = [
"fs_manager/fs_manager_log.c",
"fs_manager/fstab.c",
"fs_manager/fstab_mount.c",
]
ohos_shared_library("libbegetutil") {
sources = [
"fd_holder/fd_holder.c",
"file/init_file.c",
"reboot/init_reboot_innerkits.c",
"service_control/service_control.c",
......@@ -36,19 +36,23 @@ ohos_shared_library("libbegetutil") {
include_dirs = [
"./include",
"//base/startup/init_lite/services/log",
"//third_party/bounds_checking_function/include",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/include/param",
"//base/startup/init_lite/interfaces/innerkits/fd_holder",
]
defines = [ "INIT_AGENT" ]
deps = [
"//base/startup/init_lite/services/log:init_log",
"//base/startup/init_lite/interfaces/innerkits/fd_holder:libfdholder_internal_static",
"//base/startup/init_lite/services/param:param_client",
"//base/startup/init_lite/services/utils:libinit_utils",
"//third_party/bounds_checking_function:libsec_shared",
"//third_party/openssl:libcrypto_static",
"//utils/native/base:utils",
]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
deps += [ "//base/startup/init_lite/services/log:init_log" ]
public_configs = [ ":exported_header_files" ]
part_name = "init"
install_images = [
......@@ -62,6 +66,7 @@ ohos_shared_library("libservice_watcher") {
sources = [ "service_watcher/service_watcher.c" ]
include_dirs = [
"./include",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/include/param",
"//third_party/bounds_checking_function/include",
......@@ -72,8 +77,9 @@ ohos_shared_library("libservice_watcher") {
"//base/startup/init_lite/services/utils:libinit_utils",
"//third_party/bounds_checking_function:libsec_shared",
]
public_configs = [ ":exported_header_files" ]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
deps += [ "//base/startup/init_lite/services/log:init_log" ]
part_name = "init"
install_images = [
"system",
......@@ -88,7 +94,9 @@ ohos_static_library("libfsmanager_static") {
"//base/startup/init_lite/interfaces/innerkits/include",
"//third_party/bounds_checking_function/include",
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/services/include",
]
deps = [ "//base/startup/init_lite/services/log:init_log" ]
part_name = "init"
}
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
ohos_static_library("libfdholder_internal_static") {
sources = [ "fd_holder_internal.c" ]
include_dirs = [
".",
"//third_party/bounds_checking_function/include",
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/interfaces/innerkits/include",
]
deps = [ "//base/startup/init_lite/services/log:init_log" ]
defines = [ "INIT_AGENT" ]
part_name = "init"
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "fd_holder.h"
#include <stdio.h>
#include <errno.h>
#include "beget_ext.h"
#include "fd_holder_internal.h"
#include "init_utils.h"
#include "securec.h"
static int BuildClientSocket(void)
{
int sockFd;
sockFd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0);
if (sockFd < 0) {
BEGET_LOGE("Failed to build socket, err = %d", errno);
return -1;
}
struct sockaddr_un addr;
(void)memset_s(&addr, sizeof(addr), 0, sizeof(addr));
addr.sun_family = AF_UNIX;
if (strncpy_s(addr.sun_path, sizeof(addr.sun_path), INIT_HOLDER_SOCKET_PATH,
strlen(INIT_HOLDER_SOCKET_PATH)) != 0) {
BEGET_LOGE("Failed to build socket path");
close(sockFd);
return -1;
}
socklen_t len = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + strlen(addr.sun_path) + 1);
if (connect(sockFd, (struct sockaddr *)&addr, len) < 0) {
BEGET_LOGE("Failed to connect to socket, err = %d", errno);
close(sockFd);
return -1;
}
return sockFd;
}
static int BuildSendData(char *buffer, size_t size, const char *serviceName, bool hold, bool poll)
{
if (buffer == NULL || size == 0 || serviceName == 0) {
return -1;
}
if (!hold && poll) {
BEGET_LOGE("Get fd with poll set, invalid parameter");
return -1;
}
char *holdString = ACTION_HOLD;
if (!hold) {
holdString = ACTION_GET;
}
char *pollString = WITHPOLL;
if (!poll) {
pollString = WITHOUTPOLL;
}
if (snprintf_s(buffer, size, size - 1, "%s|%s|%s", serviceName, holdString, pollString) == -1) {
BEGET_LOGE("Failed to build send data");
return -1;
}
return 0;
}
static int ServiceSendFds(const char *serviceName, int *fds, int fdCount, bool doPoll)
{
int sock = BuildClientSocket();
if (sock < 0) {
return -1;
}
struct iovec iovec = {};
struct msghdr msghdr = {
.msg_iov = &iovec,
.msg_iovlen = 1,
};
char sendBuffer[MAX_FD_HOLDER_BUFFER] = {};
if (BuildSendData(sendBuffer, sizeof(sendBuffer), serviceName, true, doPoll) < 0) {
BEGET_LOGE("Failed to build send data");
close(sock);
return -1;
}
BEGET_LOGV("Send data: [%s]", sendBuffer);
iovec.iov_base = sendBuffer;
iovec.iov_len = strlen(sendBuffer);
if (BuildControlMessage(&msghdr, fds, fdCount, true) < 0) {
BEGET_LOGE("Failed to build control message");
if (msghdr.msg_control != NULL) {
free(msghdr.msg_control);
}
msghdr.msg_controllen = 0;
close(sock);
return -1;
}
if (TEMP_FAILURE_RETRY(sendmsg(sock, &msghdr, MSG_NOSIGNAL)) < 0) {
BEGET_LOGE("Failed to send fds to init, err = %d", errno);
if (msghdr.msg_control != NULL) {
free(msghdr.msg_control);
}
msghdr.msg_controllen = 0;
close(sock);
return -1;
}
if (msghdr.msg_control != NULL) {
free(msghdr.msg_control);
}
msghdr.msg_controllen = 0;
BEGET_LOGI("Send fds done");
close(sock);
return 0;
}
int ServiceSaveFd(const char *serviceName, int *fds, int fdCount)
{
// Sanity checks
if (serviceName == NULL || fds == NULL ||
fdCount < 0 || fdCount > MAX_HOLD_FDS) {
BEGET_LOGE("Invalid parameters");
return -1;
}
return ServiceSendFds(serviceName, fds, fdCount, false);
}
int ServiceSaveFdWithPoll(const char *serviceName, int *fds, int fdCount)
{
// Sanity checks
if (serviceName == NULL || fds == NULL ||
fdCount < 0 || fdCount > MAX_HOLD_FDS) {
BEGET_LOGE("Invalid parameters");
return -1;
}
return ServiceSendFds(serviceName, fds, fdCount, true);
}
int *ServiceGetFd(const char *serviceName, size_t *outfdCount)
{
if (serviceName == NULL || outfdCount == NULL) {
BEGET_LOGE("Invalid parameters");
return NULL;
}
char path[MAX_FD_HOLDER_BUFFER] = {};
int ret = snprintf_s(path, MAX_FD_HOLDER_BUFFER, MAX_FD_HOLDER_BUFFER - 1, ENV_FD_HOLD_PREFIX"%s", serviceName);
BEGET_ERROR_CHECK(ret > 0, return NULL, "Failed snprintf_s err=%d", errno);
const char *value = getenv(path);
if (value == NULL) {
BEGET_LOGE("Cannot get env %s\n", path);
return NULL;
}
char fdBuffer[MAX_FD_HOLDER_BUFFER] = {};
ret = strncpy_s(fdBuffer, MAX_FD_HOLDER_BUFFER - 1, value, strlen(value));
BEGET_ERROR_CHECK(ret == 0, return NULL, "Failed strncpy_s err=%d", errno);
BEGET_LOGV("fds = %s", fdBuffer);
int fdCount = 0;
char **fdList = SplitStringExt(fdBuffer, " ", &fdCount, MAX_HOLD_FDS);
if (fdList == NULL) {
BEGET_LOGE("Cannot get fd list");
return NULL;
}
int *fds = calloc((size_t)fdCount, sizeof(int));
if (fds == NULL) {
BEGET_LOGE("Allocate memory for fd failed. err = %d", errno);
FreeStringVector(fdList, fdCount);
*outfdCount = 0;
return NULL;
}
bool encounterError = false;
for (int i = 0; i < fdCount; i++) {
errno = 0;
fds[i] = (int)strtol(fdList[i], NULL, DECIMAL_BASE);
if (errno != 0) {
BEGET_LOGE("Failed to convert \' %s \' to fd number", fdList[i]);
encounterError = true;
break;
}
}
if (encounterError) {
free(fds);
fds = NULL;
fdCount = 0;
}
*outfdCount = fdCount;
FreeStringVector(fdList, fdCount);
return fds;
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "fd_holder_internal.h"
#include <errno.h>
#include <stdio.h>
#include "beget_ext.h"
#include "securec.h"
#ifndef PAGE_SIZE
#define PAGE_SIZE (4096U)
#endif
int BuildControlMessage(struct msghdr *msghdr, int *fds, int fdCount, bool sendUcred)
{
if (msghdr == NULL || (fdCount > 0 && fds == NULL)) {
BEGET_LOGE("Build control message with invalid parameter");
return -1;
}
if (fdCount > 0) {
msghdr->msg_controllen = CMSG_SPACE(sizeof(int) * fdCount);
} else {
msghdr->msg_controllen = 0;
}
if (sendUcred) {
msghdr->msg_controllen += CMSG_SPACE(sizeof(struct ucred));
}
msghdr->msg_control = calloc(1, (msghdr->msg_controllen == 0 ? 1 : msghdr->msg_controllen));
if (msghdr->msg_control == NULL) {
BEGET_LOGE("Failed to build control message");
return -1;
}
struct cmsghdr *cmsg = NULL;
cmsg = CMSG_FIRSTHDR(msghdr);
if (fdCount > 0) {
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int) * fdCount);
int ret = memcpy_s(CMSG_DATA(cmsg), cmsg->cmsg_len, fds, sizeof(int) * fdCount);
if (ret != 0) {
BEGET_LOGE("Controll message is not valid");
free(msghdr->msg_control);
return -1;
}
// build ucred info
cmsg = CMSG_NXTHDR(msghdr, cmsg);
}
if (sendUcred) {
if (cmsg == NULL) {
BEGET_LOGE("Controll message is not valid");
free(msghdr->msg_control);
return -1;
}
struct ucred *ucred;
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_CREDENTIALS;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
ucred = (struct ucred*) CMSG_DATA(cmsg);
ucred->pid = getpid();
ucred->uid = getuid();
ucred->gid = getgid();
}
return 0;
}
// This function will allocate memory to store FDs
// Remember to delete when not used anymore.
int *ReceiveFds(int sock, struct iovec iovec, size_t *outFdCount, bool nonblock, pid_t *requestPid)
{
CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) +
CMSG_SPACE(sizeof(int) * MAX_HOLD_FDS)) control;
BEGET_ERROR_CHECK(sizeof(control) <= PAGE_SIZE, return NULL, "Too many fds, out of memory");
struct msghdr msghdr = {
.msg_iov = &iovec,
.msg_iovlen = 1,
.msg_control = &control,
.msg_controllen = sizeof(control),
.msg_flags = 0,
};
int flags = MSG_CMSG_CLOEXEC | MSG_TRUNC;
if (nonblock) {
flags |= MSG_DONTWAIT;
}
ssize_t rc = TEMP_FAILURE_RETRY(recvmsg(sock, &msghdr, flags));
BEGET_ERROR_CHECK(rc >= 0, return NULL, "Failed to get fds from remote, err = %d", errno);
if ((msghdr.msg_flags) & MSG_TRUNC) {
BEGET_LOGE("Message was trucated when receiving fds");
return NULL;
}
struct cmsghdr *cmsg = NULL;
int *fds = NULL;
size_t fdCount = 0;
for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
fds = (int*) CMSG_DATA(cmsg);
fdCount = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
BEGET_ERROR_CHECK(fdCount <= MAX_HOLD_FDS, return NULL, "Too many fds returned.");
}
if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS &&
cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
// Ignore credentials
if (requestPid != NULL) {
struct ucred *ucred = (struct ucred*)CMSG_DATA(cmsg);
*requestPid = ucred->pid;
}
continue;
}
}
int *outFds = NULL;
if (fds != NULL && fdCount > 0) {
outFds = calloc(fdCount + 1, sizeof(int));
BEGET_ERROR_CHECK(outFds != NULL, return NULL, "Failed to allocate memory for fds");
BEGET_ERROR_CHECK(memcpy_s(outFds, sizeof(int) * (fdCount + 1), fds, sizeof(int) * fdCount) == 0,
free(outFds); return NULL, "Failed to copy fds");
}
*outFdCount = fdCount;
return outFds;
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BASE_STARTUP_INITLITE_FD_HOLDER_INTERNAL_H
#define BASE_STARTUP_INITLITE_FD_HOLDER_INTERNAL_H
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/socket.h>
#ifdef __cplusplus
extern "C" {
#endif
#define INIT_HOLDER_SOCKET_PATH "/dev/unix/socket/fd_holder"
#define MAX_HOLD_FDS (64)
#define MAX_FD_HOLDER_BUFFER (MAX_HOLD_FDS * sizeof(int))
#define ENV_FD_HOLD_PREFIX "OHOS_FD_HOLD_"
// actions
#define ACTION_HOLD "hold"
#define ACTION_GET "get"
// poll or not
#define WITHPOLL "poll"
#define WITHOUTPOLL "withoutpoll"
int BuildControlMessage(struct msghdr *msghdr, int *fds, int fdCount, bool sendUcred);
// This function will allocate memory to store FDs
// Remember to delete when not used anymore.
int *ReceiveFds(int sock, struct iovec iovec, size_t *outFdCount, bool nonblock, pid_t *requestPid);
#define CMSG_BUFFER_TYPE(size) \
union { \
struct cmsghdr cmsghdr; \
uint8_t buf[size]; \
uint8_t align_check[(size) >= CMSG_SPACE(0) && \
(size) == CMSG_ALIGN(size) ? 1 : -1]; \
}
#ifdef __cplusplus
}
#endif
#endif // BASE_STARTUP_INITLITE_FD_HOLDER_INTERNAL_H
......@@ -22,7 +22,7 @@
#include <sys/types.h>
#include <unistd.h>
#include "init_log.h"
#include "beget_ext.h"
#include "init_utils.h"
#include "securec.h"
......@@ -34,17 +34,17 @@ int GetControlFile(const char *pathName)
return -1;
}
char path[PATH_MAX] = { 0 };
INIT_ERROR_CHECK(snprintf_s(path, sizeof(path), sizeof(path) - 1, OHOS_FILE_ENV_PREFIX "%s", pathName) >= 0,
BEGET_ERROR_CHECK(snprintf_s(path, sizeof(path), sizeof(path) - 1, OHOS_FILE_ENV_PREFIX "%s", pathName) >= 0,
return -1, "Failed snprintf_s err=%d", errno);
INIT_ERROR_CHECK(StringReplaceChr(path, '/', '_') == 0,
BEGET_ERROR_CHECK(StringReplaceChr(path, '/', '_') == 0,
return -1, "Failed string replace char");
INIT_LOGI("Environment path is %s ", path);
BEGET_LOGI("Environment path is %s ", path);
const char *val = getenv(path);
INIT_ERROR_CHECK(val != NULL, return -1, "Failed getenv err=%d", errno);
BEGET_ERROR_CHECK(val != NULL, return -1, "Failed getenv err=%d", errno);
errno = 0;
int fd = strtol(val, NULL, N_DEC);
INIT_ERROR_CHECK(errno == 0, return -1, "Failed strtol val");
INIT_LOGI("Get environment fd is %d ", fd);
INIT_ERROR_CHECK(fcntl(fd, F_GETFD) >= 0, return -1, "Failed fcntl fd err=%d ", errno);
BEGET_ERROR_CHECK(errno == 0, return -1, "Failed strtol val");
BEGET_LOGI("Get environment fd is %d ", fd);
BEGET_ERROR_CHECK(fcntl(fd, F_GETFD) >= 0, return -1, "Failed fcntl fd err=%d ", errno);
return fd;
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "fs_manager/fs_manager_log.h"
#include "init_log.h"
#include "init_utils.h"
#include "securec.h"
#define LOG_BUFFER_MAX (1024)
static FILE *g_logFile = NULL;
static FsMgrLogLevel g_defaultLogLevel = FSMGR_DEBUG;
FsManagerLogFunc g_logFunc = FsManagerLogToStd;
static InitLogLevel ConvertToInitLog(FsMgrLogLevel level)
{
switch (level) {
case FSMGR_VERBOSE: // fall through
case FSMGR_DEBUG:
return INIT_DEBUG;
case FSMGR_INFO:
return INIT_INFO;
case FSMGR_WARNING:
return INIT_WARN;
case FSMGR_ERROR:
return INIT_ERROR;
case FSMGR_FATAL:
return INIT_FATAL;
// Unexpected log level, set it as lowest
default:
return INIT_DEBUG;
}
}
static const char *ConvertToKernelLog(FsMgrLogLevel level)
{
switch (level) {
case FSMGR_VERBOSE: // fall through
case FSMGR_DEBUG:
return "<7>";
case FSMGR_INFO:
return "<6>";
case FSMGR_WARNING:
return "<4>";
case FSMGR_ERROR:
case FSMGR_FATAL:
return "<3>";
// Unexpected log level, set level as lowest
default:
return "<7>";
}
}
// Wrap init log
static void FsManagerLogToKernel(FsMgrLogLevel level, const char *fileName, int line, const char *fmt, ...)
{
va_list vargs;
va_start(vargs, fmt);
char tmpFmt[LOG_BUFFER_MAX];
if (vsnprintf_s(tmpFmt, LOG_BUFFER_MAX, LOG_BUFFER_MAX - 1, fmt, vargs) == -1) {
return;
}
char logInfo[LOG_BUFFER_MAX];
if (snprintf_s(logInfo, LOG_BUFFER_MAX, LOG_BUFFER_MAX - 1, "[%s:%d]%s", fileName, line, tmpFmt) == -1) {
return;
}
InitLog(fileName, ConvertToInitLog(level), ConvertToKernelLog(level), logInfo);
va_end(vargs);
return;
}
static void WriteLogToFile(FILE *fp, const char *fileName, int line, const char *fmt, ...)
{
// Sanity checks
INIT_CHECK_ONLY_RETURN(fp != NULL && fmt != NULL);
va_list vargs;
va_start(vargs, fmt);
va_end(vargs);
char fullLogMsg[LOG_BUFFER_MAX];
if (snprintf_s(fullLogMsg, LOG_BUFFER_MAX, LOG_BUFFER_MAX - 1, "[%s:%d][%s] %s",
(fileName == NULL) ? "" : fileName, line, "fs_manager", fmt) == -1) {
return;
}
(void)fprintf(fp, "%s", fullLogMsg);
return;
}
void FsManagerLogToStd(FsMgrLogLevel level, const char *fileName, int line, const char *fmt, ...)
{
if (level < g_defaultLogLevel) {
return;
}
FILE *fp = NULL;
if (level >= FSMGR_ERROR) {
fp = stderr;
} else {
fp = stdout;
}
va_list vargs;
va_start(vargs, fmt);
char tmpFmt[LOG_BUFFER_MAX];
if (vsnprintf_s(tmpFmt, LOG_BUFFER_MAX, LOG_BUFFER_MAX - 1, fmt, vargs) == -1) {
return;
}
WriteLogToFile(fp, fileName, line, tmpFmt, vargs);
va_end(vargs);
return;
}
static void FsManagerLogToFile(FsMgrLogLevel level, const char *fileName, int line, const char *fmt, ...)
{
if (level < g_defaultLogLevel) {
return;
}
va_list vargs;
va_start(vargs, fmt);
// If @g_logFile is NULL, output the log to standard I/O.
if (g_logFile == NULL) {
FsManagerLogToStd(level, fileName, line, fmt, vargs);
} else {
char tmpFmt[LOG_BUFFER_MAX];
if (vsnprintf_s(tmpFmt, LOG_BUFFER_MAX, LOG_BUFFER_MAX - 1, fmt, vargs) == -1) {
return;
}
WriteLogToFile(g_logFile, fileName, line, tmpFmt, vargs);
}
va_end(vargs);
return;
}
void FsManagerLogInit(LogTarget target, const char *fileName)
{
setbuf(stderr, NULL);
setbuf(stdout, NULL);
switch (target) {
case LOG_TO_KERNEL:
g_logFunc = FsManagerLogToKernel;
break;
case LOG_TO_FILE:
if (fileName != NULL && *fileName != '\0') {
char *realPath = GetRealPath(fileName);
if (realPath != NULL) {
g_logFile = fopen(realPath, "a+");
setbuf(g_logFile, NULL);
free(realPath);
}
// Do not check return values. The log writte function will do this.
}
g_logFunc = FsManagerLogToFile;
break;
case LOG_TO_STDIO:
g_logFunc = FsManagerLogToStd;
break;
default:
// Output log to standard I/O by default
g_logFunc = FsManagerLogToStd;
break;
}
return;
}
void FsManagerLogDeInit(void)
{
if (g_logFile != NULL) {
fclose(g_logFile);
g_logFile = NULL;
}
return;
}
......@@ -24,9 +24,8 @@
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "beget_ext.h"
#include "fs_manager/fs_manager.h"
#include "fs_manager/fs_manager_log.h"
#include "init_log.h"
#include "init_utils.h"
#include "securec.h"
......@@ -54,12 +53,12 @@ unsigned int ConvertFlags(char *flagBuffer)
{"required", FS_MANAGER_REQUIRED},
};
INIT_CHECK_RETURN_VALUE(flagBuffer != NULL && *flagBuffer != '\0', 0); // No valid flags.
BEGET_CHECK_RETURN_VALUE(flagBuffer != NULL && *flagBuffer != '\0', 0); // No valid flags.
int flagCount = 0;
unsigned int flags = 0;
const int maxCount = 3;
char **vector = SplitStringExt(flagBuffer, ",", &flagCount, maxCount);
INIT_CHECK_RETURN_VALUE(vector != NULL && flagCount != 0, 0);
BEGET_CHECK_RETURN_VALUE(vector != NULL && flagCount != 0, 0);
for (size_t i = 0; i < ARRAY_LENGTH(fsFlags); i++) {
for (int j = 0; j < flagCount; j++) {
if (strcmp(fsFlags[i].name, vector[j]) == 0) {
......@@ -127,7 +126,7 @@ void ReleaseFstab(Fstab *fstab)
static int ParseFstabPerLine(char *str, Fstab *fstab, bool procMounts)
{
INIT_CHECK_RETURN_VALUE(str != NULL && fstab != NULL, -1);
BEGET_CHECK_RETURN_VALUE(str != NULL && fstab != NULL, -1);
const char *separator = " \t";
char *rest = NULL;
FstabItem *item = NULL;
......@@ -135,37 +134,37 @@ static int ParseFstabPerLine(char *str, Fstab *fstab, bool procMounts)
if ((item = (FstabItem *)calloc(1, sizeof(FstabItem))) == NULL) {
errno = ENOMEM;
FSMGR_LOGE("Allocate memory for FS table item failed, err = %d", errno);
BEGET_LOGE("Allocate memory for FS table item failed, err = %d", errno);
return -1;
}
do {
if ((p = strtok_r(str, separator, &rest)) == NULL) {
FSMGR_LOGE("Failed to parse block device.");
BEGET_LOGE("Failed to parse block device.");
break;
}
item->deviceName = strdup(p);
if ((p = strtok_r(NULL, separator, &rest)) == NULL) {
FSMGR_LOGE("Failed to parse mount point.");
BEGET_LOGE("Failed to parse mount point.");
break;
}
item->mountPoint = strdup(p);
if ((p = strtok_r(NULL, separator, &rest)) == NULL) {
FSMGR_LOGE("Failed to parse fs type.");
BEGET_LOGE("Failed to parse fs type.");
break;
}
item->fsType = strdup(p);
if ((p = strtok_r(NULL, separator, &rest)) == NULL) {
FSMGR_LOGE("Failed to parse mount options.");
BEGET_LOGE("Failed to parse mount options.");
break;
}
item->mountOptions = strdup(p);
if ((p = strtok_r(NULL, separator, &rest)) == NULL) {
FSMGR_LOGE("Failed to parse fs manager flags.");
BEGET_LOGE("Failed to parse fs manager flags.");
break;
}
// @fsManagerFlags only for fstab
......@@ -193,18 +192,18 @@ Fstab *ReadFstabFromFile(const char *file, bool procMounts)
char *realPath = GetRealPath(file);
if (realPath == NULL) {
FSMGR_LOGE("Invalid file");
BEGET_LOGE("Invalid file");
return NULL;
}
FILE *fp = fopen(realPath, "r");
free(realPath);
if (fp == NULL) {
FSMGR_LOGE("Open %s failed, err = %d", file, errno);
BEGET_LOGE("Open %s failed, err = %d", file, errno);
return NULL;
}
if ((fstab = (Fstab *)calloc(1, sizeof(Fstab))) == NULL) {
FSMGR_LOGE("Allocate memory for FS table failed, err = %d", errno);
BEGET_LOGE("Allocate memory for FS table failed, err = %d", errno);
fclose(fp);
fp = NULL;
return NULL;
......@@ -234,7 +233,7 @@ Fstab *ReadFstabFromFile(const char *file, bool procMounts)
}
// If one line in fstab file parsed with a failure. just give a warning
// and skip it.
FSMGR_LOGW("Cannot parse file \" %s \" at line %zu. skip it", file, ln);
BEGET_LOGW("Cannot parse file \" %s \" at line %zu. skip it", file, ln);
continue;
}
}
......@@ -270,7 +269,7 @@ FstabItem *FindFstabItemForPath(Fstab fstab, const char *path)
char tmp[PATH_MAX] = {0};
char *dir = NULL;
if (strncpy_s(tmp, PATH_MAX - 1, path, strlen(path)) != EOK) {
FSMGR_LOGE("Failed to copy path.");
BEGET_LOGE("Failed to copy path.");
return NULL;
}
......@@ -294,28 +293,28 @@ char *GetFstabFile(void)
char file[PATH_MAX] = {0};
if (InUpdaterMode() == 1) {
if (strncpy_s(file, PATH_MAX, "/etc/fstab.updater", strlen("/etc/fstab.updater")) != 0) {
FSMGR_LOGE("Failed strncpy_s err=%d", errno);
BEGET_LOGE("Failed strncpy_s err=%d", errno);
return NULL;
}
} else {
char hardware[MAX_BUFFER_LEN] = {0};
char *buffer = ReadFileData("/proc/cmdline");
if (buffer == NULL) {
FSMGR_LOGE("Failed read \"/proc/cmdline\"");
BEGET_LOGE("Failed read \"/proc/cmdline\"");
return NULL;
}
int ret = GetProcCmdlineValue("hardware", buffer, hardware, MAX_BUFFER_LEN);
free(buffer);
if (ret != 0) {
FSMGR_LOGE("Failed get hardware from cmdline");
BEGET_LOGE("Failed get hardware from cmdline");
return NULL;
}
if (snprintf_s(file, PATH_MAX, PATH_MAX - 1, "/vendor/etc/fstab.%s", hardware) == -1) {
FSMGR_LOGE("Fail snprintf_s err=%d", errno);
BEGET_LOGE("Fail snprintf_s err=%d", errno);
return NULL;
}
}
FSMGR_LOGI("file is %s", file);
BEGET_LOGI("file is %s", file);
return strdup(file); // After the return value is used up, it must be free.
}
......@@ -326,11 +325,11 @@ int GetBlockDeviceByMountPoint(const char *mountPoint, const Fstab *fstab, char
}
FstabItem *item = FindFstabItemForMountPoint(*fstab, mountPoint);
if (item == NULL) {
FSMGR_LOGE("Failed get fstab item from point \" %s \"", mountPoint);
BEGET_LOGE("Failed get fstab item from point \" %s \"", mountPoint);
return -1;
}
if (strncpy_s(deviceName, nameLen, item->deviceName, strlen(item->deviceName)) != 0) {
FSMGR_LOGE("Failed strncpy_s err=%d", errno);
BEGET_LOGE("Failed strncpy_s err=%d", errno);
return -1;
}
return 0;
......@@ -387,7 +386,7 @@ static unsigned long ParseDefaultMountFlag(const char *str)
unsigned long GetMountFlags(char *mountFlag, char *fsSpecificData, size_t fsSpecificDataSize)
{
unsigned long flags = 0;
INIT_CHECK_RETURN_VALUE(mountFlag != NULL && fsSpecificData != NULL, 0);
BEGET_CHECK_RETURN_VALUE(mountFlag != NULL && fsSpecificData != NULL, 0);
int flagCount = 0;
// Why max count of mount flags is 15?
// There are lots for mount flags defined in sys/mount.h
......@@ -409,7 +408,7 @@ unsigned long GetMountFlags(char *mountFlag, char *fsSpecificData, size_t fsSpec
flags |= ParseDefaultMountFlag(p);
} else {
if (strncat_s(fsSpecificData, fsSpecificDataSize - 1, p, strlen(p)) != EOK) {
FSMGR_LOGW("Failed to append mount flag \" %s \", ignore it.", p);
BEGET_LOGW("Failed to append mount flag \" %s \", ignore it.", p);
continue;
}
if (i == flagCount - 1) { // last flags, do not need to append ','
......@@ -417,7 +416,7 @@ unsigned long GetMountFlags(char *mountFlag, char *fsSpecificData, size_t fsSpec
}
// Combined each mount flag with ','
if (strncat_s(fsSpecificData, fsSpecificDataSize - 1, ",", 1) != EOK) {
FSMGR_LOGW("Failed to append comma.");
BEGET_LOGW("Failed to append comma.");
break; // If cannot add ',' to the end of flags, there is not reason to continue.
}
}
......
......@@ -22,9 +22,8 @@
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include "beget_ext.h"
#include "fs_manager/fs_manager.h"
#include "fs_manager/fs_manager_log.h"
#include "init_log.h"
#include "init_utils.h"
#include "securec.h"
......@@ -62,7 +61,7 @@ static int ExecCommand(int argc, char **argv)
}
pid_t pid = fork();
if (pid < 0) {
INIT_LOGE("Fork new process to format failed: %d", errno);
BEGET_LOGE("Fork new process to format failed: %d", errno);
return -1;
}
if (pid == 0) {
......@@ -72,7 +71,7 @@ static int ExecCommand(int argc, char **argv)
int status;
waitpid(pid, &status, 0);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
FSMGR_LOGE("Command %s failed with status %d", argv[0], WEXITSTATUS(status));
BEGET_LOGE("Command %s failed with status %d", argv[0], WEXITSTATUS(status));
}
return WEXITSTATUS(status);
}
......@@ -84,7 +83,7 @@ int DoFormat(const char *devPath, const char *fsType)
}
if (!IsSupportedFilesystem(fsType)) {
FSMGR_LOGE("Do not support filesystem \" %s \"", fsType);
BEGET_LOGE("Do not support filesystem \" %s \"", fsType);
return -1;
}
int ret = 0;
......@@ -92,7 +91,7 @@ int DoFormat(const char *devPath, const char *fsType)
if (strcmp(fsType, "ext4") == 0) {
const unsigned int blockSize = 4096;
if (snprintf_s(blockSizeBuffer, BLOCK_SIZE_BUFFER, BLOCK_SIZE_BUFFER - 1, "%u", blockSize) == -1) {
FSMGR_LOGE("Failed to build block size buffer");
BEGET_LOGE("Failed to build block size buffer");
return -1;
}
char *formatCmds[] = {
......@@ -158,7 +157,7 @@ static int DoResizeF2fs(const char* device, const unsigned long long size)
{
char *file = "/system/bin/resize.f2fs";
if (access(file, F_OK) != 0) {
INIT_LOGE("resize.f2fs is not exists.");
BEGET_LOGE("resize.f2fs is not exists.");
return -1;
}
......@@ -188,7 +187,7 @@ static int DoFsckF2fs(const char* device)
{
char *file = "/system/bin/fsck.f2fs";
if (access(file, F_OK) != 0) {
INIT_LOGE("fsck.f2fs is not exists.");
BEGET_LOGE("fsck.f2fs is not exists.");
return -1;
}
......@@ -204,7 +203,7 @@ static int DoResizeExt(const char* device, const unsigned long long size)
{
char *file = "/system/bin/resize2fs";
if (access(file, F_OK) != 0) {
INIT_LOGE("resize2fs is not exists.");
BEGET_LOGE("resize2fs is not exists.");
return -1;
}
......@@ -233,7 +232,7 @@ static int DoFsckExt(const char* device)
{
char *file = "/system/bin/e2fsck";
if (access(file, F_OK) != 0) {
INIT_LOGE("e2fsck is not exists.");
BEGET_LOGE("e2fsck is not exists.");
return -1;
}
......@@ -252,11 +251,11 @@ static int Mount(const char *source, const char *target, const char *fsType,
int rc = -1;
if (source == NULL || target == NULL || fsType == NULL) {
FSMGR_LOGE("Invalid argment for mount.");
BEGET_LOGE("Invalid argment for mount.");
return -1;
}
if (stat(target, &st) != 0 && errno != ENOENT) {
FSMGR_LOGE("Cannot get stat of \" %s \", err = %d", target, errno);
BEGET_LOGE("Cannot get stat of \" %s \", err = %d", target, errno);
return -1;
}
if ((st.st_mode & S_IFMT) == S_IFLNK) { // link, delete it.
......@@ -264,14 +263,14 @@ static int Mount(const char *source, const char *target, const char *fsType,
}
if (mkdir(target, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0) {
if (errno != EEXIST) {
FSMGR_LOGE("Failed to create dir \" %s \", err = %d", target, errno);
BEGET_LOGE("Failed to create dir \" %s \", err = %d", target, errno);
return -1;
}
}
errno = 0;
while ((rc = mount(source, target, fsType, flags, data)) != 0) {
if (errno == EAGAIN) {
FSMGR_LOGE("Mount %s to %s failed. try again", source, target);
BEGET_LOGE("Mount %s to %s failed. try again", source, target);
continue;
} else {
break;
......@@ -290,7 +289,7 @@ int MountOneItem(FstabItem *item)
mountFlags = GetMountFlags(item->mountOptions, fsSpecificData, sizeof(fsSpecificData));
if (!IsSupportedFilesystem(item->fsType)) {
FSMGR_LOGE("Unsupported file system \" %s \"", item->fsType);
BEGET_LOGE("Unsupported file system \" %s \"", item->fsType);
return -1;
}
if (FM_MANAGER_WAIT_ENABLED(item->fsManagerFlags)) {
......@@ -300,29 +299,29 @@ int MountOneItem(FstabItem *item)
if (strcmp(item->fsType, "f2fs") == 0 && strcmp(item->mountPoint, "/data") == 0) {
int ret = DoResizeF2fs(item->deviceName, 0);
if (ret != 0) {
INIT_LOGE("Failed to resize.f2fs dir %s , ret = %d", item->deviceName, ret);
BEGET_LOGE("Failed to resize.f2fs dir %s , ret = %d", item->deviceName, ret);
}
ret = DoFsckF2fs(item->deviceName);
if (ret != 0) {
INIT_LOGE("Failed to fsck.f2fs dir %s , ret = %d", item->deviceName, ret);
BEGET_LOGE("Failed to fsck.f2fs dir %s , ret = %d", item->deviceName, ret);
}
} else if (strcmp(item->fsType, "ext4") == 0 && strcmp(item->mountPoint, "/data") == 0) {
int ret = DoResizeExt(item->deviceName, 0);
if (ret != 0) {
INIT_LOGE("Failed to resize2fs dir %s , ret = %d", item->deviceName, ret);
BEGET_LOGE("Failed to resize2fs dir %s , ret = %d", item->deviceName, ret);
}
ret = DoFsckExt(item->deviceName);
if (ret != 0) {
INIT_LOGE("Failed to e2fsck dir %s , ret = %d", item->deviceName, ret);
BEGET_LOGE("Failed to e2fsck dir %s , ret = %d", item->deviceName, ret);
}
}
int rc = Mount(item->deviceName, item->mountPoint, item->fsType, mountFlags, fsSpecificData);
if (rc != 0) {
FSMGR_LOGE("Mount %s to %s failed %d", item->deviceName, item->mountPoint, errno);
BEGET_LOGE("Mount %s to %s failed %d", item->deviceName, item->mountPoint, errno);
} else {
FSMGR_LOGI("Mount %s to %s successful", item->deviceName, item->mountPoint);
BEGET_LOGI("Mount %s to %s successful", item->deviceName, item->mountPoint);
}
return rc;
}
......@@ -369,7 +368,7 @@ int MountAllWithFstabFile(const char *fstabFile, bool required)
}
Fstab *fstab = NULL;
if ((fstab = ReadFstabFromFile(fstabFile, false)) == NULL) {
FSMGR_LOGE("[fs_manager][error] Read fstab file \" %s \" failed\n", fstabFile);
BEGET_LOGE("[fs_manager][error] Read fstab file \" %s \" failed\n", fstabFile);
return -1;
}
......@@ -386,29 +385,29 @@ int UmountAllWithFstabFile(const char *fstabFile)
}
Fstab *fstab = NULL;
if ((fstab = ReadFstabFromFile(fstabFile, false)) == NULL) {
FSMGR_LOGE("Read fstab file \" %s \" failed.", fstabFile);
BEGET_LOGE("Read fstab file \" %s \" failed.", fstabFile);
return -1;
}
FstabItem *item = NULL;
int rc = -1;
for (item = fstab->head; item != NULL; item = item->next) {
FSMGR_LOGI("Umount %s.", item->mountPoint);
BEGET_LOGI("Umount %s.", item->mountPoint);
MountStatus status = GetMountStatusForMountPoint(item->mountPoint);
if (status == MOUNT_ERROR) {
FSMGR_LOGW("Cannot get mount status of mount point \" %s \"", item->mountPoint);
BEGET_LOGW("Cannot get mount status of mount point \" %s \"", item->mountPoint);
continue; // Cannot get mount status, just ignore it and try next one.
} else if (status == MOUNT_UMOUNTED) {
FSMGR_LOGI("Mount point \" %s \" already unmounted. device path: %s, fs type: %s.",
BEGET_LOGI("Mount point \" %s \" already unmounted. device path: %s, fs type: %s.",
item->mountPoint, item->deviceName, item->fsType);
continue;
} else {
rc = umount(item->mountPoint);
if (rc == -1) {
FSMGR_LOGE("Umount %s failed, device path: %s, fs type: %s, err = %d.",
BEGET_LOGE("Umount %s failed, device path: %s, fs type: %s, err = %d.",
item->mountPoint, item->deviceName, item->fsType, errno);
} else {
FSMGR_LOGE("Umount %s successfully.", item->mountPoint);
BEGET_LOGE("Umount %s successfully.", item->mountPoint);
}
}
}
......@@ -420,4 +419,4 @@ int UmountAllWithFstabFile(const char *fstabFile)
#if __cplusplus
}
#endif
#endif
\ No newline at end of file
#endif
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BEGET_EXT_API_H
#define BEGET_EXT_API_H
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
#if defined(ENABLE_HILOG) || defined(OHOS_LITE)
#include "hilog/log.h"
#undef LOG_DOMAIN
#define LOG_DOMAIN 0xD000719
#endif
typedef enum InitLogLevel {
INIT_DEBUG = 0,
INIT_INFO,
INIT_WARN,
INIT_ERROR,
INIT_FATAL
} InitLogLevel;
#ifndef INIT_LOG_PATH
#define INIT_LOG_PATH "/data/init_agent/"
#endif
#define FILE_NAME (strrchr((__FILE__), '/') ? strrchr((__FILE__), '/') + 1 : (__FILE__))
void InitLogInit(const char *outFileName, InitLogLevel logLevel, const char *kLevel, const char *fmt, ...);
void InitLogAgent(const char *outFileName, InitLogLevel logLevel, const char *kLevel, const char *fmt, ...);
void OpenLogDevice(void);
#ifndef INIT_AGENT
#define InitLogPrint InitLogInit
#else
#define InitLogPrint InitLogAgent
#endif
#ifndef OHOS_LITE
#ifndef ENABLE_HILOG
#define STARTUP_LOGV(logFile, LABEL, fmt, ...) \
do { \
InitLogPrint(INIT_LOG_PATH logFile, INIT_DEBUG, LABEL, "[%s:%d)] " fmt "\n", \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
} while (0)
#define STARTUP_LOGI(logFile, LABEL, fmt, ...) \
do { \
InitLogPrint(INIT_LOG_PATH logFile, INIT_INFO, LABEL, "[%s:%d)] " fmt "\n", \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
} while (0)
#define STARTUP_LOGE(logFile, LABEL, fmt, ...) \
do { \
InitLogPrint(INIT_LOG_PATH logFile, INIT_ERROR, LABEL, "[%s:%d)] " fmt "\n", \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
} while (0)
#define STARTUP_LOGW(logFile, LABEL, fmt, ...) \
do { \
InitLogPrint(INIT_LOG_PATH logFile, INIT_WARN, LABEL, "[%s:%d)] " fmt "\n", \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
} while (0)
#else
#define STARTUP_LOGV(logFile, LABEL, fmt, ...) \
do { \
InitLogPrint(INIT_LOG_PATH logFile, INIT_DEBUG, LABEL, "[%s:%d)] " fmt "\n", \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
(void)HiLogPrint(LOG_APP, LOG_DEBUG, LOG_DOMAIN, LABEL, "[%{public}s(%{public}d)] " fmt, \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
} while (0)
#define STARTUP_LOGI(logFile, LABEL, fmt, ...) \
do { \
InitLogPrint(INIT_LOG_PATH logFile, INIT_INFO, LABEL, "[%s:%d)] " fmt "\n", \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
(void)HiLogPrint(LOG_APP, LOG_INFO, LOG_DOMAIN, LABEL, "[%{public}s(%{public}d)] " fmt, \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
} while (0)
#define STARTUP_LOGE(logFile, LABEL, fmt, ...) \
do { \
InitLogPrint(INIT_LOG_PATH logFile, INIT_ERROR, LABEL, "[%s:%d)] " fmt "\n", \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
(void)HiLogPrint(LOG_APP, LOG_ERROR, LOG_DOMAIN, LABEL, "[%{public}s(%{public}d)] " fmt, \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
} while (0)
#define STARTUP_LOGW(logFile, LABEL, fmt, ...) \
do { \
InitLogPrint(INIT_LOG_PATH logFile, INIT_WARN, LABEL, "[%s:%d)] " fmt "\n", \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
(void)HiLogPrint(LOG_APP, LOG_WARN, LOG_DOMAIN, LABEL, "[%{public}s(%{public}d)] " fmt, \
(FILE_NAME), (__LINE__), ##__VA_ARGS__); \
} while (0)
#endif
#endif
#define BEGET_LOG_FILE "beget.log"
#define BEGET_LABEL "BEGET"
#define BEGET_LOGI(fmt, ...) STARTUP_LOGI(BEGET_LOG_FILE, BEGET_LABEL, fmt, ##__VA_ARGS__)
#define BEGET_LOGE(fmt, ...) STARTUP_LOGE(BEGET_LOG_FILE, BEGET_LABEL, fmt, ##__VA_ARGS__)
#define BEGET_LOGV(fmt, ...) STARTUP_LOGV(BEGET_LOG_FILE, BEGET_LABEL, fmt, ##__VA_ARGS__)
#define BEGET_LOGW(fmt, ...) STARTUP_LOGW(BEGET_LOG_FILE, BEGET_LABEL, fmt, ##__VA_ARGS__)
#define BEGET_ERROR_CHECK(ret, statement, format, ...) \
if (!(ret)) { \
BEGET_LOGE(format, ##__VA_ARGS__); \
statement; \
} \
#define BEGET_INFO_CHECK(ret, statement, format, ...) \
if (!(ret)) { \
BEGET_LOGI(format, ##__VA_ARGS__); \
statement; \
} \
#define BEGET_WARNING_CHECK(ret, statement, format, ...) \
if (!(ret)) { \
BEGET_LOGW(format, ##__VA_ARGS__); \
statement; \
} \
#define BEGET_CHECK(ret, statement) \
if (!(ret)) { \
statement; \
} \
#define BEGET_CHECK_RETURN_VALUE(ret, result) \
do { \
if (!(ret)) { \
return result; \
} \
} while (0)
#define BEGET_CHECK_ONLY_RETURN(ret) \
do { \
if (!(ret)) { \
return; \
} \
} while (0)
#define BEGET_CHECK_ONLY_ELOG(ret, format, ...) \
do { \
if (!(ret)) { \
BEGET_LOGE(format, ##__VA_ARGS__); \
} \
} while (0)
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
#endif
\ No newline at end of file
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BASE_STARTUP_INITLITE_FD_HOLDER_H
#define BASE_STARTUP_INITLITE_FD_HOLDER_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
// fds stored in allocated memory, do not forget to release the memory when not use anymore
int *ServiceGetFd(const char *serviceName, size_t *fdCount);
// Let init poll the fd for service
// This function will not take responsibility to close these fds
// Caller need to handle them.
int ServiceSaveFdWithPoll(const char *serviceName, int *fds, int fdCount);
// Init only save the fd for service
// This function will not take responsibility to close these fds
// Caller need to handle them.
int ServiceSaveFd(const char *serviceName, int *fds, int fdCount);
#ifdef __cplusplus
}
#endif
#endif // BASE_STARTUP_INITLITE_FD_HOLDER_H
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef STARTUP_FS_MANAGER_LOG_H
#define STARTUP_FS_MANAGER_LOG_H
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
typedef enum LOGTARGET {
LOG_TO_KERNEL,
LOG_TO_FILE,
LOG_TO_STDIO
} LogTarget;
typedef enum FsMgrLogLevel {
FSMGR_VERBOSE,
FSMGR_DEBUG,
FSMGR_INFO,
FSMGR_WARNING,
FSMGR_ERROR,
FSMGR_FATAL
} FsMgrLogLevel;
void FsManagerLogInit(LogTarget target, const char *fileName);
void FsManagerLogDeInit(void);
void FsManagerLogToStd(FsMgrLogLevel level, const char *fileName, int line, const char *fmt, ...);
typedef void (*FsManagerLogFunc)(FsMgrLogLevel level, const char *fileName, int line, const char *fmt, ...);
extern FsManagerLogFunc g_logFunc;
#define FILE_NAME (strrchr((__FILE__), '/') ? strrchr((__FILE__), '/') + 1 : (__FILE__))
#define FSMGR_LOGV(fmt, ...) g_logFunc(FSMGR_VERBOSE, (FILE_NAME), (__LINE__), fmt"\n", ##__VA_ARGS__)
#define FSMGR_LOGD(fmt, ...) g_logFunc(FSMGR_DEBUG, (FILE_NAME), (__LINE__), fmt"\n", ##__VA_ARGS__)
#define FSMGR_LOGI(fmt, ...) g_logFunc(FSMGR_INFO, (FILE_NAME), (__LINE__), fmt"\n", ##__VA_ARGS__)
#define FSMGR_LOGW(fmt, ...) g_logFunc(FSMGR_WARNING, (FILE_NAME), (__LINE__), fmt"\n", ##__VA_ARGS__)
#define FSMGR_LOGE(fmt, ...) g_logFunc(FSMGR_ERROR, (FILE_NAME), (__LINE__), fmt"\n", ##__VA_ARGS__)
#define FSMGR_LOGF(fmt, ...) g_logFunc(FSMGR_FATAL, (FILE_NAME), (__LINE__), fmt"\n", ##__VA_ARGS__)
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
#endif // STARTUP_FS_MANAGER_LOG_H
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BASE_STARTUP_INIT_PLUGIN_H
#define BASE_STARTUP_INIT_PLUGIN_H
#include <stdint.h>
#include <stdio.h>
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
#define PLUGIN_CONSTRUCTOR(void) static void _init(void) __attribute__((constructor)); static void _init(void)
#define PLUGIN_DESTRUCTOR(void) static void _destroy(void) __attribute__((destructor)); static void _destroy(void)
typedef struct {
int (*pluginRegister)(const char *name, const char *config, int (*pluginInit)(void), void (*pluginExit)(void));
int (*addCmdExecutor)(const char *cmdName,
void (*CmdExecutor)(int id, const char *name, int argc, const char **argv));
void (*removeCmdExecutor)(const char *cmdName, int id);
int (*systemWriteParam)(const char *name, const char *value);
int (*systemReadParam)(const char *name, char *value, unsigned int *len);
} PluginInterface;
PluginInterface *GetPluginInterface(void);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
#endif // BASE_STARTUP_INIT_PLUGIN_H
文件模式从 100755 更改为 100644
文件模式从 100755 更改为 100644
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
ohos_shared_library("libplugin") {
sources = [ "init_plugin.c" ]
include_dirs = [
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/services/log",
]
deps = [
"//base/startup/init_lite/services/log:init_log",
"//third_party/bounds_checking_function:libsec_static",
]
install_enable = true
part_name = "init"
}
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "init_plugin.h"
static PluginInterface g_pluginInterface = {};
PluginInterface *GetPluginInterface(void)
{
return &g_pluginInterface;
}
......@@ -18,7 +18,7 @@
#include <sys/types.h>
#include <unistd.h>
#include "init_log.h"
#include "beget_ext.h"
#include "param.h"
#include "securec.h"
#include "sys_param.h"
......@@ -36,18 +36,18 @@ int DoReboot(const char *option)
{
char value[MAX_REBOOT_OPTION_SIZE];
if (option == NULL || strlen(option) == 0) {
INIT_ERROR_CHECK(snprintf_s(value, MAX_REBOOT_OPTION_SIZE, strlen("reboot") + 1, "%s", "reboot") >= 0,
BEGET_ERROR_CHECK(snprintf_s(value, MAX_REBOOT_OPTION_SIZE, strlen("reboot") + 1, "%s", "reboot") >= 0,
return -1, "reboot options too large, overflow");
INIT_ERROR_CHECK(SystemSetParameter(DOREBOOT_PARAM, value) == 0, return -1,
BEGET_ERROR_CHECK(SystemSetParameter(DOREBOOT_PARAM, value) == 0, return -1,
"Set parameter to trigger reboot command \" %s \" failed", value);
return 0;
}
int length = strlen(option);
INIT_ERROR_CHECK(length <= MAX_REBOOT_OPTION_SIZE, return -1,
BEGET_ERROR_CHECK(length <= MAX_REBOOT_OPTION_SIZE, return -1,
"Reboot option \" %s \" is too large, overflow", option);
INIT_ERROR_CHECK(snprintf_s(value, MAX_REBOOT_OPTION_SIZE, MAX_REBOOT_OPTION_SIZE - 1, "%s%s", "reboot,",
BEGET_ERROR_CHECK(snprintf_s(value, MAX_REBOOT_OPTION_SIZE, MAX_REBOOT_OPTION_SIZE - 1, "%s%s", "reboot,",
option) >= 0, return -1, "Failed to copy boot option \" %s \"", option);
INIT_ERROR_CHECK(SystemSetParameter(DOREBOOT_PARAM, value) == 0, return -1,
BEGET_ERROR_CHECK(SystemSetParameter(DOREBOOT_PARAM, value) == 0, return -1,
"Set parameter to trigger reboot command \" %s \" failed", value);
return 0;
}
......
......@@ -20,20 +20,20 @@
#include <stdlib.h>
#include <string.h>
#include "hilog/log.h"
#include "beget_ext.h"
#include "init_utils.h"
#include "securec.h"
#include "sys_param.h"
static int StartDynamicProcess(const char *name, const char *extArgv[], int extArgc)
static int StartProcess(const char *name, const char *extArgv[], int extArgc)
{
if (name == NULL) {
HILOG_ERROR(LOG_CORE, "Start dynamic service failed, service name is null.");
BEGET_LOGE("Start dynamic service failed, service name is null.");
return -1;
}
int extraArg = 0;
if ((extArgv != NULL) && (extArgc > 0)) {
HILOG_INFO(LOG_CORE, "Start service by extra args");
BEGET_LOGI("Start service by extra args");
extraArg = 1;
}
if (extraArg == 1) {
......@@ -44,97 +44,102 @@ static int StartDynamicProcess(const char *name, const char *extArgv[], int extA
len += strlen(name) + extArgc + 1;
char *nameValue = (char *)calloc(len, sizeof(char));
if (nameValue == NULL) {
HILOG_ERROR(LOG_CORE, "Failed calloc err=%{public}d", errno);
BEGET_LOGE("Failed calloc err=%d", errno);
return -1;
}
if (strncat_s(nameValue, len, name, strlen(name)) != 0) {
HILOG_ERROR(LOG_CORE, "Failed strncat_s name err=%{public}d", errno);
BEGET_LOGE("Failed strncat_s name err=%d", errno);
return -1;
}
for (int j = 0; j < extArgc; j++) {
if (strncat_s(nameValue, len, "|", 1) != 0) {
HILOG_ERROR(LOG_CORE, "Failed strncat_s \"|\"err=%{public}d", errno);
BEGET_LOGE("Failed strncat_s \"|\"err=%d", errno);
return -1;
}
if (strncat_s(nameValue, len, extArgv[j], strlen(extArgv[j])) != 0) {
HILOG_ERROR(LOG_CORE, "Failed strncat_s err=%{public}d", errno);
BEGET_LOGE("Failed strncat_s err=%d", errno);
return -1;
}
}
if (SystemSetParameter("ohos.ctl.start", nameValue) != 0) {
HILOG_ERROR(LOG_CORE, "Set param for %{public}s failed.\n", nameValue);
BEGET_LOGE("Set param for %s failed.\n", nameValue);
free(nameValue);
return -1;
}
free(nameValue);
} else {
if (SystemSetParameter("ohos.ctl.start", name) != 0) {
HILOG_ERROR(LOG_CORE, "Set param for %{public}s failed.\n", name);
BEGET_LOGE("Set param for %s failed.\n", name);
return -1;
}
}
return 0;
}
static int StopDynamicProcess(const char *serviceName)
static int StopProcess(const char *serviceName)
{
if (serviceName == NULL) {
HILOG_ERROR(LOG_CORE, "Stop dynamic service failed, service is null.\n");
BEGET_LOGE("Stop dynamic service failed, service is null.\n");
return -1;
}
if (SystemSetParameter("ohos.ctl.stop", serviceName) != 0) {
HILOG_ERROR(LOG_CORE, "Set param for %{public}s failed.\n", serviceName);
BEGET_LOGE("Set param for %s failed.\n", serviceName);
return -1;
}
return 0;
}
static int GetCurrentServiceStatus(const char *serviceName, char *paramValue, unsigned int valueLen)
static int GetCurrentServiceStatus(const char *serviceName, char *status, int len)
{
char paramName[PARAM_NAME_LEN_MAX] = {0};
if (snprintf_s(paramName, PARAM_NAME_LEN_MAX, PARAM_NAME_LEN_MAX - 1, "init.svc.%s", serviceName) == -1) {
HILOG_ERROR(LOG_CORE, "Failed snprintf_s err=%{public}d", errno);
BEGET_LOGE("Failed snprintf_s err=%d", errno);
return -1;
}
char paramValue[PARAM_VALUE_LEN_MAX] = {0};
unsigned int valueLen = PARAM_VALUE_LEN_MAX;
if (SystemGetParameter(paramName, paramValue, &valueLen) != 0) {
HILOG_ERROR(LOG_CORE, "Failed get paramName.");
BEGET_LOGE("Failed get paramName.");
return -1;
}
if (strncpy_s(status, len, paramValue, len - 1) < 0) {
BEGET_LOGE("Failed strncpy_s err=%d", errno);
return -1;
}
return 0;
}
static int RestartDynamicProcess(const char *serviceName, const char *extArgv[], int extArgc)
static int RestartProcess(const char *serviceName, const char *extArgv[], int extArgc)
{
if (serviceName == NULL) {
HILOG_ERROR(LOG_CORE, "Restart dynamic service failed, service is null.\n");
BEGET_LOGE("Restart dynamic service failed, service is null.\n");
return -1;
}
char paramValue[PARAM_VALUE_LEN_MAX] = {0};
unsigned int valueLen = PARAM_VALUE_LEN_MAX;
if (GetCurrentServiceStatus(serviceName, paramValue, valueLen) != 0) {
HILOG_ERROR(LOG_CORE, "Get service status failed.\n");
char status[PARAM_VALUE_LEN_MAX] = {0};
if (GetCurrentServiceStatus(serviceName, status, PARAM_VALUE_LEN_MAX) != 0) {
BEGET_LOGE("Get service status failed.\n");
return -1;
}
if (strcmp(paramValue, "running") == 0) {
if (StopDynamicProcess(serviceName) != 0) {
HILOG_ERROR(LOG_CORE, "Stop service %{public}s failed", serviceName);
if (strcmp(status, "running") == 0) {
if (StopProcess(serviceName) != 0) {
BEGET_LOGE("Stop service %s failed", serviceName);
return -1;
}
if (ServiceWaitForStatus(serviceName, "stopped", DEFAULT_PARAM_WAIT_TIMEOUT) != 0) {
HILOG_ERROR(LOG_CORE, "Failed wait service %{public}s stopped", serviceName);
BEGET_LOGE("Failed wait service %s stopped", serviceName);
return -1;
}
if (StartDynamicProcess(serviceName, extArgv, extArgc) != 0) {
HILOG_ERROR(LOG_CORE, "Start service %{public}s failed", serviceName);
if (StartProcess(serviceName, extArgv, extArgc) != 0) {
BEGET_LOGE("Start service %s failed", serviceName);
return -1;
}
} else if (strcmp(paramValue, "stopped") == 0) {
if (StartDynamicProcess(serviceName, extArgv, extArgc) != 0) {
HILOG_ERROR(LOG_CORE, "Start service %{public}s failed", serviceName);
} else if (strcmp(status, "stopped") == 0) {
if (StartProcess(serviceName, extArgv, extArgc) != 0) {
BEGET_LOGE("Start service %s failed", serviceName);
return -1;
}
} else {
HILOG_ERROR(LOG_CORE, "Current service status: %{public}s is not support.", paramValue);
BEGET_LOGE("Current service status: %s is not support.", status);
}
return 0;
}
......@@ -142,22 +147,22 @@ static int RestartDynamicProcess(const char *serviceName, const char *extArgv[],
int ServiceControlWithExtra(const char *serviceName, int action, const char *extArgv[], int extArgc)
{
if (serviceName == NULL) {
HILOG_ERROR(LOG_CORE, "Service wait failed, service is null.\n");
BEGET_LOGE("Service wait failed, service is null.\n");
return -1;
}
int ret = 0;
switch (action) {
case START:
ret = StartDynamicProcess(serviceName, extArgv, extArgc);
ret = StartProcess(serviceName, extArgv, extArgc);
break;
case STOP:
ret = StopDynamicProcess(serviceName);
ret = StopProcess(serviceName);
break;
case RESTART:
ret = RestartDynamicProcess(serviceName, extArgv, extArgc);
ret = RestartProcess(serviceName, extArgv, extArgc);
break;
default:
HILOG_ERROR(LOG_CORE, "Set service %{public}s action %d error", serviceName, action);
BEGET_LOGE("Set service %s action %d error", serviceName, action);
ret = -1;
break;
}
......@@ -167,7 +172,7 @@ int ServiceControlWithExtra(const char *serviceName, int action, const char *ext
int ServiceControl(const char *serviceName, int action)
{
if (serviceName == NULL) {
HILOG_ERROR(LOG_CORE, "Service getctl failed, service is null.\n");
BEGET_LOGE("Service getctl failed, service is null.");
return -1;
}
int ret = ServiceControlWithExtra(serviceName, action, NULL, 0);
......@@ -178,18 +183,18 @@ int ServiceControl(const char *serviceName, int action)
int ServiceWaitForStatus(const char *serviceName, const char *status, int waitTimeout)
{
if (serviceName == NULL) {
HILOG_ERROR(LOG_CORE, "Service wait failed, service is null.\n");
BEGET_LOGE("Service wait failed, service is null.");
return -1;
}
char paramName[PARAM_NAME_LEN_MAX] = {0};
if (snprintf_s(paramName, PARAM_NAME_LEN_MAX, PARAM_NAME_LEN_MAX - 1, "init.svc.%s", serviceName) == -1) {
HILOG_ERROR(LOG_CORE, "Failed snprintf_s err=%{public}d", errno);
BEGET_LOGE("Failed snprintf_s err=%d", errno);
return -1;
}
if (SystemWaitParameter(paramName, status, waitTimeout) != 0) {
HILOG_ERROR(LOG_CORE, "Wait param for %{public}s failed.\n", paramName);
BEGET_LOGE("Wait param for %s failed.", paramName);
return -1;
}
HILOG_INFO(LOG_CORE, "Success wait");
BEGET_LOGI("Success wait");
return 0;
}
......@@ -19,23 +19,23 @@
#include <stdlib.h>
#include <string.h>
#include "hilog/log.h"
#include "beget_ext.h"
#include "init_utils.h"
#include "securec.h"
int ServiceWatchForStatus(const char *serviceName, void *context, ServiceStatusChangePtr changeCallback)
{
if (serviceName == NULL) {
HILOG_ERROR(LOG_CORE, "Service wait failed, service is null.\n");
BEGET_LOGE("Service wait failed, service is null.");
return -1;
}
char paramName[PARAM_NAME_LEN_MAX] = {0};
if (snprintf_s(paramName, PARAM_NAME_LEN_MAX, PARAM_NAME_LEN_MAX - 1, "init.svc.%s", serviceName) == -1) {
HILOG_ERROR(LOG_CORE, "Failed snprintf_s err=%{public}d", errno);
BEGET_LOGE("Failed snprintf_s err=%d", errno);
return -1;
}
if (SystemWatchParameter(paramName, changeCallback, context) != 0) {
HILOG_ERROR(LOG_CORE, "Wait param for %{public}s failed.\n", paramName);
BEGET_LOGE("Wait param for %s failed.", paramName);
return -1;
}
return 0;
......
......@@ -23,7 +23,7 @@
#include <sys/stat.h>
#include <sys/uio.h>
#include <sys/un.h>
#include "init_log.h"
#include "beget_ext.h"
#include "securec.h"
#define N_DEC 10
......@@ -32,36 +32,36 @@
static int GetControlFromEnv(const char *path, int length)
{
INIT_CHECK_RETURN_VALUE(path != NULL && length > 0, -1);
INIT_LOGI("GetControlFromEnv path is %s ", path);
BEGET_CHECK_RETURN_VALUE(path != NULL && length > 0, -1);
BEGET_LOGI("GetControlFromEnv path is %s ", path);
const char *val = getenv(path);
INIT_ERROR_CHECK(val != NULL, return -1, "GetControlFromEnv val is null %d", errno);
BEGET_ERROR_CHECK(val != NULL, return -1, "GetControlFromEnv val is null %d", errno);
errno = 0;
int fd = strtol(val, NULL, N_DEC);
INIT_CHECK_RETURN_VALUE(errno == 0, -1);
INIT_LOGI("GetControlFromEnv fd is %d ", fd);
INIT_ERROR_CHECK(fcntl(fd, F_GETFD) >= 0, return -1, "GetControlFromEnv errno %d ", errno);
BEGET_CHECK_RETURN_VALUE(errno == 0, -1);
BEGET_LOGI("GetControlFromEnv fd is %d ", fd);
BEGET_ERROR_CHECK(fcntl(fd, F_GETFD) >= 0, return -1, "GetControlFromEnv errno %d ", errno);
return fd;
}
int GetControlSocket(const char *name)
{
INIT_CHECK_RETURN_VALUE(name != NULL, -1);
BEGET_CHECK_RETURN_VALUE(name != NULL, -1);
char path[MAX_SOCKET_ENV_PREFIX_LEN] = {0};
INIT_CHECK_RETURN_VALUE(snprintf_s(path, sizeof(path), sizeof(path) - 1, OHOS_SOCKET_ENV_PREFIX"%s",
BEGET_CHECK_RETURN_VALUE(snprintf_s(path, sizeof(path), sizeof(path) - 1, OHOS_SOCKET_ENV_PREFIX"%s",
name) != -1, -1);
INIT_LOGI("GetControlSocket path is %s ", path);
BEGET_LOGI("GetControlSocket path is %s ", path);
int fd = GetControlFromEnv(path, MAX_SOCKET_ENV_PREFIX_LEN);
INIT_ERROR_CHECK(fd >= 0, return -1, "GetControlFromEnv fail ");
BEGET_ERROR_CHECK(fd >= 0, return -1, "GetControlFromEnv fail ");
struct sockaddr_un addr;
socklen_t addrlen = sizeof(addr);
int ret = getsockname(fd, (struct sockaddr*)&addr, &addrlen);
INIT_ERROR_CHECK(ret >= 0, return -1, "GetControlSocket errno %d ", errno);
BEGET_ERROR_CHECK(ret >= 0, return -1, "GetControlSocket errno %d ", errno);
char sockDir[MAX_SOCKET_DIR_LEN] = {0};
INIT_CHECK_RETURN_VALUE(snprintf_s(sockDir, sizeof(sockDir), sizeof(sockDir) - 1, OHOS_SOCKET_DIR"/%s",
BEGET_CHECK_RETURN_VALUE(snprintf_s(sockDir, sizeof(sockDir), sizeof(sockDir) - 1, OHOS_SOCKET_DIR"/%s",
name) != -1, -1);
INIT_LOGI("sockDir %s ", sockDir);
INIT_LOGI("addr.sun_path %s ", addr.sun_path);
BEGET_LOGI("sockDir %s ", sockDir);
BEGET_LOGI("addr.sun_path %s ", addr.sun_path);
if (strncmp(sockDir, addr.sun_path, strlen(sockDir)) == 0) {
return fd;
}
......
......@@ -7,20 +7,23 @@
"//base/startup/init_lite/ueventd:startup_ueventd",
"//base/startup/init_lite/watchdog:watchdog",
"//base/startup/init_lite/services/begetctl:begetctl",
"//base/startup/init_lite/services/begetctl:paramshell",
"//base/startup/init_lite/interfaces/innerkits:libbegetutil",
"//base/startup/init_lite/interfaces/innerkits:libservice_watcher",
"//base/startup/init_lite/interfaces/innerkits/file:libfile",
"//base/startup/init_lite/interfaces/innerkits/socket:libsocket"
"//base/startup/init_lite/interfaces/innerkits/socket:libsocket",
"//base/startup/init_lite/services/loopevent:loopevent",
"//base/startup/init_lite/interfaces/innerkits/plugin:libplugin"
],
"inner_kits": [{
"header": {
"header_files": [
"init_socket.h",
"init_file.h",
"fs_manager/fs_manager_log.h",
"fs_manager/fs_manager.h",
"init_reboot.h",
"service_control.h"
"service_control.h",
"beget_ext.h"
],
"header_base": "//base/startup/init_lite/interfaces/innerkits/include/"
},
......
......@@ -16,13 +16,11 @@ init_common_sources = [
"init/init_common_cmds.c",
"init/init_common_service.c",
"init/init_config.c",
"init/init_group_manager.c",
"init/init_service_file.c",
"init/init_service_manager.c",
"init/init_service_socket.c",
"init/main.c",
"log/init_log.c",
"utils/init_utils.c",
"utils/list.c",
]
if (defined(ohos_lite)) {
......@@ -41,7 +39,10 @@ if (defined(ohos_lite)) {
"init/lite/init_reboot.c",
"init/lite/init_service.c",
"init/lite/init_signal_handler.c",
"init/lite/init_socket_manager.c",
"log/init_log.c",
"utils/init_hashmap.c",
"utils/init_utils.c",
"utils/list.c",
]
sources += init_common_sources
......@@ -50,10 +51,12 @@ if (defined(ohos_lite)) {
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/init/include",
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/interfaces/innerkits/include",
"//third_party/cJSON",
"//third_party/bounds_checking_function/include",
"//base/startup/syspara_lite/interfaces/kits",
"//base/hiviewdfx/hilog_lite/interfaces/native/kits",
"//base/startup/init_lite/interfaces/innerkits/fd_holder",
]
cflags = [ "-Wall" ]
......@@ -98,16 +101,18 @@ if (defined(ohos_lite)) {
ohos_executable("init") {
sources = [
"//base/startup/init_lite/interfaces/innerkits/fd_holder/fd_holder_internal.c",
"init/adapter/init_adapter.c",
"init/standard/device.c",
"init/standard/fd_holder_service.c",
"init/standard/init.c",
"init/standard/init_cmds.c",
"init/standard/init_jobs.c",
"init/standard/init_mount.c",
"init/standard/init_plugin_manager.c",
"init/standard/init_reboot.c",
"init/standard/init_service.c",
"init/standard/init_signal_handler.c",
"init/standard/init_socket_manager.c",
"init/standard/switch_root.c",
]
......@@ -119,15 +124,20 @@ if (defined(ohos_lite)) {
"//base/startup/init_lite/services/init/include",
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/services/loopevent/include",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/interfaces/innerkits/fd_holder",
"//base/startup/init_lite/ueventd/include",
"//third_party/cJSON",
"//third_party/bounds_checking_function/include",
"//third_party/libuv/include",
]
deps = [
"//base/startup/init_lite/interfaces/innerkits:libfsmanager_static",
"//base/startup/init_lite/services/log:init_log",
"//base/startup/init_lite/services/loopevent:loopevent",
"//base/startup/init_lite/services/param:param_service",
"//base/startup/init_lite/services/utils:libinit_tools",
"//base/startup/init_lite/services/utils:libinit_utils",
"//base/startup/init_lite/ueventd:libueventd_ramdisk_static",
"//third_party/bounds_checking_function:libsec_static",
"//third_party/cJSON:cjson_static",
......@@ -154,8 +164,9 @@ if (defined(ohos_lite)) {
cflags += [ "-DWITH_SELINUX" ]
}
defines = [ "OHOS_SERVICE_DUMP" ]
if (!enable_ramdisk) {
defines = [ "DISABLE_INIT_TWO_STAGES" ]
defines += [ "DISABLE_INIT_TWO_STAGES" ]
}
if (defined(product_name) && product_name == "rk3568") {
......@@ -239,8 +250,14 @@ if (defined(ohos_lite)) {
module_install_dir = "etc/param"
}
ohos_prebuilt_etc("boot.group") {
source = "//base/startup/init_lite/services/etc/device.boot.group.cfg"
part_name = "init"
}
group("init_etc") {
deps = [
":boot.group",
":group",
":init.cfg",
":init.usb.cfg",
......
......@@ -10,7 +10,7 @@
# 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.
import("//base/startup/init_lite/begetd.gni")
import("//build/ohos.gni")
ohos_executable("begetctl") {
......@@ -20,6 +20,7 @@ ohos_executable("begetctl") {
"misc_daemon.cpp",
"param_cmd.c",
"service_control.c",
"shell/shell_bas.c",
]
defines = [ "INIT_AGENT" ]
......@@ -29,26 +30,22 @@ ohos_executable("begetctl") {
}
include_dirs = [
"shell",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/update/updater/interfaces/kits/include/misc_info",
"//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include",
"//base/startup/init_lite/services/include/param/",
"//base/startup/init_lite/services/param/include",
"//third_party/bounds_checking_function/include",
"//base/update/updateservice/interfaces/innerkits/include",
]
deps = [
"//base/startup/init_lite/interfaces/innerkits:libbegetutil",
"//base/startup/init_lite/services/log:agent_log",
"//base/startup/init_lite/services/param:param_client",
"//base/startup/syspara_lite/interfaces/innerkits/native/syspara:syspara",
"//third_party/bounds_checking_function:libsec_static",
]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
symlink_target_name = [
"misc_daemon",
"reboot",
......@@ -66,3 +63,43 @@ ohos_executable("begetctl") {
part_name = "init"
}
ohos_executable("paramshell") {
sources = [
"param_cmd.c",
"shell/shell_bas.c",
"shell/shell_main.c",
]
defines = [ "INIT_AGENT" ]
include_dirs = [
".",
"shell",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include",
"//base/startup/init_lite/services/include/param/",
"//base/startup/init_lite/services/param/include",
"//third_party/bounds_checking_function/include",
]
deps = [
"//base/startup/init_lite/services/log:agent_log",
"//base/startup/init_lite/services/param:param_client",
"//third_party/bounds_checking_function:libsec_static",
]
if (param_test) {
sources += [ "//base/startup/init_lite/test/plugintest/plugin_param_cmd.c" ]
deps += [
"//base/startup/init_lite/services/param/watcher:param_watcheragent",
"//base/startup/init_lite/test/plugintest:pluginparamtest",
]
}
install_images = [ "system" ]
install_enable = true
part_name = "init"
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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
......@@ -15,6 +15,11 @@
#ifndef __BEGETCTL_CMD_H
#define __BEGETCTL_CMD_H
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "shell.h"
#ifdef __cplusplus
#if __cplusplus
......@@ -26,8 +31,14 @@ typedef int (*BegetCtlCmdPtr)(int argc, char **argv);
int BegetCtlCmdAdd(const char *name, BegetCtlCmdPtr cmd);
#define MODULE_CONSTRUCTOR() static void _init(void) __attribute__((constructor)); static void _init(void)
#define MODULE_DESTRUCTOR() static void _destroy(void) __attribute__((destructor)); static void _destroy(void)
#define MODULE_CONSTRUCTOR(void) static void _init(void) __attribute__((constructor)); static void _init(void)
#define MODULE_DESTRUCTOR(void) static void _destroy(void) __attribute__((destructor)); static void _destroy(void)
BShellHandle GetShellHandle(void);
void demoExit(void);
int SetParamShellPrompt(BShellHandle shell, const char *param);
int32_t BShellParamCmdRegister(BShellHandle shell, int execMode);
#ifdef __cplusplus
#if __cplusplus
......
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Copyright (c) 2022 Huawei Device Co., Ltd.
* 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
......@@ -20,27 +20,10 @@
#include "begetctl.h"
#define REBOOT_CMD_NUMBER 2
#ifdef PRODUCT_RK
#define USAGE_INFO "usage: reboot shutdown\n"\
" reboot updater\n"\
" reboot updater[:options]\n" \
" reboot flashd\n" \
" reboot flashd[:options]\n" \
" reboot loader\n" \
" reboot\n"
#else
#define USAGE_INFO "usage: reboot shutdown\n"\
" reboot updater\n"\
" reboot updater[:options]\n" \
" reboot flashd\n" \
" reboot flashd[:options]\n" \
" reboot\n"
#endif
static int main_cmd(int argc, char* argv[])
static int main_cmd(BShellHandle shell, int argc, char* argv[])
{
if (argc > REBOOT_CMD_NUMBER) {
printf("%s", USAGE_INFO);
BShellCmdHelp(shell, argc, argv);
return 0;
}
......@@ -52,7 +35,7 @@ static int main_cmd(int argc, char* argv[])
#endif
strncmp(argv[1], "updater:", strlen("updater:")) != 0 &&
strncmp(argv[1], "flashd:", strlen("flashd:")) != 0) {
printf("%s", USAGE_INFO);
BShellCmdHelp(shell, argc, argv);
return 0;
}
int ret;
......@@ -72,8 +55,20 @@ static int main_cmd(int argc, char* argv[])
return 0;
}
MODULE_CONSTRUCTOR()
MODULE_CONSTRUCTOR(void)
{
(void)BegetCtlCmdAdd("reboot", main_cmd);
(void)BegetCtlCmdAdd("devctl", main_cmd);
CmdInfo infos[] = {
{"reboot", main_cmd, "reboot system", "reboot", ""},
{"reboot", main_cmd, "shutdown system", "reboot shutdown", ""},
{"reboot", main_cmd, "reboot and boot into updater", "reboot updater", ""},
{"reboot", main_cmd, "reboot and boot into updater", "reboot updater[:options]", ""},
{"reboot", main_cmd, "reboot and boot into flashd", "reboot flashd", ""},
{"reboot", main_cmd, "reboot and boot into flashd", "reboot flashd[:options]", ""},
#ifdef PRODUCT_RK
{"reboot", main_cmd, "reboot loader", "reboot loader", ""}
#endif
};
for (size_t i = sizeof(infos) / sizeof(infos[0]); i > 0; i--) {
BShellEnvRegitsterCmd(GetShellHandle(), &infos[i - 1]);
}
}
......@@ -12,77 +12,44 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "begetctl.h"
struct CMD_LIST_ST {
struct CMD_LIST_ST *next;
const char *name;
BegetCtlCmdPtr cmd;
};
static struct CMD_LIST_ST *m_cmdList = NULL;
#include "begetctl.h"
#include "shell.h"
#include "shell_utils.h"
#include "sys_param.h"
int BegetCtlCmdAdd(const char *name, BegetCtlCmdPtr cmd)
static BShellHandle g_handle = NULL;
static int32_t ShellOuput(const char *data, int32_t len)
{
if (name == NULL) {
return -1;
}
struct CMD_LIST_ST *item = (struct CMD_LIST_ST *)malloc(sizeof(struct CMD_LIST_ST));
if (item == NULL) {
return -1;
}
item->name = strdup(name);
if (item->name == NULL) {
free((void *)item);
return -1;
for (int32_t i = 0; i < len; i++) {
putchar(*(data + i));
}
item->cmd = cmd;
item->next = m_cmdList;
m_cmdList = item;
return 0;
(void)fflush(stdout);
return len;
}
static const struct CMD_LIST_ST *BegetCtlCmdFind(const char *name)
BShellHandle GetShellHandle(void)
{
const struct CMD_LIST_ST *item = m_cmdList;
while (item != NULL) {
if (strcmp(item->name, name) == 0) {
return item;
}
item = item->next;
if (g_handle == NULL) {
BShellInfo info = {PARAM_SHELL_DEFAULT_PROMPT, NULL, ShellOuput};
BShellEnvInit(&g_handle, &info);
}
return NULL;
return g_handle;
}
static void BegetCtlUsage(const char *command)
static void signalHandler(int signal)
{
const struct CMD_LIST_ST *item = m_cmdList;
int notFirst = 0;
while (item != NULL) {
if (notFirst) {
printf(" ");
}
notFirst = 1;
printf("%s", item->name);
item = item->next;
}
printf("\n");
demoExit();
exit(0);
}
int main(int argc, char **argv)
int main(int argc, char *argv[])
{
(void)signal(SIGINT, signalHandler);
const char *last = strrchr(argv[0], '/');
// Get the first ending command name
if (last != NULL) {
last = last + 1;
......@@ -91,19 +58,15 @@ int main(int argc, char **argv)
}
// If it is begetctl with subcommand name, try to do subcommand first
int number = argc;
char **args = argv;
if ((argc > 1) && (strcmp(last, "begetctl") == 0)) {
argc = argc - 1;
argv = argv + 1;
last = argv[0];
}
// Match the command
const struct CMD_LIST_ST *cmd = BegetCtlCmdFind(last);
if (cmd == NULL) {
BegetCtlUsage(last);
return 0;
number = argc - 1;
args = argv + 1;
}
// Do command
return cmd->cmd(argc, argv);
SetInitLogLevel(0);
BShellParamCmdRegister(g_handle, 0);
BShellEnvDirectExecute(g_handle, number, args);
demoExit();
return 0;
}
......@@ -14,6 +14,8 @@
*/
#include <cerrno>
#include <cstdlib>
#include <cstdio>
#include <cstdint>
#include <fcntl.h>
#include <getopt.h>
......@@ -21,9 +23,12 @@
#include <string>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
#include "begetctl.h"
#include "sys_param.h"
#include "fs_manager/fs_manager.h"
#include "param_wrapper.h"
#include "begetctl.h"
constexpr int MAX_LOGO_SIZE = 1024 * 2038;
constexpr int PARTITION_INFO_POS = 1144;
......@@ -40,12 +45,14 @@ static std::string GetMiscDevicePath()
{
std::string miscDev {};
// Get misc device path from fstab
std::string hardwareVal {};
int ret = OHOS::system::GetStringParameter("ohos.boot.hardware", hardwareVal, "");
uint32_t size = PARAM_VALUE_LEN_MAX;
std::vector<char> buffer(PARAM_VALUE_LEN_MAX);
int ret = SystemGetParameter((char *)"ohos.boot.hardware", buffer.data(), &size);
if (ret != 0) {
std::cout << "get ohos.boot.hardware failed\n";
return "";
}
std::string hardwareVal(buffer.data());
std::string fstabFileName = std::string("fstab.") + hardwareVal;
std::string fstabFile = std::string("/vendor/etc/") + fstabFileName;
Fstab *fstab = ReadFstabFromFile(fstabFile.c_str(), false);
......@@ -225,7 +232,7 @@ static void WriteLogoToMisc(const std::string &logoPath)
close(fd1);
}
static int main_cmd(int argc, char **argv)
static int main_cmd(BShellHandle shell, int argc, char **argv)
{
int rc = -1;
int optIndex = -1;
......@@ -250,7 +257,15 @@ static int main_cmd(int argc, char **argv)
return 0;
}
MODULE_CONSTRUCTOR()
MODULE_CONSTRUCTOR(void)
{
(void)BegetCtlCmdAdd("misc_daemon", main_cmd);
CmdInfo infos[] = {
{
(char *)"misc_daemon", main_cmd, (char *)"write start logo",
(char *)"misc_daemon --write_logo xxx.rgb", (char *)"misc_daemon --write_logo"
}
};
for (size_t i = 0; i < sizeof(infos) / sizeof(infos[0]); i++) {
BShellEnvRegitsterCmd(GetShellHandle(), &infos[i]);
}
}
此差异已折叠。
......@@ -12,90 +12,55 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "service_control.h"
#include <string.h>
#include <stdio.h>
#include <string.h>
#include "begetctl.h"
#include "securec.h"
#include "sys_param.h"
#include "begetctl.h"
#define SERVICE_START_NUMBER 2
#define SERVICE_CONTROL_NUMBER 3
#define CONTROL_SERVICE_POS 2
#define SERVICE_CONTROL_MAX_SIZE 50
static void ServiceControlUsage()
static void ServiceControlUsage(BShellHandle shell, int argc, char **argv)
{
printf("Please input correct params, example:\n");
printf(" start_service serviceName\n");
printf(" stop_service serviceName\n");
printf(" service_control start serviceName\n");
printf(" service_control stop serviceName\n");
BShellCmdHelp(shell, argc, argv);
return;
}
static void ServiceControl(int argc, char** argv)
static int main_cmd(BShellHandle shell, int argc, char **argv)
{
if (argc != SERVICE_CONTROL_NUMBER) {
ServiceControlUsage();
return;
}
char serviceCtl[SERVICE_CONTROL_MAX_SIZE];
if (strcmp(argv[1], "start") == 0) {
if (strncpy_s(serviceCtl, sizeof(serviceCtl), "ohos.ctl.start", sizeof(serviceCtl) - 1) != EOK) {
printf("strncpy_s failed.\n");
return;
}
} else if (strcmp(argv[1], "stop") == 0) {
if (strncpy_s(serviceCtl, sizeof(serviceCtl), "ohos.ctl.stop", sizeof(serviceCtl) - 1) != EOK) {
printf("strncpy_s failed.\n");
return;
}
} else {
ServiceControlUsage();
return;
}
if (SystemSetParameter(serviceCtl, argv[CONTROL_SERVICE_POS]) != 0) {
printf("%s service:%s failed.\n", argv[1], argv[CONTROL_SERVICE_POS]);
return;
}
return;
}
static int main_cmd(int argc, char** argv)
{
if (argc != SERVICE_START_NUMBER && argc != SERVICE_CONTROL_NUMBER) {
ServiceControlUsage();
return -1;
if (argc < SERVICE_START_NUMBER) {
ServiceControlUsage(shell, argc, argv);
return 0;
}
char serviceCtl[SERVICE_CONTROL_MAX_SIZE];
if (strcmp(argv[0], "start_service") == 0) {
if (strncpy_s(serviceCtl, sizeof(serviceCtl), "ohos.ctl.start", sizeof(serviceCtl) - 1) != EOK) {
printf("strncpy_s failed.\n");
return -1;
}
ServiceControlWithExtra(argv[1], 0, (const char **)argv + SERVICE_START_NUMBER, argc - SERVICE_START_NUMBER);
} else if (strcmp(argv[0], "stop_service") == 0) {
if (strncpy_s(serviceCtl, sizeof(serviceCtl), "ohos.ctl.stop", sizeof(serviceCtl) - 1) != EOK) {
printf("strncpy_s failed.\n");
return -1;
}
ServiceControlWithExtra(argv[1], 1, (const char **)argv + SERVICE_START_NUMBER, argc - SERVICE_START_NUMBER);
} else if (strcmp(argv[0], "start") == 0) {
ServiceControlWithExtra(argv[1], 0, (const char **)argv + SERVICE_START_NUMBER, argc - SERVICE_START_NUMBER);
} else if (strcmp(argv[0], "stop") == 0) {
ServiceControlWithExtra(argv[1], 1, (const char **)argv + SERVICE_START_NUMBER, argc - SERVICE_START_NUMBER);
} else {
ServiceControl(argc, argv);
return 0;
}
if (SystemSetParameter(serviceCtl, argv[1]) != 0) {
printf("%s service:%s failed.\n", argv[0], argv[1]);
return -1;
ServiceControlUsage(shell, argc, argv);
}
return 0;
}
MODULE_CONSTRUCTOR()
MODULE_CONSTRUCTOR(void)
{
(void)BegetCtlCmdAdd("service", main_cmd);
(void)BegetCtlCmdAdd("service_control", main_cmd);
(void)BegetCtlCmdAdd("start_service", main_cmd);
(void)BegetCtlCmdAdd("stop_service", main_cmd);
CmdInfo infos[] = {
{"service_control", main_cmd, "stop service", "service_control stop servicename", "service_control stop"},
{"service_control", main_cmd, "start service", "service_control start servicename", "service_control start"},
{"stop_service", main_cmd, "stop service", "stop_service servicename", ""},
{"start_service", main_cmd, "start service", "start_service servicename", ""}
};
for (size_t i = 0; i < sizeof(infos) / sizeof(infos[0]); i++) {
BShellEnvRegitsterCmd(GetShellHandle(), &infos[i]);
}
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _BSHELL_H_
#define _BSHELL_H_
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
#define PARAM_REVERESD_NAME_CURR_PARAMETER "_current_param_"
#define PARAM_SHELL_DEFAULT_PROMPT "param#"
typedef struct BShellEnv_ *BShellHandle;
typedef int32_t (*BShellCmdExecuter_)(BShellHandle handle, int32_t argc, char *argv[]);
typedef int32_t (*BShellInput_)(char *, int32_t);
typedef int32_t (*BShellOutput_)(const char *, int32_t);
typedef int32_t (*BShellkeyHandle)(BShellHandle, uint8_t code);
typedef enum {
BSH_ERRNO_BASE = 1000,
BSH_SHELL_INFO,
BSH_INVALID_PARAM,
BSH_CMD_TOO_LONG,
BSH_SHOW_CMD_LIST,
BSH_CMD_NOT_EXIST,
BSH_CMD_PARAM_INVALID,
BSH_SYSTEM_ERR,
} BShellErrNo;
typedef struct BShellErrInfo_ {
BShellErrNo err;
char *desc;
} BShellErrInfo;
typedef struct CmdInfo_ {
char *name;
BShellCmdExecuter_ executer;
char *desc;
char *help;
char *multikey;
} CmdInfo;
typedef enum {
PARAM_INT8 = 0,
PARAM_INT16,
PARAM_INT32,
PARAM_STRING,
} BShellParamType;
typedef struct ParamInfo_ {
char *name;
char *desc;
BShellParamType type;
} ParamInfo;
typedef struct BShellParam_ {
char *desc;
BShellParamType type;
union {
char data;
uint8_t data8;
uint16_t data16;
uint32_t data32;
char *string;
} value;
struct BShellParam_ *next;
char name[0];
} BShellParam;
typedef struct BShellInfo_ {
char *prompt;
BShellInput_ input;
BShellOutput_ output;
} BShellInfo;
int BShellEnvInit(BShellHandle *handle, BShellInfo *info);
int BShellEnvStart(BShellHandle handle);
void BShellEnvDestory(BShellHandle handle);
int BShellEnvRegitsterCmd(BShellHandle handle, CmdInfo *cmdInfo);
int BShellEnvSetParam(BShellHandle handle, const char *name, const char *desc, BShellParamType type, void *value);
const BShellParam *BShellEnvGetParam(BShellHandle handle, const char *name);
int BShellEnvRegisterKeyHandle(BShellHandle handle, uint8_t code, BShellkeyHandle keyHandle);
void BShellEnvLoop(BShellHandle handle);
const ParamInfo *BShellEnvGetReservedParam(BShellHandle handle, const char *name);
int32_t BShellEnvOutput(BShellHandle handle, char *fmt, ...);
int32_t BShellEnvOutputString(BShellHandle handle, const char *string);
int32_t BShellEnvOutputPrompt(BShellHandle handle, const char *prompt);
int32_t BShellCmdHelp(BShellHandle handle, int32_t argc, char *argv[]);
int32_t BShellEnvDirectExecute(BShellHandle handle, int argc, char *args[]);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
#endif
\ No newline at end of file
此差异已折叠。
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BSHELL_BAS_H
#define BSHELL_BAS_H
#include <stdint.h>
#include <stdlib.h>
#include "shell.h"
#define BSH_VERSION "0.0.1"
#define BSH_KEY_LF 0x0A
#define BSH_KEY_CR 0x0D
#define BSH_KEY_TAB 0x09
#define BSH_KEY_BACKSPACE 0x08
#define BSH_KEY_DELETE 0x7F
#define BSH_KEY_CTRLC 0x03 // ctr + c
#define BSH_KEY_ESC 0x1B // ecs
#define BSH_COMMAND_MAX_LENGTH 256
#define BSH_PARAMETER_MAX_NUMBER 10
#define BSH_CMD_NAME_END 48
#define BSH_CMD_MAX_KEY 5
typedef enum {
BSH_IN_NORMAL = 0,
BSH_ANSI_ESC,
BSH_ANSI_CSI,
} BShellState;
typedef enum {
BSH_EXEC_TASK = 0,
BSH_EXEC_INDEPENDENT,
} BShellExecMode;
typedef struct BShellCommand_ {
char *desc;
char *help;
BShellCmdExecuter_ executer;
struct BShellCommand_ *next;
char *multikey;
char *multikeys[BSH_CMD_MAX_KEY];
uint8_t argStart;
char name[0];
} BShellCommand;
typedef struct {
uint8_t shellState : 2;
uint8_t tabFlag : 1;
} BShellStatus;
typedef struct BShellKey_ {
uint8_t keyCode;
BShellkeyHandle keyHandle;
struct BShellKey_ *next;
} BShellKey;
typedef struct BShellEnv_ {
char *prompt;
char buffer[BSH_COMMAND_MAX_LENGTH];
uint16_t length;
uint16_t cursor;
char *args[BSH_PARAMETER_MAX_NUMBER];
uint8_t argc;
uint8_t shellState : 3;
uint8_t execMode : 2;
BShellCommand *command;
BShellParam *param;
BShellKey *keyHandle;
BShellStatus status;
BShellInput_ input;
BShellOutput_ output;
char data[BSH_COMMAND_MAX_LENGTH];
} BShellEnv;
BShellKey *BShellEnvGetKey(BShellHandle handle, uint8_t code);
BShellCommand *BShellEnvGetCmd(BShellHandle handle, int32_t argc, char *argv[]);
int32_t BShellEnvOutputString(BShellHandle handle, const char *string);
void BShellEnvOutputByte(BShellHandle handle, char data);
void BShellEnvOutputResult(BShellHandle handle, int32_t result);
char *BShellEnvErrString(BShellHandle handle, int32_t err);
const char *BShellEnvGetStringParam(BShellHandle handle, const char *name);
#endif
\ No newline at end of file
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include "begetctl.h"
#include "shell.h"
#include "shell_utils.h"
static BShellHandle g_handle = NULL;
struct termios terminalState;
static void signalHandler(int signal)
{
tcsetattr(0, TCSAFLUSH, &terminalState);
demoExit();
exit(0);
}
static int32_t ShellOuput(const char *data, int32_t len)
{
for (int32_t i = 0; i < len; i++) {
putchar(*(data + i));
}
(void)fflush(stdout);
return len;
}
static int32_t ShellInput(char *data, int32_t len)
{
for (int32_t i = 0; i < len; i++) {
data[i] = getchar();
}
return len;
}
BShellHandle GetShellHandle(void)
{
if (g_handle == NULL) {
BShellInfo info = {PARAM_SHELL_DEFAULT_PROMPT, ShellInput, ShellOuput};
BShellEnvInit(&g_handle, &info);
}
return g_handle;
}
int main(int argc, char *args[])
{
(void)signal(SIGINT, signalHandler);
(void)signal(SIGKILL, signalHandler);
if (tcgetattr(0, &terminalState)) {
return -1;
}
struct termios tio;
if (tcgetattr(0, &tio)) {
return -1;
}
tio.c_lflag &= ~(ECHO | ICANON | ISIG);
tio.c_cc[VTIME] = 0;
tio.c_cc[VMIN] = 1;
tcsetattr(0, TCSAFLUSH, &tio);
SetInitLogLevel(0);
BSH_LOGV("BShellEnvStart %d", argc);
do {
if (g_handle == NULL) {
BShellInfo info = {PARAM_SHELL_DEFAULT_PROMPT, ShellInput, ShellOuput};
BShellEnvInit(&g_handle, &info);
}
const ParamInfo *param = BShellEnvGetReservedParam(g_handle, PARAM_REVERESD_NAME_CURR_PARAMETER);
BSH_CHECK(param != NULL && param->type == PARAM_STRING, break, "Failed to get revered param");
BShellEnvSetParam(g_handle, param->name, param->desc, param->type, (void *)"");
if (argc > 1) {
int ret = SetParamShellPrompt(g_handle, args[1]);
if (ret != 0) {
break;
}
}
BShellParamCmdRegister(g_handle, 1);
BShellEnvStart(g_handle);
BShellEnvLoop(g_handle);
} while (0);
demoExit();
tcsetattr(0, TCSAFLUSH, &terminalState);
return 0;
}
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BSHELL_UTILS_
#define BSHELL_UTILS_
#include <memory.h>
#include <stdint.h>
#include <stdio.h>
#include "init_log.h"
#include "securec.h"
#define BSH_LOG_FILE "paramshell.log"
#define BSH_LABEL "SHELL"
#define BSH_LOGI(fmt, ...) STARTUP_LOGI(BSH_LOG_FILE, BSH_LABEL, fmt, ##__VA_ARGS__)
#define BSH_LOGE(fmt, ...) STARTUP_LOGE(BSH_LOG_FILE, BSH_LABEL, fmt, ##__VA_ARGS__)
#define BSH_LOGV(fmt, ...) STARTUP_LOGV(BSH_LOG_FILE, BSH_LABEL, fmt, ##__VA_ARGS__)
#define BSH_CHECK(ret, exper, ...) \
if (!(ret)) { \
BSH_LOGE(__VA_ARGS__); \
exper; \
}
#define BSH_ONLY_CHECK(ret, exper, ...) \
if (!(ret)) { \
exper; \
}
#endif
\ No newline at end of file
{
"jobs": [
],
"services": [
],
"groups": [
]
}
\ No newline at end of file
......@@ -27,7 +27,6 @@ net_bw_acct:x:3007:
readproc:x:3009:
wakelock:x:3010:
uhid:x:3011:
ddms:x:3012:
access_token:x:3020:
misc:x:9998:
app:x:10000:
......@@ -186,36 +186,6 @@
"start misc",
"chown system system /data",
"chmod 0771 /data",
"mkdir /data/app 0711 root root",
"mkdir /data/app/el1 0711 root root",
"mkdir /data/app/el1/bundle 0711 root root",
"mkdir /data/app/el2 0711 root root",
"mkdir /data/app/el3 0711 root root",
"mkdir /data/app/el4 0711 root root",
"mkdir /data/service 0711 root root",
"mkdir /data/service/el0 0711 root root",
"mkdir /data/service/el1 0711 root root",
"mkdir /data/service/el1/public 0711 root root",
"mkdir /data/service/el2 0711 root root",
"mkdir /data/chipset 0711 root root",
"mkdir /data/chipset/el1 0711 root root",
"mkdir /data/chipset/el1/public 0711 root root",
"mkdir /data/chipset/el2 0711 root root",
"mkdir /data/app/el1/0 0711 root root",
"mkdir /data/app/el1/0/base 0711 root root",
"mkdir /data/app/el1/0/database 0711 system system",
"mkdir /data/app/el2/0 0711 root root",
"mkdir /data/app/el2/0/base 0711 root root",
"mkdir /data/app/el2/0/database 0711 system system",
"mkdir /data/app/el3/0 0711 root root",
"mkdir /data/app/el3/0/base 0711 root root",
"mkdir /data/app/el4/0 0711 root root",
"mkdir /data/app/el4/0/base 0711 root root",
"mkdir /data/service/el1/0 0711 root root",
"mkdir /data/service/el2/0 0711 root root",
"mkdir /data/service/el2/0/hmdfs 0711 system system",
"mkdir /data/chipset/el1/0 0711 root root",
"mkdir /data/chipset/el2/0 0711 root root",
"mkdir /data/bootchart 0755 shell shell",
"mkdir /data/app-staging 0750 system system",
"copy /data/system/entropy.dat /dev/urandom",
......
......@@ -14,12 +14,6 @@
"cmds" : [
"stop hdcd"
]
}, {
"name" : "param:sys.usb.config=hdc && param:sys.usb.configfs=0",
"condition" : "sys.usb.config=hdc && sys.usb.configfs=0",
"cmds" : [
"start hdcd"
]
}
],
"services" : [{
......
......@@ -186,36 +186,6 @@
"start misc",
"chown system system /data",
"chmod 0771 /data",
"mkdir /data/app 0711 root root",
"mkdir /data/app/el1 0711 root root",
"mkdir /data/app/el1/bundle 0711 root root",
"mkdir /data/app/el2 0711 root root",
"mkdir /data/app/el3 0711 root root",
"mkdir /data/app/el4 0711 root root",
"mkdir /data/service 0711 root root",
"mkdir /data/service/el0 0711 root root",
"mkdir /data/service/el1 0711 root root",
"mkdir /data/service/el1/public 0711 root root",
"mkdir /data/service/el2 0711 root root",
"mkdir /data/chipset 0711 root root",
"mkdir /data/chipset/el1 0711 root root",
"mkdir /data/chipset/el1/public 0711 root root",
"mkdir /data/chipset/el2 0711 root root",
"mkdir /data/app/el1/0 0711 root root",
"mkdir /data/app/el1/0/base 0711 root root",
"mkdir /data/app/el1/0/database 0711 system system",
"mkdir /data/app/el2/0 0711 root root",
"mkdir /data/app/el2/0/base 0711 root root",
"mkdir /data/app/el2/0/database 0711 system system",
"mkdir /data/app/el3/0 0711 root root",
"mkdir /data/app/el3/0/base 0711 root root",
"mkdir /data/app/el4/0 0711 root root",
"mkdir /data/app/el4/0/base 0711 root root",
"mkdir /data/service/el1/0 0711 root root",
"mkdir /data/service/el2/0 0711 root root",
"mkdir /data/service/el2/0/hmdfs 0711 system system",
"mkdir /data/chipset/el1/0 0711 root root",
"mkdir /data/chipset/el2/0 0711 root root",
"mkdir /data/bootchart 0755 shell shell",
"mkdir /data/app-staging 0750 system system",
"copy /data/system/entropy.dat /dev/urandom",
......
......@@ -27,7 +27,6 @@ net_bw_acct:x:3007:3007:::/bin/false
readproc:x:3009:3009:::/bin/false
wakelock:x:3010:3010:::/bin/false
uhid:x:3011:3011:::/bin/false
ddms:x:3012:3012:::/bin/false
access_token:x:3020:3020:::/bin/false
misc:x:9998:9998:::/bin/false
app:x:10000:10000:::/bin/false
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INIT_HASH_MAP_
#define INIT_HASH_MAP_
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "init_log.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
#define HASH_TAB_BUCKET_MAX 1024
#define HASH_TAB_BUCKET_MIN 16
typedef struct HashNode_ {
struct HashNode_ *next;
} HashNode;
#define HASHMAP_ENTRY(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member)))
#define HASHMAPInitNode(node) (node)->next = NULL
typedef int (*HashNodeCompare)(const HashNode *node1, const HashNode *node2);
typedef int (*HashKeyCompare)(const HashNode *node1, const void *key);
typedef int (*HashNodeFunction)(const HashNode *node);
typedef int (*HashKeyFunction)(const void *key);
typedef void (*HashNodeOnFree)(const HashNode *node);
typedef struct {
HashNodeCompare nodeCompare;
HashKeyCompare keyCompare;
HashNodeFunction nodeHash;
HashKeyFunction keyHash;
HashNodeOnFree nodeFree;
int maxBucket;
} HashInfo;
typedef void *HashMapHandle;
int32_t HashMapCreate(HashMapHandle *handle, const HashInfo *info);
void HashMapDestory(HashMapHandle handle);
int32_t HashMapAdd(HashMapHandle handle, HashNode *hashNode);
void HashMapRemove(HashMapHandle handle, const void *key);
HashNode *HashMapGet(HashMapHandle handle, const void *key);
HashNode *HashMapFind(HashMapHandle handle,
int hashCode, const void *key, HashKeyCompare keyCompare);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
#endif
\ No newline at end of file
......@@ -25,13 +25,16 @@ extern "C" {
#endif
#endif
typedef struct {
char *name;
int value;
} InitArgInfo;
#define BINARY_BASE 2
#define OCTAL_BASE 8
#define DECIMAL_BASE 10
#define WAIT_MAX_COUNT 10
#define MAX_BUFFER_LEN 256
#define CMDLINE_VALUE_LEN_MAX 512
#define PARAM_CMD_LINE "/proc/cmdline"
#define ARRAY_LENGTH(array) (sizeof((array)) / sizeof((array)[0]))
uid_t DecodeUid(const char *name);
char *ReadFileToBuf(const char *configFile);
......@@ -50,9 +53,9 @@ int ReadFileInDir(const char *dirPath, const char *includeExt,
char **SplitStringExt(char *buffer, const char *del, int *returnCount, int maxItemCount);
void FreeStringVector(char **vector, int count);
int InUpdaterMode(void);
int InChargerMode(void);
int StringReplaceChr(char *strl, char oldChr, char newChr);
int GetMapValue(const char *name, const InitArgInfo *infos, int argNum, int defValue);
#ifdef __cplusplus
#if __cplusplus
}
......
......@@ -15,6 +15,7 @@
#ifndef BASE_STARTUP_INITLITE_LIST_H
#define BASE_STARTUP_INITLITE_LIST_H
#include <stddef.h>
#ifdef __cplusplus
#if __cplusplus
......@@ -25,7 +26,7 @@ extern "C" {
typedef struct ListNode {
struct ListNode *next;
struct ListNode *prev;
} ListNode;
} ListNode, ListHead;
#define ListEmpty(node) ((node).next == &(node) && (node).prev == &(node))
#define ListEntry(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member)))
......
......@@ -86,7 +86,7 @@ void PostTrigger(EventType type, const char *content, uint32_t contentLen);
* 解析trigger文件。
*
*/
int ParseTriggerConfig(const cJSON *fileRoot);
int ParseTriggerConfig(const cJSON *fileRoot, int (*checkJobValid)(const char *jobName));
/**
* 对Init接口
......@@ -94,6 +94,14 @@ int ParseTriggerConfig(const cJSON *fileRoot);
*
*/
void DoTriggerExec(const char *triggerName);
void DoJobExecNow(const char *triggerName);
/**
* 对Init接口
* 按名字添加一个job,用于group支持。
*
*/
int AddCompleteJob(const char *name, const char *condition, const char *cmdContent);
/**
* 对Init接口
......@@ -102,6 +110,7 @@ void DoTriggerExec(const char *triggerName);
*/
void DumpParametersAndTriggers(void);
void RegisterBootStateChange(void (*bootStateChange)(const char *));
#ifdef __cplusplus
#if __cplusplus
}
......
......@@ -41,6 +41,7 @@ typedef enum {
PARAM_CODE_NOT_FOUND,
PARAM_CODE_READ_ONLY,
PARAM_CODE_FAIL_CONNECT,
PARAM_CODE_NODE_EXIST,
PARAM_CODE_MAX
} PARAM_CODE;
......
......@@ -65,7 +65,8 @@ int SystemGetParameterCommitId(ParamHandle handle, uint32_t *commitId);
* 遍历参数。
*
*/
int SystemTraversalParameter(void (*traversalParameter)(ParamHandle handle, void *cookie), void *cookie);
int SystemTraversalParameter(const char *prefix,
void (*traversalParameter)(ParamHandle handle, void *cookie), void *cookie);
/**
* 外部接口
......@@ -95,6 +96,7 @@ int SystemWatchParameter(const char *keyprefix, ParameterChangePtr change, void
void SystemDumpParameters(int verbose);
int SysCheckParamExist(const char *name);
#ifdef __cplusplus
#if __cplusplus
}
......
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BASE_STARTUP_INITLITE_FD_HOLDER_SERVICE_H
#define BASE_STARTUP_INITLITE_FD_HOLDER_SERVICE_H
#ifdef __cplusplus
extern "C" {
#endif
void RegisterFdHoldWatcher(int sock);
#ifdef __cplusplus
extern "C" {
#endif
#endif // BASE_STARTUP_INITLITE_FD_HOLDER_SERVICE_H
/*
* Copyright (c) 2020-2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef STARTUP_INIT_GROUP_MANAGER_H
#define STARTUP_INIT_GROUP_MANAGER_H
#include <stdlib.h>
#include <string.h>
#include "init_service.h"
#include "init_hashmap.h"
#include "init_plugin_manager.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
#define GROUP_IMPORT_MAX_LEVEL 5
#define GROUP_NAME_MAX_LENGTH 64
#define GROUP_HASHMAP_BUCKET 32
#ifdef STARTUP_INIT_TEST
#define GROUP_DEFAULT_PATH "/home/axw/init_ut" // "/system/init"
#define BOOT_CMD_LINE GROUP_DEFAULT_PATH "/proc/cmdline"
#else
#define GROUP_DEFAULT_PATH "/system/etc"
#define BOOT_CMD_LINE "/proc/cmdline"
#endif
#define BOOT_GROUP_NAME "bootgroup"
#define BOOT_GROUP_DEFAULT "device.boot.group"
typedef enum {
GROUP_BOOT,
GROUP_CHARING,
GROUP_UPDATER,
GROUP_UNKNOW
} InitGroupType;
typedef enum {
NODE_TYPE_JOBS,
NODE_TYPE_SERVICES,
NODE_TYPE_PLUGINS,
NODE_TYPE_CMDS,
NODE_TYPE_GROUPS,
NODE_TYPE_MAX
} InitNodeType;
typedef struct InitGroupNode_ {
struct InitGroupNode_ *next;
HashNode hashNode;
unsigned char type;
union {
Service *service;
PluginInfo *pluginInfo;
PluginCmd *cmd;
} data;
char name[0];
} InitGroupNode;
typedef struct {
uint8_t initFlags;
InitGroupType groupMode;
InitGroupNode *groupNodes[NODE_TYPE_MAX];
HashMapHandle hashMap[NODE_TYPE_GROUPS];
char groupModeStr[GROUP_NAME_MAX_LENGTH];
} InitWorkspace;
void InitServiceSpace(void);
int InitParseGroupCfg(void);
int GenerateHashCode(const char *key);
InitGroupNode *AddGroupNode(int type, const char *name);
InitGroupNode *GetGroupNode(int type, const char *name);
InitGroupNode *GetNextGroupNode(int type, const InitGroupNode *curr);
void DelGroupNode(int type, const char *name);
int CheckNodeValid(int type, const char *name);
HashMapHandle GetGroupHashMap(int type);
#ifdef STARTUP_INIT_TEST
InitWorkspace *GetInitWorkspace(void);
#endif
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
#endif // STARTUP_INIT_GROUP_MANAGER_H
......@@ -36,13 +36,14 @@ void DoJob(const char *jobName);
void ReleaseAllJobs(void);
void DumpAllJobs(void);
int DoJobNow(const char *jobName);
#ifndef DISABLE_INIT_TWO_STAGES
#define INIT_CONFIGURATION_FILE "/etc/init.cfg"
#else
#define INIT_CONFIGURATION_FILE "/etc/init.without_two_stages.cfg"
#endif
#define OTHER_CFG_PATH "/system/etc/init"
#define OTHER_CHARGE_PATH "/system/etc/charge"
#define MAX_PATH_ARGS_CNT 20
void ReadConfig(void);
......
/*
* Copyright (c) 2020-2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef STARTUP_INIT_PULUGIN_MANAGER_H
#define STARTUP_INIT_PULUGIN_MANAGER_H
#include <stdlib.h>
#include <string.h>
#include "init_plugin.h"
#include "list.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
#define DEFAULT_PLUGIN_PATH "/system/lib/plugin"
typedef enum {
PLUGIN_STATE_IDLE,
PLUGIN_STATE_INIT,
PLUGIN_STATE_RUNNING,
PLUGIN_STATE_DESTORYED
} PluginState;
typedef struct PluginInfo_ {
int state;
int (*pluginInit)();
void (*pluginExit)();
char *name;
} PluginInfo;
typedef struct {
ListNode cmdExecutor;
int cmdId;
char *name;
} PluginCmd;
typedef void (*CmdExecutor)(int id, const char *name, int argc, const char **argv);
typedef struct {
ListNode node;
int id;
CmdExecutor execCmd;
} PluginCmdExecutor;
void PluginExecCmdByName(const char *name, const char *cmdContent);
void PluginExecCmdByCmdIndex(int index, const char *cmdContent);
const char *PluginGetCmdIndex(const char *cmdStr, int *index);
int PluginUninstall(const char *name);
int PluginInstall(const char *name);
void PluginManagerInit(void);
int AddCmdExecutor(const char *cmdName, CmdExecutor execCmd);
int ParseInitCfg(const char *configFile, void *context);
typedef PluginInterface *(*GetPluginInterfaceFunc)();
int SetPluginInterface(void);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
#endif // STARTUP_INIT_PULUGIN_MANAGER_H
......@@ -47,6 +47,8 @@ extern "C" {
#define SERVICE_ATTR_ONDEMAND 0x200 // ondemand, manage socket by init
#define MAX_SERVICE_NAME 32
#define MAX_APL_NAME 32
#define MAX_JOB_NAME 128
#define MAX_WRITEPID_FILES 100
#define FULL_CAP 0xFFFFFFFF
......@@ -57,6 +59,22 @@ extern "C" {
#define SERVICES_ARR_NAME_IN_JSON "services"
#define IsOnDemandService(service) \
(((service)->attribute & SERVICE_ATTR_ONDEMAND) == SERVICE_ATTR_ONDEMAND)
typedef enum {
START_MODE_CONDITION,
START_MODE_BOOT,
START_MODE_NARMAL,
} ServiceStartMode;
typedef enum {
END_PRE_FORK,
END_AFTER_FORK,
END_AFTER_EXEC,
END_RECV_READY,
} ServiceEndMode;
typedef struct {
uid_t uID;
gid_t *gIDArray;
......@@ -70,9 +88,20 @@ typedef struct {
char **argv;
} ServiceArgs;
typedef enum {
JOB_ON_BOOT,
JOB_ON_START,
JOB_ON_STOP,
JOB_ON_RESTART,
JOB_ON_MAX
} ServiceJobType;
typedef struct {
ListNode node;
char name[MAX_SERVICE_NAME + 1];
char *jobsName[JOB_ON_MAX];
} ServiceJobs;
typedef struct Service_ {
char *name;
#ifdef WITH_SELINUX
char secon[MAX_SECON_LEN];
#endif // WITH_SELINUX
......@@ -83,13 +112,20 @@ typedef struct {
int crashTime;
unsigned int attribute;
int importance;
int startMode : 4; // startCondition/ startBoot / startNormal
int endMode : 4; // preFork/ fork / exec / ready
Perms servPerm;
char apl[MAX_APL_NAME + 1];
ServiceArgs capsArgs;
ServiceArgs pathArgs;
ServiceArgs extraArgs;
ServiceArgs writePidArgs;
CmdLines *restartArg;
ServiceSocket *socketCfg;
ServiceFile *fileCfg;
int *fds;
size_t fdCount;
ServiceJobs serviceJobs;
} Service;
int ServiceStart(Service *service);
......@@ -102,6 +138,11 @@ int IsForbidden(const char *fieldStr);
int SetImportantValue(Service *curServ, const char *attrName, int value, int flag);
int GetServiceCaps(const cJSON *curArrItem, Service *curServ);
int ServiceExec(const Service *service);
void CloseServiceFds(Service *service, bool needFree);
int UpdaterServiceFds(Service *service, int *fds, size_t fdCount);
int ServiceAddWatcher(ServiceWatcher *watcherHandle, Service *service, int fd);
void ServiceDelWatcher(ServiceWatcher watcherHandle);
#ifdef __cplusplus
#if __cplusplus
......@@ -109,4 +150,4 @@ int ServiceExec(const Service *service);
#endif
#endif
#endif // BASE_STARTUP_INITLITE_SERVICE_H
#endif // BASE_STARTUP_INITLITE_SERVICE_H
\ No newline at end of file
......@@ -33,6 +33,8 @@ extern "C" {
#define CRITICAL_STR_IN_CFG "critical"
#define DISABLED_STR_IN_CFG "disabled"
#define CONSOLE_STR_IN_CFG "console"
#define D_CAPS_STR_IN_CFG "d-caps"
#define APL_STR_IN_CFG "apl"
#define MAX_SERVICES_CNT_IN_FILE 100
......@@ -42,7 +44,6 @@ typedef struct {
} CapStrCapNum;
typedef struct {
ListNode services;
int serviceCount;
} ServiceSpace;
......@@ -50,18 +51,13 @@ Service *GetServiceByPid(pid_t pid);
Service *GetServiceByName(const char *servName);
cJSON *GetArrayItem(const cJSON *fileRoot, int *arrSize, const char *arrName);
int ParseOneService(const cJSON *curItem, Service *service);
void SocketPollInit(int sockFd, const char* serviceName);
int CreateAndPollSocket(Service *service);
void StartServiceByName(const char *serviceName, bool checkDynamic);
void StopServiceByName(const char *serviceName);
void StopAllServices(int flags);
void ParseAllServices(const cJSON *fileRoot);
void ReleaseService(Service *service);
static inline bool IsOnDemandService(Service *service)
{
return !!(service->attribute & SERVICE_ATTR_ONDEMAND);
}
void StartAllServices(int startMode);
#ifdef OHOS_SERVICE_DUMP
void DumpAllServices();
......
......@@ -35,7 +35,8 @@ enum SockOptionTab {
SERVICE_SOCK_GID,
SERVICE_SOCK_SETOPT
};
typedef void *ServiceWatcher;
struct Service_;
typedef struct ServiceSocket_ {
struct ServiceSocket_ *next;
int type; // socket type
......@@ -44,11 +45,12 @@ typedef struct ServiceSocket_ {
bool passcred; // setsocketopt
mode_t perm; // Setting permissions
int sockFd;
ServiceWatcher watcher;
char name[0]; // service name
} ServiceSocket;
int CreateServiceSocket(ServiceSocket *sockopt);
void CloseServiceSocket(ServiceSocket *sockopt);
int CreateServiceSocket(struct Service_ *service);
void CloseServiceSocket(struct Service_ *service);
#ifdef __cplusplus
#if __cplusplus
......
......@@ -33,6 +33,7 @@
#include "init.h"
#include "init_jobs_internal.h"
#include "init_log.h"
#include "init_plugin_manager.h"
#include "init_service_manager.h"
#include "init_utils.h"
#include "securec.h"
......@@ -178,20 +179,20 @@ static void DoSleep(const struct CmdArgs *ctx)
static void DoStart(const struct CmdArgs *ctx)
{
INIT_LOGD("DoStart %s", ctx->argv[0]);
INIT_LOGV("DoStart %s", ctx->argv[0]);
StartServiceByName(ctx->argv[0], true);
}
static void DoStop(const struct CmdArgs *ctx)
{
INIT_LOGD("DoStop %s", ctx->argv[0]);
INIT_LOGV("DoStop %s", ctx->argv[0]);
StopServiceByName(ctx->argv[0]);
return;
}
static void DoReset(const struct CmdArgs *ctx)
{
INIT_LOGD("DoReset %s", ctx->argv[0]);
INIT_LOGV("DoReset %s", ctx->argv[0]);
Service *service = GetServiceByName(ctx->argv[0]);
if (service == NULL) {
INIT_LOGE("Reset cmd cannot find service %s.", ctx->argv[0]);
......@@ -461,6 +462,7 @@ static void DoSetrlimit(const struct CmdArgs *ctx)
for (unsigned int i = 0; i < ARRAY_LENGTH(resource); ++i) {
if (strcmp(ctx->argv[0], resource[i]) == 0) {
rcs = (int)i;
break;
}
}
if (rcs == -1) {
......@@ -572,7 +574,7 @@ const char *GetMatchCmd(const char *cmdStr, int *index)
return cmds[i].name;
}
}
return NULL;
return PluginGetCmdIndex(startCmd, index);
}
const char *GetCmdKey(int index)
......@@ -640,7 +642,11 @@ void DoCmdByName(const char *name, const char *cmdContent)
return;
}
const struct CmdTable *cmd = GetCmdByName(name);
ExecCmd(cmd, cmdContent);
if (cmd != NULL) {
ExecCmd(cmd, cmdContent);
return;
}
PluginExecCmdByName(name, cmdContent);
}
void DoCmdByIndex(int index, const char *cmdContent)
......@@ -660,4 +666,5 @@ void DoCmdByIndex(int index, const char *cmdContent)
ExecCmd(&cmds[index - cmdCnt], cmdContent);
return;
}
PluginExecCmdByCmdIndex(index, cmdContent);
}
此差异已折叠。
......@@ -23,8 +23,6 @@ static void ParseAllImports(const cJSON *root);
static void ParseInitCfgContents(const char *cfgName, const cJSON *root)
{
INIT_ERROR_CHECK(root != NULL, return, "Root is null");
INIT_LOGI("Parse init cfg %s ", cfgName);
ParseAllServices(root);
// parse jobs
ParseAllJobs(root);
......@@ -32,8 +30,9 @@ static void ParseInitCfgContents(const char *cfgName, const cJSON *root)
ParseAllImports(root);
}
static int ParseInitCfg(const char *configFile, void *context)
int ParseInitCfg(const char *configFile, void *context)
{
INIT_LOGI("ParseInitCfg %s", configFile);
UNUSED(context);
char *fileBuf = ReadFileToBuf(configFile);
INIT_ERROR_CHECK(fileBuf != NULL, return -1, "Failed to read file content %s", configFile);
......@@ -85,10 +84,7 @@ static void ParseAllImports(const cJSON *root)
void ReadConfig(void)
{
// parse cfg
if (InChargerMode() == 1) {
ParseInitCfg(INIT_CONFIGURATION_FILE, NULL);
ReadFileInDir(OTHER_CHARGE_PATH, ".cfg", ParseInitCfg, NULL);
} else if (InUpdaterMode() == 0) {
if (InUpdaterMode() == 0) {
ParseInitCfg(INIT_CONFIGURATION_FILE, NULL);
ReadFileInDir(OTHER_CFG_PATH, ".cfg", ParseInitCfg, NULL);
} else {
......
此差异已折叠。
......@@ -18,7 +18,6 @@
#include <fcntl.h>
#include <netinet/in.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/uio.h>
......@@ -106,26 +105,34 @@ static int SetSocketEnv(int fd, const char *name)
return 0;
}
int CreateServiceSocket(ServiceSocket *sockopt)
int CreateServiceSocket(Service *service)
{
INIT_CHECK(sockopt != NULL, return 0);
ServiceSocket *tmpSock = sockopt;
INIT_CHECK(service != NULL && service->socketCfg != NULL, return 0);
int ret = 0;
ServiceSocket *tmpSock = service->socketCfg;
while (tmpSock != NULL) {
int fd = CreateSocket(tmpSock);
INIT_CHECK_RETURN_VALUE(fd >= 0, -1);
int ret = SetSocketEnv(fd, tmpSock->name);
if (IsOnDemandService(service)) {
ret = ServiceAddWatcher(&tmpSock->watcher, service, tmpSock->sockFd);
INIT_CHECK_RETURN_VALUE(ret == 0, -1);
}
ret = SetSocketEnv(fd, tmpSock->name);
INIT_CHECK_RETURN_VALUE(ret >= 0, -1);
tmpSock = tmpSock->next;
}
return 0;
}
void CloseServiceSocket(ServiceSocket *sockopt)
void CloseServiceSocket(Service *service)
{
INIT_CHECK(sockopt != NULL, return);
INIT_CHECK(service != NULL && service->socketCfg != NULL, return);
struct sockaddr_un addr;
ServiceSocket *tmpSock = sockopt;
while (tmpSock != NULL) {
ServiceSocket *sockopt = service->socketCfg;
while (sockopt != NULL) {
if (sockopt->watcher != NULL) {
ServiceDelWatcher(sockopt->watcher);
}
if (sockopt->sockFd >= 0) {
close(sockopt->sockFd);
sockopt->sockFd = -1;
......@@ -133,7 +140,7 @@ void CloseServiceSocket(ServiceSocket *sockopt)
if (GetSocketAddr(&addr, sockopt->name) == 0) {
unlink(addr.sun_path);
}
tmpSock = tmpSock->next;
sockopt = sockopt->next;
}
return;
}
......@@ -47,6 +47,7 @@ void SystemPrepare(void)
void SystemConfig(void)
{
InitServiceSpace();
// read config
ReadConfig();
......
......@@ -118,3 +118,14 @@ const struct CmdTable *GetCmdTable(int *number)
*number = (int)ARRAY_LENGTH(g_cmdTable);
return g_cmdTable;
}
void PluginExecCmdByName(const char *name, const char *cmdContent)
{
}
void PluginExecCmdByCmdIndex(int index, const char *cmdContent)
{
}
const char *PluginGetCmdIndex(const char *cmdStr, int *index)
{
return NULL;
}
\ No newline at end of file
......@@ -30,19 +30,19 @@ static int g_jobCnt = 0;
void DumpAllJobs(void)
{
INIT_LOGD("Start to dump all jobs...");
INIT_LOGV("Start to dump all jobs...");
for (int i = 0; i < g_jobCnt; i++) {
INIT_LOGD("\tjob name: %s", g_jobs[i].name);
INIT_LOGV("\tjob name: %s", g_jobs[i].name);
if (g_jobs[i].cmdLines == NULL) {
continue;
}
INIT_LOGD("\tlist all commands:");
INIT_LOGV("\tlist all commands:");
for (int j = 0; j < g_jobs[i].cmdLines->cmdNum; j++) {
CmdLine *cmd = &g_jobs[i].cmdLines->cmds[j];
INIT_LOGD("\t\tcommand: %s %s", GetCmdKey(cmd->cmdIndex), cmd->cmdContent);
INIT_LOGV("\t\tcommand: %s %s", GetCmdKey(cmd->cmdIndex), cmd->cmdContent);
}
}
INIT_LOGD("Finish dump all jobs");
INIT_LOGV("Finish dump all jobs");
}
static int GetJobName(const cJSON *jobItem, Job *resJob)
......@@ -130,7 +130,7 @@ void DoJob(const char *jobName)
return;
}
INIT_LOGD("Call job with name %s", jobName);
INIT_LOGV("Call job with name %s", jobName);
for (int i = 0; i < g_jobCnt; ++i) {
if (strncmp(jobName, g_jobs[i].name, strlen(g_jobs[i].name)) == 0) {
CmdLines *cmdLines = g_jobs[i].cmdLines;
......@@ -160,3 +160,8 @@ void ReleaseAllJobs(void)
g_jobs = NULL;
g_jobCnt = 0;
}
int DoJobNow(const char *jobName)
{
return 0;
}
......@@ -74,3 +74,13 @@ int ServiceExec(const Service *service)
}
return SERVICE_SUCCESS;
}
int ServiceAddWatcher(ServiceWatcher *watcherHandle, Service *service, int fd)
{
return 0;
}
void ServiceDelWatcher(ServiceWatcher watcherHandle)
{
return;
}
\ No newline at end of file
......@@ -16,6 +16,12 @@
#include "init_log.h"
static const pid_t INIT_PROCESS_PID = 1;
int __attribute__((weak)) AtlibInit(void)
{
return 0;
}
int main(int argc, char * const argv[])
{
int isSecondStage = 0;
......@@ -31,6 +37,7 @@ int main(int argc, char * const argv[])
if (isSecondStage == 0) {
SystemPrepare();
}
(void)AtlibInit();
SystemInit();
SystemExecuteRcs();
SystemConfig();
......
......@@ -44,9 +44,6 @@ void MountBasicFs(void)
if (mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755") != 0) {
INIT_LOGE("Mount tmpfs failed. %s", strerror(errno));
}
if (mount("tmpfs", "/mnt", "tmpfs", MS_NOSUID, "mode=0755") != 0) {
INIT_LOGE("Mount tmpfs failed. %s", strerror(errno));
}
if (mkdir("/dev/pts", S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) != 0) {
INIT_LOGE("mkdir /dev/pts failed. %s", strerror(errno));
}
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
......@@ -14,9 +14,22 @@
*/
#include "init_jobs_internal.h"
#include "init_group_manager.h"
#include "init_param.h"
static int CheckJobValid(const char *jobName)
{
// check job in group
return CheckNodeValid(NODE_TYPE_JOBS, jobName);
}
void ParseAllJobs(const cJSON *fileRoot)
{
ParseTriggerConfig(fileRoot);
ParseTriggerConfig(fileRoot, CheckJobValid);
}
int DoJobNow(const char *jobName)
{
DoJobExecNow(jobName);
return 0;
}
此差异已折叠。
此差异已折叠。
......@@ -119,9 +119,9 @@ static int MountToNewTarget(const char *target)
// Just ignore this one or return error?
continue;
}
INIT_LOGD("new mount point is: %s", newMountPoint);
INIT_LOGV("new mount point is: %s", newMountPoint);
if (!UnderBasicMountPoint(mountPoint)) {
INIT_LOGD("Move mount %s to %s", mountPoint, newMountPoint);
INIT_LOGV("Move mount %s to %s", mountPoint, newMountPoint);
if (mount(mountPoint, newMountPoint, NULL, MS_MOVE, NULL) < 0) {
INIT_LOGE("Failed to mount moving %s to %s, err = %d", mountPoint, newMountPoint, errno);
// If one mount entry cannot move to new mountpoint, umount it.
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册