switch-root.c revision ac0930c892bc7979b4c9bc2a52e5e844650b025d
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2012 Harald Hoyer, Lennart Poettering
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <stdbool.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include "util.h"
#include "path-util.h"
#include "switch-root.h"
int switch_root(const char *new_root) {
static const char move_mounts[] =
"/dev\0"
"/proc\0"
"/sys\0"
"/run\0";
int r, old_root_fd = -1;
struct stat new_root_stat;
bool old_root_remove;
const char *i;
return 0;
old_root_remove = in_initrd();
r = -errno;
goto fail;
}
/* Work-around for a kernel bug: for some reason the kernel
* refuses switching root if any file systems are mounted
* MS_SHARED. Hence remount them MS_PRIVATE here as a
* work-around.
*
log_warning("Failed to make \"/\" private mount: %m");
NULSTR_FOREACH(i, move_mounts) {
/* Mount point seems to be mounted already or
* stat failed. Unmount the old mount
* point. */
if (umount2(i, MNT_DETACH) < 0)
log_warning("Failed to unmount %s: %m", i);
continue;
}
log_warning("Failed to unmount %s: %m", i);
}
}
r = -errno;
goto fail;
}
if (old_root_remove) {
if (old_root_fd < 0)
log_warning("Failed to open root directory: %m");
}
r = -errno;
goto fail;
}
if (chroot(".") < 0) {
r = -errno;
log_error("Failed to change root: %m");
goto fail;
}
if (chdir("/") < 0) {
r = -errno;
log_error("Failed to change directory: %m");
goto fail;
}
if (old_root_fd >= 0) {
log_warning("Failed to stat old root directory, leaving: %m");
else {
old_root_fd = -1;
}
}
r = 0;
fail:
if (old_root_fd >= 0)
return r;
}