Merge branch 'collectd-5.7' into collectd-5.8
[collectd.git] / contrib / docker / rootfs_prefix / rootfs_prefix.c
1 #define _GNU_SOURCE
2
3 #include <dirent.h>
4 #include <dlfcn.h>
5 #include <errno.h>
6 #include <error.h>
7 #include <stdio.h>
8 #include <string.h>
9
10 #define PREFIX "/rootfs"
11 #define BUFSIZE 256
12
13 const char *add_prefix(const char *orig, char *prefixed) {
14   if ((strncmp(orig, "/proc", strlen("/proc")) != 0) &&
15       (strncmp(orig, "/sys", strlen("/sys")) != 0))
16     return orig;
17
18   int status = snprintf(prefixed, BUFSIZE, "%s%s", PREFIX, orig);
19   if (status < 1) {
20     error(status, errno, "adding '%s' prefix to file path failed: '%s' -> '%s'",
21           PREFIX, orig, prefixed);
22     return orig;
23   } else if ((unsigned int)status >= BUFSIZE) {
24     error(status, ENAMETOOLONG,
25           "'%s' got truncated when adding '%s' prefix: '%s'", orig, PREFIX,
26           prefixed);
27     return orig;
28   } else {
29     return (const char *)prefixed;
30   }
31 }
32
33 FILE *fopen(const char *path, const char *mode) {
34   char filename[BUFSIZE] = "\0";
35
36   FILE *(*original_fopen)(const char *, const char *);
37   original_fopen = dlsym(RTLD_NEXT, "fopen");
38
39   return (*original_fopen)(add_prefix(path, filename), mode);
40 }
41
42 DIR *opendir(const char *name) {
43   char filename[BUFSIZE] = "\0";
44
45   DIR *(*original_opendir)(const char *);
46   original_opendir = dlsym(RTLD_NEXT, "opendir");
47
48   return (*original_opendir)(add_prefix(name, filename));
49 }
50
51 int *open(const char *pathname, int flags) {
52   char filename[BUFSIZE] = "\0";
53
54   int *(*original_open)(const char *, int);
55   original_open = dlsym(RTLD_NEXT, "open");
56
57   return (*original_open)(add_prefix(pathname, filename), flags);
58 }