contrib/docker: add LD_PRELOAD wrapper to fopen/open/opendir syscalls
[collectd.git] / contrib / docker / rootfs_prefix / rootfs_prefix.c
1 #define _GNU_SOURCE
2
3 #include <stdio.h>
4 #include <error.h>
5 #include <dlfcn.h>
6 #include <string.h>
7 #include <errno.h>
8 #include <dirent.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) ||
18                 (strncmp(orig, "/sys", 4) == 0)) {
19
20                 status = snprintf(prefixed, BUFSIZE, "%s%s", PREFIX, orig);
21                 if ((unsigned int)status >= BUFSIZE) {
22                         error(status, ENAMETOOLONG, "'%s' got truncated when adding '%s' prefix: '%s'",
23                                 orig, PREFIX, prefixed);
24                         return orig;
25                 } else if (status < 1) {
26                         error(status, errno, "adding '%s' prefix to file path failed: '%s' -> '%s'",
27                                 PREFIX, orig, prefixed);
28                         return orig;
29                 } else {
30                         return (const char*) prefixed;
31                 }
32
33         } else {
34                 return orig;
35         }
36 }
37
38 FILE *fopen(const char *path, const char *mode) {
39         char filename[BUFSIZE] = "\0";
40
41         FILE *(*original_fopen)(const char*, const char*);
42         original_fopen = dlsym(RTLD_NEXT, "fopen");
43
44         return (*original_fopen)(add_prefix(path, filename), mode);
45 }
46
47 DIR *opendir(const char *name) {
48         char filename[BUFSIZE] = "\0";
49
50         DIR *(*original_opendir)(const char*);
51         original_opendir = dlsym(RTLD_NEXT, "opendir");
52
53         return (*original_opendir)(add_prefix(name, filename));
54 }
55
56 int *open(const char *pathname, int flags) {
57         char filename[BUFSIZE] = "\0";
58
59         int *(*original_open)(const char*, int);
60         original_open = dlsym(RTLD_NEXT, "open");
61
62         return (*original_open)(add_prefix(pathname, filename), flags);
63 }