From 0b1258b44cb7412e2c8a01640aeeef25a7c36080 Mon Sep 17 00:00:00 2001 From: Joachim Wiberg Date: Sun, 27 Feb 2022 23:52:18 +0100 Subject: [PATCH] Add very basic in_container() function, from sysklogd project Signed-off-by: Joachim Wiberg --- src/helpers.c | 33 +++++++++++++++++++++++++++++++++ src/helpers.h | 1 + 2 files changed, 34 insertions(+) diff --git a/src/helpers.c b/src/helpers.c index fd352f8d..a06cd1cc 100644 --- a/src/helpers.c +++ b/src/helpers.c @@ -522,6 +522,39 @@ done: } } +/* + * Very basic, and incomplete, check if we're running in a container. + */ +int in_container(void) +{ + const char *files[] = { + "/run/.containerenv", + "/.dockerenv" + }; + const char *containers[] = { + "lxc", + "docker", + "kubepod" + }; + size_t i; + char *c; + + c = getenv("container"); + if (c) { + for (i = 0; i < NELEMS(containers); i++) { + if (!strcmp(containers[i], c)) + return 1; + } + } + + for (i = 0; i < NELEMS(files); i++) { + if (!access(files[i], F_OK)) + return 1; + } + + return 0; +} + #ifndef HAVE_GETFSENT static lfile_t *fstab = NULL; diff --git a/src/helpers.h b/src/helpers.h index 07b70d02..839a2952 100644 --- a/src/helpers.h +++ b/src/helpers.h @@ -93,6 +93,7 @@ int mksubsys (const char *dir, mode_t mode, char *user, char *group); void set_hostname (char **hostname); void networking (int updown); +int in_container (void); int complete (char *cmd, int pid); int run (char *cmd);