From 3195bc481b601d6f88d83c9a62fd090fc92a96a4 Mon Sep 17 00:00:00 2001 From: Kaige Fu Date: Wed, 4 Jul 2018 13:47:06 +0800 Subject: [PATCH] tools: acrnlog: Deprecate binary "rm" and "mkdir" with GPLv3+ The tools currently rely on the availability of binary "rm" and "mkdir" to be available in the $PATH on the Service OS. This create an obscure dependency. The patch changes the code to use standard C APIs to perform the same functionality which makes the code more self-contained. Signed-off-by: Kaige Fu Reviewed-by: Yan, Like --- tools/acrnlog/acrnlog.c | 54 ++++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 9 deletions(-) diff --git a/tools/acrnlog/acrnlog.c b/tools/acrnlog/acrnlog.c index 125cce8aa..21f5daba1 100644 --- a/tools/acrnlog/acrnlog.c +++ b/tools/acrnlog/acrnlog.c @@ -293,7 +293,6 @@ static struct hvlog_file last_log = { static int new_log_file(struct hvlog_file *log) { char file_name[32] = { }; - char cmd[64] = { }; if (log->fd >= 0) { if (!hvlog_log_size) @@ -304,8 +303,7 @@ static int new_log_file(struct hvlog_file *log) snprintf(file_name, sizeof(file_name), "%s.%hu", log->path, log->index + 1); - snprintf(cmd, sizeof(cmd), "rm -f %s", file_name); - system(cmd); + remove(file_name); log->fd = open(file_name, O_RDWR | O_CREAT | O_TRUNC, 0666); if (log->fd < 0) { @@ -315,9 +313,9 @@ static int new_log_file(struct hvlog_file *log) log->left_space = hvlog_log_size; log->index++; - snprintf(cmd, sizeof(cmd), "rm -f %s.%hu", log->path, - log->index - hvlog_log_num); - system(cmd); + snprintf(file_name, sizeof(file_name), "%s.%hu", log->path, + log->index - hvlog_log_num); + remove(file_name); return 0; } @@ -367,6 +365,44 @@ static void *cur_read_func(void *arg) return NULL; } +/* If dir *path does't exist, create a new one. + * Otherwise, remove all the old acrnlog files in the dir. + */ +static int mk_dir(const char *path) +{ + char prefix[32] = "acrnlog_cur."; /* acrnlog file prefix */ + char acrnlog_file[64] = { }; + struct dirent *pdir; + struct stat st; + int index = 0; + char *find; + DIR *dir; + + if (stat(path, &st)) { + if (mkdir(path, 0644)) + return -1; + } else { + /* Remove all the old acrnlogs */ + dir = opendir(path); + if (!dir) { + printf("Error opening directory %s. Error: %s\n", + path, strerror(errno)); + return -1; + } + while (pdir = readdir(dir)) { + find = strstr(pdir->d_name, prefix); + if (!find) + continue; + + snprintf(acrnlog_file, sizeof(acrnlog_file), "%s/%s%d", + path, prefix, index++); + remove(acrnlog_file); + } + } + + return 0; +} + /* for user optinal args */ static const char optString[] = "s:n:t:h"; @@ -430,10 +466,10 @@ int main(int argc, char *argv[]) if (parse_opt(argc, argv)) return -1; - system("rm -rf /tmp/acrnlog"); - ret = system("mkdir -p /tmp/acrnlog"); + ret = mk_dir("/tmp/acrnlog"); if (ret) { - printf("can't create /tmp/acrnlog\n"); + printf("Cannot create /tmp/acrnlog. Error: %s\n", + strerror(errno)); return ret; }