Is there a way to monitor and redirect file access of a thread or process?
For example a thread wants to read /etc/mysql/my.cnf and I want to change the access to ~/my.cnf or if I run touch /etc/test.config
I want the file to be redirected to ~/somefolder/etc/test.config
.
I am looking for a libary preferably for C, C++ which works for Linux/Unix.
Thanks in advance
You could write a shared object that gets pre-loaded when your program starts running. In the .so you'd redefine the libc function open()
. When the caller (the program that's getting fooled) passes as argument the string /etc/mysql/my.cnf
, you'd instead open ~/my.cnf
and return the opened file descriptor. The caller wouldn't know the difference.
Your shared object would of course need to call the "real" open()
to to open the file handle; you can get a pointer to the original libc function using dlsym()
.
This seems overly complicated, but in fact it isn't, it works like a charm. I've used it on several occasions where I had to fool a program that I didn't have the sources for; and it simply works like a clockwork.
If you want to see a proof of concept, check out my blog where I wrote it up. Happy coding!
In linux, you can use bind mounts to map directory or file to another path, and per-process mount namespaces to do it for specific application.
See this question.
Example 1: use proot
$ proot -b ~/alternate_hosts:/etc/hosts
# echo '1.2.3.4 google.com' > /etc/hosts
# resolveip google.com
# IP address of google.com is 1.2.3.4
Example 2: use unshare(1)
$ unshare -m
# touch foo bar
# mount -o bind foo bar
# echo hello > foo
# cat bar
hello
Example 3: use unshare(2)
See this post: http://glandium.org/blog/?p=217.