From bc1d44460cc92a734b9999042dfeef8c6be3fd9c Mon Sep 17 00:00:00 2001 From: Giuseppe Scrivano Date: Thu, 24 Sep 2020 18:00:18 +0200 Subject: [PATCH] container: truncate pid file before writing it Closes: https://github.com/containers/crun/issues/504 Signed-off-by: Giuseppe Scrivano --- src/libcrun/container.c | 4 ++-- src/libcrun/utils.c | 10 ++++++++-- src/libcrun/utils.h | 2 ++ 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/libcrun/container.c b/src/libcrun/container.c index 109f5337a0..927986a467 100644 --- a/src/libcrun/container.c +++ b/src/libcrun/container.c @@ -1230,7 +1230,7 @@ wait_for_process (pid_t pid, libcrun_context_t *context, int terminal_fd, int no { char buf[12]; size_t buf_len = sprintf (buf, "%d", pid); - ret = write_file (context->pid_file, buf, buf_len, err); + ret = write_file_with_flags (context->pid_file, O_CREAT | O_TRUNC, buf, buf_len, err); if (UNLIKELY (ret < 0)) return ret; } @@ -2864,7 +2864,7 @@ libcrun_container_restore (libcrun_context_t *context, const char *id, libcrun_c { char buf[12]; size_t buf_len = sprintf (buf, "%d", status.pid); - ret = write_file (context->pid_file, buf, buf_len, err); + ret = write_file_with_flags (context->pid_file, O_CREAT | O_TRUNC, buf, buf_len, err); if (UNLIKELY (ret < 0)) return ret; } diff --git a/src/libcrun/utils.c b/src/libcrun/utils.c index e2d5991511..b1df0fe288 100644 --- a/src/libcrun/utils.c +++ b/src/libcrun/utils.c @@ -111,9 +111,9 @@ write_file_at (int dirfd, const char *name, const void *data, size_t len, libcru } int -write_file (const char *name, const void *data, size_t len, libcrun_error_t *err) +write_file_with_flags (const char *name, int flags, const void *data, size_t len, libcrun_error_t *err) { - cleanup_close int fd = open (name, O_WRONLY | O_CREAT, 0700); + cleanup_close int fd = open (name, O_WRONLY | flags, 0700); int ret; if (UNLIKELY (fd < 0)) return crun_make_error (err, errno, "opening file `%s` for writing", name); @@ -125,6 +125,12 @@ write_file (const char *name, const void *data, size_t len, libcrun_error_t *err return ret; } +int +write_file (const char *name, const void *data, size_t len, libcrun_error_t *err) +{ + return write_file_with_flags (name, O_CREAT, data, len, err); +} + int detach_process () { diff --git a/src/libcrun/utils.h b/src/libcrun/utils.h index 8f77820e8a..178a9575b3 100644 --- a/src/libcrun/utils.h +++ b/src/libcrun/utils.h @@ -149,6 +149,8 @@ int xasprintf (char **str, const char *fmt, ...); int crun_path_exists (const char *path, libcrun_error_t *err); +int write_file_with_flags (const char *name, int flags, const void *data, size_t len, libcrun_error_t *err); + int write_file (const char *name, const void *data, size_t len, libcrun_error_t *err); int write_file_at (int dirfd, const char *name, const void *data, size_t len, libcrun_error_t *err);