Merge branch 'collectd-5.7'
[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   int status;
15   int errno;
16
17   if ((strncmp(orig, "/proc", 5) == 0) || (strncmp(orig, "/sys", 4) == 0)) {
18
19     status = snprintf(prefixed, BUFSIZE, "%s%s", PREFIX, orig);
20     if ((unsigned int)status >= BUFSIZE) {
21       error(status, ENAMETOOLONG,
22             "'%s' got truncated when adding '%s' prefix: '%s'", orig, PREFIX,
23             prefixed);
24       return orig;
25     } else if (status < 1) {
26       error(status, errno,
27             "adding '%s' prefix to file path failed: '%s' -> '%s'", PREFIX,
28             orig, prefixed);
29       return orig;
30     } else {
31       return (const char *)prefixed;
32     }
33
34   } else {
35     return orig;
36   }
37 }
38
39 FILE *fopen(const char *path, const char *mode) {
40   char filename[BUFSIZE] = "\0";
41
42   FILE *(*original_fopen)(const char *, const char *);
43   original_fopen = dlsym(RTLD_NEXT, "fopen");
44
45   return (*original_fopen)(add_prefix(path, filename), mode);
46 }
47
48 DIR *opendir(const char *name) {
49   char filename[BUFSIZE] = "\0";
50
51   DIR *(*original_opendir)(const char *);
52   original_opendir = dlsym(RTLD_NEXT, "opendir");
53
54   return (*original_opendir)(add_prefix(name, filename));
55 }
56
57 int *open(const char *pathname, int flags) {
58   char filename[BUFSIZE] = "\0";
59
60   int *(*original_open)(const char *, int);
61   original_open = dlsym(RTLD_NEXT, "open");
62
63   return (*original_open)(add_prefix(pathname, filename), flags);
64 }