From c39940d81b000a721d70ab9c19787f5bf5716b55 Mon Sep 17 00:00:00 2001 From: Ralph Boehme Date: Wed, 30 Sep 2020 14:45:34 +0200 Subject: [PATCH] s3/lib: add proc fds infrastructure Signed-off-by: Ralph Boehme Reviewed-by: Jeremy Allison --- source3/include/proto.h | 3 +++ source3/lib/system.c | 56 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/source3/include/proto.h b/source3/include/proto.h index 9f74287f967..2ce632c5400 100644 --- a/source3/include/proto.h +++ b/source3/include/proto.h @@ -237,6 +237,9 @@ char *sys_realpath(const char *path); int sys_get_number_of_cores(void); #endif +bool sys_have_proc_fds(void); +const char *sys_proc_fd_path(int fd, char *buf, int bufsize); + struct stat; void init_stat_ex_from_stat (struct stat_ex *dst, const struct stat *src, diff --git a/source3/lib/system.c b/source3/lib/system.c index cf4c4d46c36..8ea2af9f93b 100644 --- a/source3/lib/system.c +++ b/source3/lib/system.c @@ -1030,3 +1030,59 @@ int sys_get_number_of_cores(void) return ret; } #endif + +static struct proc_fd_pattern { + const char *pattern; + const char *test_path; +} proc_fd_patterns[] = { + /* Linux */ + { "/proc/self/fd/%d", "/proc/self/fd/0" }, + { NULL, NULL }, +}; + +static const char *proc_fd_pattern; + +bool sys_have_proc_fds(void) +{ + static bool checked; + static bool have_proc_fds; + struct proc_fd_pattern *p = NULL; + struct stat sb; + int ret; + + if (checked) { + return have_proc_fds; + } + + for (p = &proc_fd_patterns[0]; p->test_path != NULL; p++) { + ret = stat(p->test_path, &sb); + if (ret != 0) { + continue; + } + have_proc_fds = true; + proc_fd_pattern = p->pattern; + break; + } + + checked = true; + return have_proc_fds; +} + +const char *sys_proc_fd_path(int fd, char *buf, int bufsize) +{ + int written; + + if (!sys_have_proc_fds()) { + return NULL; + } + + written = snprintf(buf, + bufsize, + proc_fd_pattern, + fd); + if (written >= bufsize) { + return NULL; + } + + return buf; +}