Skip to content
This repository has been archived by the owner on Jul 12, 2022. It is now read-only.

Commit

Permalink
指定ディレクトリに入ってプロセスを隔離するところまで実装
Browse files Browse the repository at this point in the history
  • Loading branch information
guni973 committed Sep 26, 2018
1 parent 8abf706 commit 620e302
Show file tree
Hide file tree
Showing 3 changed files with 147 additions and 1 deletion.
51 changes: 51 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ authors = ["guni973 <ad2314ce71926@gmail.com>"]
edition = "2018"

[dependencies]
nix = "0.11.0"
96 changes: 95 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,97 @@
use std::fs;
use std::env::{set_var, args};
use std::process::*;
use std::ffi::CString;
use nix::unistd::*;
use nix::unistd::{execv, fork, ForkResult};
use nix::sched::*; // 調べる
use nix::unistd::*;
use nix::sys::wait::*;
use nix::mount::{mount, MsFlags};

fn print_help() {}

// TODO Bootstrap func

fn main() {
println!("Hello, world!");
// debug
set_var("RUST_BACKTRACE", "1");

let args: Vec<String> = args().collect();
if args.len() < 2 {
eprintln!("invalid argments");
print_help();
exit(1);
}

let container_path = args[1].as_str();

match unshare(CloneFlags::CLONE_NEWPID | CloneFlags::CLONE_NEWNS) {
Ok(_) => {},
Err(e) => eprintln!("{}", e)
}

fs::create_dir_all(container_path).unwrap();

mount(
None::<&str>,
"/",
None::<&str>,
MsFlags::MS_PRIVATE,
None::<&str>,
).expect("Can not mount specify dir.");


mount(
Some(container_path),
container_path,
None::<&str>,
MsFlags::MS_BIND | MsFlags::MS_REC,
None::<&str>,
).expect("mount root dir faild.");

chroot(container_path).expect("chroot failed.");

chdir("/").expect("cd / faild.");

match fork() {
Ok(ForkResult::Parent{ child, .. }) => {
// 親プロセスは待つだけ
match waitpid(child, None).expect("wait_pid faild") {
WaitStatus::Exited(pid, status) => {
println!("Exit: pid: {:?}, status: {:?}", pid, status)
}
WaitStatus::Signaled(pid, status, _) => {
println!("Signal: pid={:?}, status={:?}", pid, status)
}
_ => eprintln!("Unexpected exit."),
}
}
Ok(ForkResult::Child) => {
// Setting Host
sethostname("archlinux-test-container").expect("sethostname faild.");
// TODO: locale

fs::create_dir_all("proc").unwrap_or_else(|why| {
eprintln!("{:?}", why.kind());
});

mount(
Some("proc"),
"/proc",
Some("proc"),
MsFlags::MS_MGC_VAL,
None::<&str>,
).expect("mount procfs faild.");

let dir = CString::new("/bin/bash".to_string()).unwrap();
let arg = CString::new("-l".to_string()).unwrap();

execv(&dir, &[dir.clone(), arg]).expect("execution faild.");

}
Err(_) => eprintln!("Fork failed"),
}


}

0 comments on commit 620e302

Please sign in to comment.