chroot.c (1259B)
- // Collection of Unix tools, comparable to coreutils
- // SPDX-FileCopyrightText: 2017-2023 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- #define _POSIX_C_SOURCE 200809L
- #define _DEFAULT_SOURCE // chroot
- #include <assert.h> // assert
- #include <errno.h> // errno
- #include <stdbool.h> // false
- #include <stdio.h> // fprintf, perror
- #include <stdlib.h> // getenv
- #include <unistd.h> // chroot, execl, execv
- int
- main(int argc, char *argv[])
- {
- if(argc < 2)
- {
- fprintf(stderr, "chroot: Needs arguments\n");
- fprintf(stderr, "Usage: chroot <newroot> [command [args ...]]\n");
- return 125;
- }
- if(chroot(argv[1]) < 0)
- {
- perror("chroot");
- return 125;
- }
- if(chdir("/") < 0)
- {
- perror("chdir");
- return 125;
- }
- int ret = 0;
- errno = 0;
- if(argc == 2)
- {
- char *shell = getenv("SHELL");
- if(shell == NULL) shell = "/bin/sh";
- /* flawfinder: ignore. No restrictions on commands is intended */
- ret = execlp(shell, shell, "-i", NULL);
- }
- else
- {
- argv += 2;
- /* flawfinder: ignore. No restrictions on commands is intended */
- ret = execvp(argv[0], argv);
- }
- if(ret != 0)
- {
- perror("chroot: exec");
- if(errno == ENOENT) return 127;
- return 126;
- }
- assert(false);
- }