While writing a perl script intended to fully automate the setup of virtual machines (Xen pv) I hit a small maybe very simple problem.
Using perl’s chroot function I do my things on the guest file system and then I need to get back to my initial real root. How the hell I do that?
Script example:
`mount $disk_image $mount_point`;
chdir($mount_point);
chroot($mount_point);
#[Do my things...]
#<Exit chroot wanted here>
`umount $mount_point`;
#[Post install things...]
I’ve tried exit; but obviously that exit the whole script.
Searching for a way to exit the chroot I’ve found a number of scripts who aim to exit an already setup chroot (privilege escalation). Since I do the chroot here theses methods do not aplies.
Tried some crazy things like:
opendir REAL_ROOT, "/";
chdir($mount_point);
chroot($mount_point);
chdir(*REAL_ROOT);
But no go.
UPDATE
Some points to consider:
- I can’t split the script in multiple files. (Silly reasons, but really, I can’t)
- The chrooted part involve using a lot of data gathered earlier by the script (before the chroot), enforcing the need of not lunching another script inside the chroot.
- Using open, system or backticks is not good, I need to run commands and based on the output (not the exit code, the actual output) do other things.
- Steps after the chroot depends on what was done inside the chroot, hence I need to have all the variables I defined or changed while inside, outside.
- Fork is possible, but I don’t know a good way to handle correctly the passing of informations from and to the child.
The chrooted process() cannot “unchroot” itself by exiting (which would just exit).
You have to spawn a children process, which will chroot.
Something along the lines of the following should do the trick:
It stills lacks of some error checking thought.