From 1bb5a4415257e02b9357a3a06e31ccd2826f1161 Mon Sep 17 00:00:00 2001 From: Simon Sundberg Date: Tue, 2 Feb 2021 14:28:42 +0100 Subject: [PATCH] pping: Create pin-folder and check if root Create the /sys/fs/bpf/tc folder if it does not exist. Also check if pping is run as root, otherwise inform user that it must run as root. Libbpf will attempt to create the /sys/fs/bpf/tc/globals directory when pinning the map, however it will not do so recursivly (so will fail if /sys/fs/bpf/tc does not exist). So as a temporary solution, attempt to create /sys/fs/bpf/tc (however, if sys/fs/bpf is not mounted this will still fail). Signed-off-by: Simon Sundberg --- pping/pping.c | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/pping/pping.c b/pping/pping.c index c328e14..5154a5d 100644 --- a/pping/pping.c +++ b/pping/pping.c @@ -14,6 +14,7 @@ #include // For detecting Ctrl-C #include // For setting rlmit #include +#include #include #include @@ -77,6 +78,21 @@ static int set_rlimit(long int lim) return !setrlimit(RLIMIT_MEMLOCK, &rlim) ? 0 : -errno; } +static int mkdir_if_noexist(const char *path) +{ + int ret; + struct stat st = {0}; + + ret = stat(path, &st); + if (ret) { + if (errno != ENOENT) + return -errno; + + return mkdir(path, 0700) ? -errno : 0; + } + return S_ISDIR(st.st_mode) ? 0 : -EEXIST; +} + static int bpf_obj_open(struct bpf_object **obj, const char *obj_path, char *map_path) { @@ -265,6 +281,12 @@ int main(int argc, char *argv[]) return EXIT_FAILURE; } + // Detect if running as root + if (geteuid() != 0) { + printf("This program must be run as root.\n"); + return EXIT_FAILURE; + } + // Increase rlimit err = set_rlimit(RLIM_INFINITY); if (err) { @@ -283,6 +305,14 @@ int main(int argc, char *argv[]) } // Load and attach the XDP program + err = mkdir_if_noexist("/sys/fs/bpf/tc"); + if (err) { + fprintf(stderr, + "Failed creating directory %s in which to pin map: %s\n", + "/sys/fs/bpf/tc", strerror(-err)); + goto cleanup; + } + err = bpf_obj_open(&obj, PPING_XDP_OBJ, PINNED_DIR); if (err) { fprintf(stderr, "Failed opening object file %s: %s\n",