Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sstream>
- #include <cerrno>
- #include <cstring>
- #include <sys/stat.h>
- #include <sys/mount.h>
- #include <sys/syscall.h>
- #include <sched.h>
- #include <cstdio>
- #include <cstdlib>
- #include <unistd.h>
- #define OLD_ROOT "oldroot"
- using namespace std;
- int main(int argc, char* argv[]) {
- if(argc != 2) {
- cerr << "First argument is the template for the root" << endl;
- return -1;
- }
- string template_root(argv[1]);
- // Generate tmpfs directory
- stringstream ss;
- ss << "tmpfs_" << template_root;
- string tmpfs = ss.str();
- struct stat st;
- if(stat(tmpfs.c_str(),&st) == 0) {
- cerr << tmpfs << " already exists!" << endl;
- return -1;
- }
- if(mkdir(tmpfs.c_str(),644) != 0) {
- perror("mkdir");
- return -1;
- }
- // Mount tmpfs
- if(mount("none", tmpfs.c_str(), "tmpfs", 0, "mode=0644,uid=65534,size=10M") != 0) {
- perror("mount");
- return 1;
- }
- // Copy content
- ss.str("");
- ss.clear();
- ss << "cp -r " << template_root << "/* " << tmpfs;
- system(ss.str().c_str());
- // Create mount namespace
- if(unshare(CLONE_NEWNS) < 0) {
- perror("unshare");
- return 1;
- }
- // Make old root MS_SLAVE
- // Using the syscall directly is not easy since it requires
- // reading the /etc/fstab
- if(system("mount --make-rslave /") != 0) {
- perror("mount");
- return 1;
- }
- // Change directory
- chdir(tmpfs.c_str());
- // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- // This command leads to EBUSY of the pivot_root.
- // Without it, everything works fine
- chroot(".");
- // Move to new root file system
- if(mkdir(OLD_ROOT,644) != 0) {
- perror("mkdir");
- return -1;
- }
- if(syscall(SYS_pivot_root,".",OLD_ROOT) < 0) {
- perror("pivot_root");
- return 1;
- }
- // Remove old mount
- if(umount2(OLD_ROOT,MNT_DETACH) != 0) {
- perror("umount");
- return 1;
- }
- if(rmdir(OLD_ROOT) != 0) {
- perror("rmdir");
- return 1;
- }
- // Enter shell - only for testing
- execl("/bin/bash","-i",NULL);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement