From b2caacbf68f88568f9cd039498f4e6c3e7f0f784 Mon Sep 17 00:00:00 2001 From: sw1tchbl4d3 Date: Thu, 29 Jul 2021 17:25:34 +0200 Subject: [PATCH] Avoid unnecessary recursion in ensuredir() Before we made the ensuredir() function recurse on itself if we couldn't open /run/rdo, after mkdir()'ing it, to retry opening the directory. Now we simplify and add a simple fd = open([...]) directly after the mkdir(), to avoid the recursion. If the second open fails, we error out. --- sessions.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/sessions.h b/sessions.h index 19cf679..cc856e2 100644 --- a/sessions.h +++ b/sessions.h @@ -47,10 +47,7 @@ int getpstartts(int pid, unsigned long long* startts) { return 0; } -int ensuredir(int recur) { - if (recur >= 2) - errx(1, "Too many recursions in ensuredir()"); - +int ensuredir() { struct stat st; int fd = open("/run/rdo", O_RDONLY, O_DIRECTORY | O_NOFOLLOW); @@ -58,7 +55,10 @@ int ensuredir(int recur) { if (errno == ENOENT) { if (mkdir("/run/rdo", 0700) < 0) err(1, "Could not create /run/rdo"); - return ensuredir(++recur); + + fd = open("/run/rdo", O_RDONLY, O_DIRECTORY | O_NOFOLLOW); + if (fd < 0) + err(1, "Could not open /run/rdo"); } else err(1, "Could not open /run/rdo"); @@ -84,7 +84,7 @@ void setsession(int pid, unsigned int ts_ttl) { unsigned long long startts; char path[1024], ts_str[32]; - if (ensuredir(0) < 0 || getpstartts(pid, &startts) < 0) + if (ensuredir() < 0 || getpstartts(pid, &startts) < 0) return; snprintf(path, sizeof(path), "/run/rdo/%d-%llu", pid, startts); @@ -115,7 +115,7 @@ int getsession(int pid, unsigned int ts_ttl) { unsigned long long startts, current; char path[1024], ts_str[32]; - if (ensuredir(0) < 0 || getpstartts(pid, &startts) < 0) + if (ensuredir() < 0 || getpstartts(pid, &startts) < 0) return -1; snprintf(path, sizeof(path), "/run/rdo/%d-%llu", pid, startts);