2021-05-18 22:10:35 +02:00
|
|
|
import os
|
|
|
|
import json
|
2021-06-16 19:48:13 +02:00
|
|
|
import modes
|
2021-05-18 22:10:35 +02:00
|
|
|
import bwrap
|
|
|
|
import config
|
|
|
|
import options
|
|
|
|
|
|
|
|
proc homePath(p: string): string =
|
|
|
|
joinPath(getHomeDir(), p)
|
|
|
|
|
2021-06-16 19:48:13 +02:00
|
|
|
const CONFIG_LOCATION = homePath(joinPath(".sandboxes", "config.json"))
|
|
|
|
|
2021-05-18 22:10:35 +02:00
|
|
|
proc checkRelativePath(p: string): string =
|
|
|
|
if p[0] == '/':
|
|
|
|
return p
|
|
|
|
homePath(p)
|
|
|
|
|
|
|
|
proc applyConfig(call: var BwrapCall, config: Config) =
|
|
|
|
for mount in config.mount.get(@[]):
|
|
|
|
call.addMount("--bind", checkRelativePath(mount))
|
|
|
|
|
|
|
|
for mount in config.romount.get(@[]):
|
|
|
|
call.addMount("--ro-bind", checkRelativePath(mount))
|
|
|
|
|
|
|
|
for symlink in config.symlinks.get(@[]):
|
|
|
|
call.addArg("--symlink", symlink.src, symlink.dst)
|
|
|
|
|
|
|
|
proc loadConfig(path: string): Config =
|
|
|
|
return readFile(path).parseJson().to(Config)
|
|
|
|
|
2021-06-16 19:48:13 +02:00
|
|
|
proc sandboxExec*(name: string, command: string, mode: Modes) =
|
2021-05-18 22:10:35 +02:00
|
|
|
let sandboxPath = homePath(joinPath(".sandboxes", name))
|
|
|
|
let sandboxFiles = joinPath(sandboxPath, "files")
|
|
|
|
let sandboxInfo = joinPath(sandboxPath, "info")
|
|
|
|
|
|
|
|
createDir(sandboxFiles)
|
|
|
|
var call = BwrapCall()
|
|
|
|
|
|
|
|
call
|
|
|
|
.addArg("--bind", sandboxFiles, getHomeDir())
|
|
|
|
.addMount("--dev-bind", "/dev")
|
2021-06-16 19:48:13 +02:00
|
|
|
.addArg("--tmpfs", "/tmp")
|
2021-05-18 22:10:35 +02:00
|
|
|
.addArg("--proc", "/proc")
|
|
|
|
.addArg("--unshare-all")
|
|
|
|
.addArg("--share-net")
|
|
|
|
.addArg("--die-with-parent")
|
|
|
|
.addArg("--hostname", name)
|
|
|
|
.applyConfig(loadConfig(CONFIG_LOCATION))
|
|
|
|
|
2021-06-16 19:48:13 +02:00
|
|
|
if mode == Modes.Shell:
|
|
|
|
call
|
|
|
|
.addMount("--bind", getCurrentDir())
|
|
|
|
.addArg("--chdir", getCurrentDir())
|
|
|
|
|
2021-05-18 22:10:35 +02:00
|
|
|
let configPath = sandboxPath.joinPath("config.json")
|
|
|
|
if fileExists(configPath):
|
|
|
|
call.applyConfig(loadConfig(configPath))
|
|
|
|
|
|
|
|
call.addArg(command).exec()
|