on dcbfa1a help sign in
AppRun.c+2−10
since splitsnapshots
unifiedsplit
@@ -92,7 +92,7 @@ static void add_path(const char* name, const char* rootdir) {
92}
92}
93
93
94#define SAVE_ENV_VAR(x) char *x = getenv(#x)
94#define SAVE_ENV_VAR(x) char *x = getenv(#x)
95−#define LOAD_ENV_VAR(x) do { if (x != NULL) setenv(#x, x, 1); } while(0)
95+#define LOAD_ENV_VAR(x) setenv(#x, x, 1)
96
96
97int main(int argc, char *argv[]) {
97int main(int argc, char *argv[]) {
98 char *appdir = dirname(realpath("/proc/self/exe", NULL));
98 char *appdir = dirname(realpath("/proc/self/exe", NULL));
@@ -207,11 +207,6 @@ int main(int argc, char *argv[]) {
207 err_exit("mount(%s, %s)", usrdir, path_buf);
207 err_exit("mount(%s, %s)", usrdir, path_buf);
208 }
208 }
209
209
210− snprintf(path_buf, sizeof(path_buf), "%s/bin", rootdir);
211− if (symlink("/usr/bin", path_buf) < 0) {
212− err_exit("symlink(/usr/bin, %s)", path_buf);
213− }
214−
215 // fixes issue #1 where writing to /proc/self/gid_map fails
210 // fixes issue #1 where writing to /proc/self/gid_map fails
216 // see user_namespaces(7) for more documentation
211 // see user_namespaces(7) for more documentation
217 int fd_setgroups = open("/proc/self/setgroups", O_WRONLY);
212 int fd_setgroups = open("/proc/self/setgroups", O_WRONLY);
@@ -231,10 +226,8 @@ int main(int argc, char *argv[]) {
231 err_exit("chroot(%s)", rootdir);
226 err_exit("chroot(%s)", rootdir);
232 }
227 }
233
228
234− char *pwddir = getenv("PWD");
235− chdir(pwddir);
229+ chdir("/");
236
230
237− SAVE_ENV_VAR(PWD);
238 SAVE_ENV_VAR(DBUS_SESSION_BUS_ADDRESS);
231 SAVE_ENV_VAR(DBUS_SESSION_BUS_ADDRESS);
239 SAVE_ENV_VAR(USER);
232 SAVE_ENV_VAR(USER);
240 SAVE_ENV_VAR(HOSTNAME);
233 SAVE_ENV_VAR(HOSTNAME);
@@ -250,7 +243,6 @@ int main(int argc, char *argv[]) {
250
243
251 clearenv();
244 clearenv();
252
245
253− LOAD_ENV_VAR(PWD);
254 LOAD_ENV_VAR(DBUS_SESSION_BUS_ADDRESS);
246 LOAD_ENV_VAR(DBUS_SESSION_BUS_ADDRESS);
255 LOAD_ENV_VAR(USER);
247 LOAD_ENV_VAR(USER);
256 LOAD_ENV_VAR(HOSTNAME);
248 LOAD_ENV_VAR(HOSTNAME);
README.md+6−20
@@ -8,6 +8,7 @@ nix-bundle is a way to package Nix attributes into single-file executables.
8* Can be run by non-root users
8* Can be run by non-root users
9* No runtime
9* No runtime
10* Distro agnostic
10* Distro agnostic
11+* Completely portable
11* No installation
12* No installation
12
13
13## Getting started
14## Getting started
@@ -27,7 +28,7 @@ $ ./hello
27Hello, world!
28Hello, world!
28```
29```
29
30
30−This is a standalone file that is completely portable! As long as you are running the same architecture Linux kernel and have a shell interpreter available it will run.
31+This is a standalone file that is completely portable! As long as you are running a same architecture Linux kernel and have a shell interpreter it will run. No external dependencies are required besides a compatible Linux kernel and a shell interpreter.
31
32
32Some others to try:
33Some others to try:
33
34
@@ -35,30 +36,17 @@ Some others to try:
35./nix-bundle.sh nano /bin/nano
36./nix-bundle.sh nano /bin/nano
36```
37```
37
38
38−```sh
39−./nix-bundle.sh emacs /bin/emacs
40−```
41−
42−Or if you want to try graphical applications:
43−
44−```sh
45−# Simple X game. Very few dependencies. Quick to build and load. ~13MB
46−./nix-bundle.sh xskat /bin/xskat
47−```
48−
49```sh
39```sh
50./nix-bundle.sh firefox /bin/firefox
40./nix-bundle.sh firefox /bin/firefox
51```
41```
52
42
53```sh
43```sh
54−# SDL-based game. ~228MB
55−./nix-bundle.sh ivan /bin/ivan
44+./nix-bundle.sh emacs /bin/emacs
56```
45```
57
46
47+## Self-bundling
58
48
59−## Self-bundling (meta)
60−
61−Starting with v0.1.3, you can bundle nix-bundle! To do this, just use nix-bundle normally:
49+Startin with v0.1.3, you can bundle nix-bundle! To do this, just use nix-bundle normally:
62
50
63```sh
51```sh
64NIX_PATH="nixpkgs=https://github.com/matthewbauer/nixpkgs/archive/nix-bundle.tar.gz" ./nix-bundle.sh nix-bundle /bin/nix-bundle
52NIX_PATH="nixpkgs=https://github.com/matthewbauer/nixpkgs/archive/nix-bundle.tar.gz" ./nix-bundle.sh nix-bundle /bin/nix-bundle
@@ -66,7 +54,7 @@ NIX_PATH="nixpkgs=https://github.com/matthewbauer/nixpkgs/archive/nix-bundle.tar
66
54
67## [Experimental] Create AppImage executables from Nix expressions
55## [Experimental] Create AppImage executables from Nix expressions
68
56
69−"nix-bundle.sh" tends to create fairly large outputs. This is largely because nix-bundle.sh "extracts" its payload up front. AppImage uses a different method where extraction only takes place when the file is accessed (through FUSE and SquashFS). You can now create a compliant "AppImage" using the "nix2appimage.sh" script:
57+"nix-bundle.sh" tends to create fairly large outputs. This is largely because nix-bundle.sh uses gzip compression and AppImage uses lzma compression. Anyway, you can create a compliant "AppImage" using the "nix2appimage.sh" script:
70
58
71```sh
59```sh
72./nix2appimage.sh emacs
60./nix2appimage.sh emacs
@@ -96,8 +84,6 @@ Some other examples to try:
96
84
97These may take a while because of the large closure size.
85These may take a while because of the large closure size.
98
86
99−Note that these do not currently work out of the box with NixOS. Other Linux distros should work.
100−
101## Comparison with AppImage, FlatPak, Snappy
87## Comparison with AppImage, FlatPak, Snappy
102
88
103| Name | Distro-agnostic | Runtime required | Root required | Storage |
89| Name | Distro-agnostic | Runtime required | Root required | Storage |
appdir.nix+6−6
@@ -1,14 +1,14 @@
1−{ stdenv, lib, fetchurl, muslPkgs, perl, pathsFromGraph, fetchFromGitHub, coreutils, bash }:
1+{ stdenv, fetchurl, perl, pathsFromGraph, fetchFromGitHub, musl, coreutils, bash }:
2
2
3let
3let
4− AppRun = targets: muslPkgs.stdenv.mkDerivation {
4+ AppRun = targets: stdenv.mkDerivation {
5 name = "AppRun";
5 name = "AppRun";
6
6
7 phases = [ "buildPhase" "installPhase" "fixupPhase" ];
7 phases = [ "buildPhase" "installPhase" "fixupPhase" ];
8
8
9 buildPhase = ''
9 buildPhase = ''
10− CC="$CC -O2 -Wall -Wno-deprecated-declarations -Wno-unused-result -static"
10+ CC="${musl}/bin/musl-gcc -O2 -Wall -Wno-deprecated-declarations -Wno-unused-result -static"
11− $CC ${./AppRun.c} -o AppRun -DENV_PATH='"${lib.makeBinPath targets}"'
11+ $CC ${./AppRun.c} -o AppRun -DENV_PATH='"${stdenv.lib.makeBinPath targets}"'
12 '';
12 '';
13
13
14 installPhase = ''
14 installPhase = ''
@@ -63,12 +63,12 @@ in
63
63
64 # icons
64 # icons
65 if [ -d ${target}/share/icons ]; then
65 if [ -d ${target}/share/icons ]; then
66− icon=$(find ${target}/share/icons -name "${name}*.png" | head -n1)
66+ icon=$(find ${target}/share/icons -name "${name}.png" | head -n1)
67 if ! [ -z "$icon" ]; then
67 if ! [ -z "$icon" ]; then
68 ln -s .$icon
68 ln -s .$icon
69 ln -s .$icon .DirIcon
69 ln -s .$icon .DirIcon
70 else
70 else
71− icon=$(find ${target}/share/icons -name "${name}*.svg" | head -n1)
71+ icon=$(find ${target}/share/icons -name "${name}.svg" | head -n1)
72 if ! [ -z "$icon" ]; then
72 if ! [ -z "$icon" ]; then
73 ln -s .$icon
73 ln -s .$icon
74 ln -s .$icon .DirIcon
74 ln -s .$icon .DirIcon
appimage-bundle.nixdeleted−61
@@ -1,61 +0,0 @@
1−# use like this:
2−# nix-build appimage-bundle.nix --argstr package hello --argstr exec hello
3−# nix-build appimage-bundle.nix --arg package 'with import <nixpkgs>{}; writers.writePython3Bin "helloThere.py" {} "print(1)\n"' --argstr exec helloThere.py
4−
5−
6−{nixpkgs ? import <nixpkgs>{},
7−package,
8−exec,
9−... }:
10−let
11− appimage_src = drv : exec : with nixpkgs;
12− self.stdenv.mkDerivation rec {
13− name = drv.name + "-appdir";
14− env = buildEnv {
15− inherit name;
16− paths = buildInputs;
17− };
18− src = env;
19− inherit exec;
20− buildInputs = [ drv ];
21− buildCommand = ''
22− mkdir -p $out/share/icons/hicolor/256x256/apps
23− mkdir -p $out/share/applications
24−
25− shopt -s extglob
26− ln -s ${env}/!(share) $out/
27− ln -s ${env}/share/* $out/share/
28−
29− touch $out/share/icons/hicolor/256x256/apps/${drv.name}.png
30− touch $out/share/icons/${drv.name}.png
31−
32− cat <<EOF > $out/share/applications/${drv.name}.desktop
33− [Desktop Entry]
34− Type=Application
35− Version=1.0
36− Name=${drv.name}
37− Path=${env}
38− Icon=${drv.name}
39− Exec=$exec
40− Terminal=true
41− EOF
42− '';
43− system = builtins.currentSystem;
44− };
45−
46−in
47− let results =
48− if (nixpkgs.lib.isDerivation package && !(nixpkgs.lib.isString package))
49− then {
50− name = package.name;
51− target = appimage_src package "${exec}";
52− extraTargets = [];
53− }
54− else {
55− name = nixpkgs."${package}".name;
56− target = appimage_src (nixpkgs."${package}") "${exec}";
57− extraTargets = [];
58− };
59− in
60− with (import (./appimage-top.nix){nixpkgs' = nixpkgs.path;});
61− (appimage (appdir results )).overrideAttrs (old: {name = results.name;})
appimage-top.nix+6−10
@@ -1,17 +1,13 @@
1−{ nixpkgs' ? <nixpkgs> }:
1+{nixpkgs ? import <nixpkgs> {}}:
2
2
3−let
4− pkgs = import nixpkgs' { };
5− muslPkgs = import nixpkgs' {
3+with nixpkgs;
6− localSystem.config = "x86_64-unknown-linux-musl";
7− };
8
4
9−in rec {
5+rec {
10− appimagetool = pkgs.callPackage ./appimagetool.nix {};
6+ appimagetool = callPackage ./appimagetool.nix {};
11
7
12− appimage = pkgs.callPackage ./appimage.nix {
8+ appimage = callPackage ./appimage.nix {
13 inherit appimagetool;
9 inherit appimagetool;
14 };
10 };
15
11
16− appdir = pkgs.callPackage ./appdir.nix { inherit muslPkgs; };
12+ appdir = callPackage ./appdir.nix {};
17}
13}
appimagetool.nix+11−13
@@ -1,18 +1,16 @@
1−{ stdenv, lib, fetchurl, fuse, zlib, squashfsTools, glib }:
1+{ stdenv, fetchurl, fuse, zlib, squashfsTools, glib }:
2
2
3# This is from some binaries.
3# This is from some binaries.
4
4
5# Ideally, this should be source based,
5# Ideally, this should be source based,
6# but I can't get it to build from GitHub
6# but I can't get it to build from GitHub
7
7
8−let
9− inherit (stdenv.cc.bintools) dynamicLinker;
10−in stdenv.mkDerivation rec {
8+stdenv.mkDerivation rec {
11 name = "appimagekit";
9 name = "appimagekit";
12
10
13 src = fetchurl {
11 src = fetchurl {
14− url = "https://github.com/AppImage/AppImageKit/releases/download/10/appimagetool-x86_64.AppImage";
12+ url = "https://github.com/probonopd/AppImageKit/releases/download/7/appimagetool-x86_64.AppImage";
15− sha256 = "03zbiblj8a1yk1xsb5snxi4ckwn3diyldg1jh5hdjjhsmpw652ig";
13+ sha256 = "1irvbf0xnya16cyzpvr43jviq5ly3wl7b9753rji7d1hhxwb7b9r";
16 };
14 };
17
15
18 buildInputs = [
16 buildInputs = [
@@ -24,7 +22,7 @@ in stdenv.mkDerivation rec {
24 unpackPhase = ''
22 unpackPhase = ''
25 cp $src appimagetool-x86_64.AppImage
23 cp $src appimagetool-x86_64.AppImage
26 chmod u+wx appimagetool-x86_64.AppImage
24 chmod u+wx appimagetool-x86_64.AppImage
27− patchelf --set-interpreter ${dynamicLinker} \
25+ patchelf --set-interpreter $(cat $NIX_CC/nix-support/dynamic-linker) \
28 --set-rpath ${fuse}/lib:${zlib}/lib \
26 --set-rpath ${fuse}/lib:${zlib}/lib \
29 appimagetool-x86_64.AppImage
27 appimagetool-x86_64.AppImage
30 ./appimagetool-x86_64.AppImage --appimage-extract
28 ./appimagetool-x86_64.AppImage --appimage-extract
@@ -34,12 +32,12 @@ in stdenv.mkDerivation rec {
34 mkdir -p $out
32 mkdir -p $out
35 cp -r usr/* $out
33 cp -r usr/* $out
36
34
37− for x in $out/bin/*; do
35+ patchelf --set-interpreter $(cat $NIX_CC/nix-support/dynamic-linker) \
38− patchelf \
39− --set-interpreter ${dynamicLinker} \
40− --set-rpath ${lib.makeLibraryPath [ zlib stdenv.glibc.out fuse glib ]} \
36+ --set-rpath ${stdenv.glibc.out}/lib:${fuse}/lib:${zlib}/lib:${glib}/lib \
41− $x
37+ $out/bin/appimagetool
42− done
38+ patchelf --set-interpreter $(cat $NIX_CC/nix-support/dynamic-linker) \
39+ --set-rpath ${zlib}/lib \
40+ $out/bin/mksquashfs
43 '';
41 '';
44
42
45 dontStrip = true;
43 dontStrip = true;
default.nix+26−46
@@ -2,29 +2,12 @@
2
2
3with nixpkgs;
3with nixpkgs;
4
4
5−let
6− arx' = haskellPackages.arx.overrideAttrs (o: {
7− patchPhase = (o.patchPhase or "") + ''
8− substituteInPlace model-scripts/tmpx.sh \
9− --replace /tmp/ \$HOME/.cache/
10− '';
11− });
12−in rec {
5+rec {
13− toStorePath = target:
14− # If a store path has been given but is not a derivation, add the missing context
15− # to it so it will be propagated properly as a build input.
16− if !(lib.isDerivation target) && lib.isStorePath target then
17− let path = toString target; in
18− builtins.appendContext path { "${path}" = { path = true; }; }
19− # Otherwise, add to the store. This takes care of appending the store path
20− # in the context automatically.
21− else "${target}";
22−
23 arx = { archive, startup}:
6 arx = { archive, startup}:
24 stdenv.mkDerivation {
7 stdenv.mkDerivation {
25 name = "arx";
8 name = "arx";
26 buildCommand = ''
9 buildCommand = ''
27− ${arx'}/bin/arx tmpx --shared -rm! ${archive} -o $out // ${startup}
10+ ${haskellPackages.arx}/bin/arx tmpx ${archive} -rm! -o $out // ${startup}
28 chmod +x $out
11 chmod +x $out
29 '';
12 '';
30 };
13 };
@@ -45,12 +28,10 @@ in rec {
45 };
28 };
46
29
47 # TODO: eventually should this go in nixpkgs?
30 # TODO: eventually should this go in nixpkgs?
48− nix-user-chroot = lib.makeOverridable stdenv.mkDerivation {
31+ nix-user-chroot = stdenv.lib.makeOverridable stdenv.mkDerivation {
49 name = "nix-user-chroot-2c52b5f";
32 name = "nix-user-chroot-2c52b5f";
50 src = ./nix-user-chroot;
33 src = ./nix-user-chroot;
51
34
52− makeFlags = [];
53−
54 # hack to use when /nix/store is not available
35 # hack to use when /nix/store is not available
55 postFixup = ''
36 postFixup = ''
56 exe=$out/bin/nix-user-chroot
37 exe=$out/bin/nix-user-chroot
@@ -68,8 +49,6 @@ in rec {
68
49
69 runHook postInstall
50 runHook postInstall
70 '';
51 '';
71−
72− meta.platforms = lib.platforms.linux;
73 };
52 };
74
53
75 makebootstrap = { targets, startup }:
54 makebootstrap = { targets, startup }:
@@ -80,40 +59,41 @@ in rec {
80 };
59 };
81 };
60 };
82
61
83− makeStartup = { target, nixUserChrootFlags, nix-user-chroot', run, initScript }:
62+ makeStartup = { target, nixUserChrootFlags, nix-user-chroot', run }:
84− let
85− # Avoid re-adding a store path into the store
86− path = toStorePath target;
87− in
88 writeScript "startup" ''
63 writeScript "startup" ''
89− #!/bin/sh
64+ #!/bin/sh
90− ${initScript}
91− .${nix-user-chroot'}/bin/nix-user-chroot -n ./nix ${nixUserChrootFlags} -- ${path}${run} "$@"
65+ .${nix-user-chroot'}/bin/nix-user-chroot -n ./nix ${nixUserChrootFlags} -- ${target}${run} $@
92 '';
66 '';
93
67
94− nix-bootstrap = { target, extraTargets ? [], run, nix-user-chroot' ? nix-user-chroot, nixUserChrootFlags ? "", initScript ? "" }:
68+ nix-bootstrap = { target, extraTargets ? [], run, nix-user-chroot' ? nix-user-chroot, nixUserChrootFlags ? "" }:
95 let
69 let
96− script = makeStartup { inherit target nixUserChrootFlags nix-user-chroot' run initScript; };
70+ script = makeStartup { inherit target nixUserChrootFlags nix-user-chroot' run; };
97 in makebootstrap {
71 in makebootstrap {
98− startup = ".${script} '\"$@\"'";
72+ startup = ".${script}";
99 targets = [ "${script}" ] ++ extraTargets;
73 targets = [ "${script}" ] ++ extraTargets;
100 };
74 };
101
75
76+ # special case handling because of impurities in nix bootstrap
77+ # anything that needs Nix will have to have these setup before they can be run
102− nix-bootstrap-nix = {target, run, extraTargets ? []}:
78+ nix-bootstrap-nix = let
103− nix-bootstrap-path {
79+ nix-user-chroot' = nix-user-chroot.override {
104− inherit target run;
80+ buildInputs = [ cacert gnutar bzip2 gzip coreutils ];
105− extraTargets = [ gnutar bzip2 xz gzip coreutils bash ];
81+ makeFlags = [
106− };
82+ ''NIX_SSL_CERT_FILE="${cacert}/etc/ssl/certs/ca-bundle.crt"''
83+ ''NIX_PATH="nixpkgs=https://github.com/matthewbauer/nixpkgs/archive/nix-bundle.tar.gz"''
84+ ''ENV_PATH="${stdenv.lib.makeBinPath [ coreutils gnutar bzip2 gzip bash ]}"''
85+ ];
86+ }; in { target, extraTargets ? [], run }: nix-bootstrap { inherit target extraTargets run nix-user-chroot'; };
107
87
108 # special case adding path to the environment before launch
88 # special case adding path to the environment before launch
109 nix-bootstrap-path = let
89 nix-bootstrap-path = let
110− nix-user-chroot'' = targets: nix-user-chroot.overrideDerivation (o: {
90+ nix-user-chroot'' = targets: nix-user-chroot.override {
111− buildInputs = o.buildInputs ++ targets;
91+ buildInputs = targets;
112− makeFlags = o.makeFlags ++ [
92+ makeFlags = [
113− ''ENV_PATH="${lib.makeBinPath targets}"''
93+ ''ENV_PATH="${stdenv.lib.makeBinPath targets}"''
114 ];
94 ];
115− }); in { target, extraTargets ? [], run, initScript ? "" }: nix-bootstrap {
95+ }; in { target, extraTargets ? [], run }: nix-bootstrap {
116− inherit target extraTargets run initScript;
96+ inherit target extraTargets run;
117 nix-user-chroot' = nix-user-chroot'' extraTargets;
97 nix-user-chroot' = nix-user-chroot'' extraTargets;
118 };
98 };
119}
99}
flake.nixdeleted−26
@@ -1,26 +0,0 @@
1−{
2− description = "The purely functional package manager";
3−
4− inputs.nixpkgs.url = "nixpkgs/nixos-20.03-small";
5−
6− outputs = { self, nixpkgs }: let
7− systems = [ "x86_64-linux" "i686-linux" "aarch64-linux" ];
8− forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f system);
9− in {
10− bundlers = {
11− nix-bundle = { program, system }: let
12− nixpkgs' = nixpkgs.legacyPackages.${system};
13− nix-bundle = import self { nixpkgs = nixpkgs'; };
14− script = nixpkgs'.writeScript "startup" ''
15− #!/bin/sh
16− .${nix-bundle.nix-user-chroot}/bin/nix-user-chroot -n ./nix -- ${program} "$@"
17− '';
18− in nix-bundle.makebootstrap {
19− targets = [ script ];
20− startup = ".${builtins.unsafeDiscardStringContext script} '\"$@\"'";
21− };
22− };
23−
24− defaultBundler = self.bundlers.nix-bundle;
25− };
26−}
nix-bootstrap.sh+13−13
@@ -1,35 +1,35 @@
1#!/bin/sh
1#!/bin/sh
2
2
3+cmd=sh
3−if [ $# -gt 0 ]; then
4+if ! [ $# -eq 0 ]; then
4− set -- sh
5+ cmd=$@
5fi
6fi
6
7
7# should download this in the future
8# should download this in the future
8# but the mirror is down
9# but the mirror is down
9−proot=$(dirname "$0")/proot-$(uname -p)
10+proot=`dirname $0`/proot-`uname -p`
10export PROOT_NO_SECCOMP=1
11export PROOT_NO_SECCOMP=1
11
12
12nixdir=$HOME/.nix
13nixdir=$HOME/.nix
13
14
14OLD_NIX_PATH=$NIX_PATH
15OLD_NIX_PATH=$NIX_PATH
15−# shellcheck disable=SC1090
16−if [ -e "$HOME/.nix-profile/etc/profile.d/nix.sh" ]; then . "$HOME/.nix-profile/etc/profile.d/nix.sh"; fi
16+if [ -e $HOME/.nix-profile/etc/profile.d/nix.sh ]; then . $HOME/.nix-profile/etc/profile.d/nix.sh; fi
17−if [ -n "$OLD_NIX_PATH" ]; then NIX_PATH="$OLD_NIX_PATH"; fi
17+if ! [ -z "$OLD_NIX_PATH" ]; then NIX_PATH="$OLD_NIX_PATH"; fi
18
18
19if [ -z "$IN_PROOT" ]; then
19if [ -z "$IN_PROOT" ]; then
20 export IN_PROOT=1
20 export IN_PROOT=1
21
21
22− if ! [ -d "$nixdir" ]; then
22+ if ! [ -d $nixdir ]; then
23− mkdir -p "$nixdir"
23+ mkdir -p $nixdir
24 s=$(mktemp)
24 s=$(mktemp)
25− curl https://nixos.org/nix/install -o "$s"
25+ curl https://nixos.org/nix/install -o $s
26− $proot -b "$nixdir:/nix" "$0" sh "$s"
26+ $proot -b $nixdir:/nix $0 sh $s
27 fi
27 fi
28
28
29− $proot -b "$nixdir:/nix" "$0" "$@"
29+ $proot -b $nixdir:/nix $0 $cmd
30
30
31 export IN_PROOT=
31 export IN_PROOT=
32 exit
32 exit
33−elif [ $# -gt 0 ]; then
33+elif ! [ $# -eq 0 ]; then
34− exec "$@"
34+ exec $cmd
35fi
35fi
nix-bundle.sh+7−12
@@ -8,9 +8,6 @@ Usage: $0 TARGET EXECUTABLE
8Create a single-file bundle from the nixpkgs attribute "TARGET".
8Create a single-file bundle from the nixpkgs attribute "TARGET".
9EXECUTABLE should be relative to the TARGET's output path.
9EXECUTABLE should be relative to the TARGET's output path.
10
10
11−The TARGET is either an attribute in nixpkgs, or an absolute path to the
12−store.
13−
14For example:
11For example:
15
12
16$ $0 hello /bin/hello
13$ $0 hello /bin/hello
@@ -22,7 +19,7 @@ EOF
22 exit 1
19 exit 1
23fi
20fi
24
21
25−nix_file=$(dirname "$0")/default.nix
22+nix_file=`dirname $0`/default.nix
26
23
27target="$1"
24target="$1"
28shift
25shift
@@ -39,25 +36,23 @@ exec="$1"
39shift
36shift
40
37
41bootstrap=nix-bootstrap
38bootstrap=nix-bootstrap
42−if [ "$target" = "nix-bundle" ] || [ "$target" = "nixStable" ] || [ "$target" = "nixUnstable" ] || [ "$target" = "nix" ]; then
39+if [ "$target" = "nix-bundle" ] || [ "$target" = "nixStable" ] || [ "$target" = "nixUnstable" ]; then
43 bootstrap=nix-bootstrap-nix
40 bootstrap=nix-bootstrap-nix
44−elif [ -n "$extraTargets" ]; then
41+elif ! [ -z "$extraTargets" ]; then
45 bootstrap=nix-bootstrap-path
42 bootstrap=nix-bootstrap-path
46fi
43fi
47
44
48expr="with import <nixpkgs> {}; with import $nix_file {}; $bootstrap { target = $target; extraTargets = [ $extraTargets ]; run = \"$exec\"; }"
45expr="with import <nixpkgs> {}; with import $nix_file {}; $bootstrap { target = $target; extraTargets = [ $extraTargets ]; run = \"$exec\"; }"
49
46
50−drv=$(nix-instantiate --no-gc-warning -E "$expr")
47+out=$(nix-store --no-gc-warning -r $(nix-instantiate --no-gc-warning -E "$expr"))
51−
52−out=$(nix-store --no-gc-warning --realize "$drv")
53
48
54if [ -z "$out" ]; then
49if [ -z "$out" ]; then
55 >&2 echo "$0 failed. Exiting."
50 >&2 echo "$0 failed. Exiting."
56 exit 1
51 exit 1
57elif [ -t 1 ]; then
52elif [ -t 1 ]; then
58− filename=$(basename "$exec")
53+ filename=$(basename $exec)
59 echo "Nix bundle created at $filename."
54 echo "Nix bundle created at $filename."
60− cp -f "$out" "$filename"
55+ cp -f $out $filename
61else
56else
62− echo "$out"
57+ cat $out
63fi
58fi
nix-run.sh+21−23
@@ -18,11 +18,11 @@ if [ -z "$1" ]; then
18 exit 1
18 exit 1
19fi
19fi
20
20
21−pkg="$1"
21+pkg=$1
22shift
22shift
23
23
24# A second argument will provide a hint to run
24# A second argument will provide a hint to run
25−if [ -n "$1" ]; then
25+if ! [ -z "$1" ]; then
26 name="$1"
26 name="$1"
27 shift
27 shift
28else
28else
@@ -31,7 +31,7 @@ fi
31
31
32expr="with import <nixpkgs> {}; let x = ($pkg); in x"
32expr="with import <nixpkgs> {}; let x = ($pkg); in x"
33path=$(nix-instantiate --no-gc-warning -E "$expr")
33path=$(nix-instantiate --no-gc-warning -E "$expr")
34−out=$(nix-store --no-gc-warning -r "$path")
34+out=$(nix-store --no-gc-warning -r $path)
35
35
36if [ -z "$out" ]; then
36if [ -z "$out" ]; then
37 >&2 echo "Could not evaluate $pkg to a Nix drv."
37 >&2 echo "Could not evaluate $pkg to a Nix drv."
@@ -43,7 +43,7 @@ run_darwin_app () {
43 dir="$1"
43 dir="$1"
44 shift
44 shift
45
45
46− open -a "$dir" --args "$@"
46+ open -a "$dir" --args $@
47}
47}
48
48
49# Run FILE as a Freedesktop application
49# Run FILE as a Freedesktop application
@@ -53,16 +53,14 @@ run_linux_desktop_app () {
53 file="$1"
53 file="$1"
54 shift
54 shift
55
55
56− cmd=$(grep '^Exec' "$file" | tail -1 | \
56+ cmd=$(grep '^Exec' $file | tail -1 | \
57− sed 's/Exec=//;s/^"//;s/" *$//')
57+ sed 's/Exec=//;s/^"//;s/" *$/')
58
58
59− if [ "$#" -gt 0 ]; then
59+ if ! [ -z "$@" ]; then
60− cmd=$(echo "$cmd" | sed "s/%[fu]/$1/;s/%[FU]/$*/")
60+ cmd=$(echo "$cmd" | sed "s/%[fu]/$1/;s/%[FU]/$@/")
61 fi
61 fi
62
62
63 cmd=$(echo "$cmd" | sed "s/%k/$desktop/;s/%.//")
63 cmd=$(echo "$cmd" | sed "s/%k/$desktop/;s/%.//")
64−
65− "$cmd" "$@"
66}
64}
67
65
68# Run FILE as an ordinary binary
66# Run FILE as an ordinary binary
@@ -70,30 +68,30 @@ run_bin () {
70 file="$1"
68 file="$1"
71 shift
69 shift
72
70
73− "$file" "$@"
71+ $file $@
74}
72}
75
73
76if [ -x "$out/nix-support/run" ]; then
74if [ -x "$out/nix-support/run" ]; then
77− run_bin "$out/nix-support/run" "$@"
75+ run_bin "$out/nix-support/run" $@
78elif [ -x "$out/bin/run" ]; then
76elif [ -x "$out/bin/run" ]; then
79− run_bin "$out/bin/run" "$@"
77+ run_bin "$out/bin/run" $@
80elif [ "$(uname)" = Darwin ] && [ -d "$out/Applications/$name.app" ]; then
78elif [ "$(uname)" = Darwin ] && [ -d "$out/Applications/$name.app" ]; then
81− run_darwin_app "$out/Applications/$name.app" "$@"
79+ run_darwin_app "$out/Applications/$name.app" $@
82−elif [ "$(uname)" = Darwin ] && [ -d "$out"/Applications/*.app ]; then
80+elif [ "$(uname)" = Darwin ] && [ -d $out/Applications/*.app ]; then
83− for f in "$out"/Applications/*.app; do
81+ for f in $out/Applications/*.app; do
84− run_darwin_app "$f" "$@"
82+ run_darwin_app "$f" $@
85 done
83 done
86elif [ -f "$out/share/applications/$name.desktop" ]; then
84elif [ -f "$out/share/applications/$name.desktop" ]; then
87− run_linux_desktop_app "$out/share/applications/$name.desktop" "$@"
85+ run_linux_desktop_app "$out/share/applications/$name.desktop" $@
88−elif [ -d "$out"/share/applications ]; then
86+elif [ -d $out/share/applications ]; then
89− for f in "$out"/share/applications/*.desktop; do
87+ for f in $out/share/applications/*.desktop; do
90 run_linux_desktop_app "$f"
88 run_linux_desktop_app "$f"
91 done
89 done
92elif [ -x "$out/bin/$name" ]; then
90elif [ -x "$out/bin/$name" ]; then
93− run_bin "$out/bin/$name" "$@"
91+ run_bin "$out/bin/$name" $@
94elif [ -d "$out/bin" ]; then
92elif [ -d "$out/bin" ]; then
95− for bin in "$out"/bin/*; do
93+ for bin in $out/bin/*; do
96− run_bin "$bin" "$@"
94+ run_bin "$bin" $@
97 done
95 done
98else
96else
99 >&2 echo "Cannot find a way to run path $out."
97 >&2 echo "Cannot find a way to run path $out."
nix-user-chroot/Makefile+3−1
@@ -1,4 +1,6 @@
1+NIX_PATH ?= "nixpkgs=https://github.com/NixOS/nixpkgs/archive/master.tar.gz"
2+NIX_SSL_CERT_FILE ?= "/homeless-shelter"
1ENV_PATH ?= ""
3ENV_PATH ?= ""
2
4
3nix-user-chroot: main.cpp
5nix-user-chroot: main.cpp
4− g++ -o nix-user-chroot -DENV_PATH='$(ENV_PATH)' main.cpp
6+ g++ -o nix-user-chroot -DNIX_PATH='$(NIX_PATH)' -DNIX_SSL_CERT_FILE='$(NIX_SSL_CERT_FILE)' -DENV_HOME='$(ENV_HOME)' -DENV_PATH='$(ENV_PATH)' main.cpp
nix-user-chroot/main.cpp+41−115
@@ -26,10 +26,6 @@
26using namespace std;
26using namespace std;
27
27
28#define err_exit(format, ...) { fprintf(stderr, format ": %s\n", ##__VA_ARGS__, strerror(errno)); exit(EXIT_FAILURE); }
28#define err_exit(format, ...) { fprintf(stderr, format ": %s\n", ##__VA_ARGS__, strerror(errno)); exit(EXIT_FAILURE); }
29−static int child_proc(const char *rootdir, const char *nixdir, uint8_t clear_env, list<struct DirMapping> dirMappings, list<struct SetEnv> envMappings, const char *executable, char * const new_argv[]);
30−
31−volatile uint8_t child_died = 0;
32−int child_pid = 0;
33
29
34static void usage(const char *pname) {
30static void usage(const char *pname) {
35 fprintf(stderr, "Usage: %s -n <nixpath> -- <command>\n", pname);
31 fprintf(stderr, "Usage: %s -n <nixpath> -- <command>\n", pname);
@@ -37,7 +33,6 @@ static void usage(const char *pname) {
37 fprintf(stderr, "\t-m <src>:<src>\tmap src on the host to dest in the sandbox\n");
33 fprintf(stderr, "\t-m <src>:<src>\tmap src on the host to dest in the sandbox\n");
38 fprintf(stderr, "\t-d\tdelete all default dir mappings, may break things\n");
34 fprintf(stderr, "\t-d\tdelete all default dir mappings, may break things\n");
39 fprintf(stderr, "\t-p <var>\tpreserve the value of a variable across the -c clear\n");
35 fprintf(stderr, "\t-p <var>\tpreserve the value of a variable across the -c clear\n");
40− fprintf(stderr, "\t-e\tadd an /escape-hatch to the sandbox, and run (outside the sandbox) any strings written to it\n");
41
36
42 exit(EXIT_FAILURE);
37 exit(EXIT_FAILURE);
43}
38}
@@ -96,15 +91,8 @@ struct DirMapping parseMapping(string input) {
96 return (struct DirMapping){ src, dest };
91 return (struct DirMapping){ src, dest };
97}
92}
98
93
99−static void handle_child_death(int signo, siginfo_t *info, void *context) {
100− if ( (child_pid == 0) || (info->si_pid == child_pid) ) {
101− child_died = 1;
102− }
103−}
104−
105int main(int argc, char *argv[]) {
94int main(int argc, char *argv[]) {
106 uint8_t clear_env = 0;
95 uint8_t clear_env = 0;
107− uint8_t enable_escape_hatch = 0;
108 char *nixdir = NULL;
96 char *nixdir = NULL;
109 list<struct DirMapping> dirMappings;
97 list<struct DirMapping> dirMappings;
110 list<struct SetEnv> envMappings;
98 list<struct SetEnv> envMappings;
@@ -117,20 +105,14 @@ int main(int argc, char *argv[]) {
117 x("run");
105 x("run");
118 x("tmp");
106 x("tmp");
119 x("var");
107 x("var");
120− x("etc");
121− x("usr");
122− x("home");
123− x("root");
124#undef x
108#undef x
125
109
126 int opt;
110 int opt;
127− while ((opt = getopt(argc, argv, "cen:m:dp:")) != -1) {
111+ while ((opt = getopt(argc, argv, "cn:m:dp:")) != -1) {
128 switch (opt) {
112 switch (opt) {
129 case 'c':
113 case 'c':
130 clear_env = 1;
114 clear_env = 1;
131− break;
115+ puts("clearing env");
132− case 'e':
133− enable_escape_hatch = 1;
134 break;
116 break;
135 case 'n':
117 case 'n':
136 // determine absolute directory for nix dir
118 // determine absolute directory for nix dir
@@ -179,74 +161,13 @@ int main(int argc, char *argv[]) {
179 err_exit("mkdtemp(%s)", template_);
161 err_exit("mkdtemp(%s)", template_);
180 }
162 }
181
163
182− int unrace[2];
183−
184− if (pipe(unrace)) {
185− err_exit("pipe()");
186− }
187−
188− struct sigaction handle_child;
189− handle_child.sa_sigaction = handle_child_death;
190− handle_child.sa_flags = SA_SIGINFO;
191−
192− struct sigaction old_handler;
193− if (sigaction(SIGCHLD, &handle_child, &old_handler)) {
194− err_exit("sigaction()");
195− }
196−
197− int child;
198− child = child_pid = fork();
199− if (child < 0) {
200− err_exit("fork()");
201− } else if (child == 0) {
202− sigaction(SIGCHLD, &old_handler, NULL);
203− close(unrace[1]);
204− char buf[10];
205− read(unrace[0], buf, 10);
206− close(unrace[0]);
207− return child_proc(rootdir, nixdir, clear_env, dirMappings, envMappings, argv[optind], argv + optind);
208− } else {
209− close(unrace[0]);
210− char fifopath[PATH_MAX];
211− if (enable_escape_hatch) {
212− snprintf(fifopath, PATH_MAX, "%s/escape-hatch", rootdir);
213− mkfifo(fifopath, 0600);
214− }
215− close(unrace[1]);
216− if (enable_escape_hatch) {
217− char buffer[1024];
218− while (!child_died) {
219− int fd = open(fifopath, O_RDONLY);
220− if (fd < 0) {
221− if (errno == EINTR) continue;
222− fprintf(stderr, "error opening escape-hatch: %s\n", strerror(errno));
223− continue;
224− }
225− int size = read(fd, buffer, 1024);
226− buffer[size] = 0;
227− system(buffer);
228− close(fd);
229− }
230− }
231− int status;
232− int ret = waitpid(child, &status, 0);
233− return WEXITSTATUS(status);
234− }
235−}
236−
237−static int child_proc(const char *rootdir, const char *nixdir, uint8_t clear_env, list<struct DirMapping> dirMappings, list<struct SetEnv> envMappings, const char *executable, char * const new_argv[]) {
238 // get uid, gid before going to new namespace
164 // get uid, gid before going to new namespace
239 uid_t uid = getuid();
165 uid_t uid = getuid();
240 gid_t gid = getgid();
166 gid_t gid = getgid();
241
167
242 // "unshare" into new namespace
168 // "unshare" into new namespace
243 if (unshare(CLONE_NEWNS | CLONE_NEWUSER) < 0) {
169 if (unshare(CLONE_NEWNS | CLONE_NEWUSER) < 0) {
244− if (errno == EPERM) {
245− fputs("Run the following to enable unprivileged namespace use:\nsudo bash -c \"sysctl -w kernel.unprivileged_userns_clone=1 ; echo kernel.unprivileged_userns_clone=1 > /etc/sysctl.d/nix-user-chroot.conf\"\n\n", stderr);
246− exit(EXIT_FAILURE);
247− } else {
248− err_exit("unshare()");
170+ err_exit("unshare()");
249− }
250 }
171 }
251
172
252 // add necessary system stuff to rootdir namespace
173 // add necessary system stuff to rootdir namespace
@@ -256,52 +177,57 @@ static int child_proc(const char *rootdir, const char *nixdir, uint8_t clear_env
256 add_path(m.src, m.dest, rootdir);
177 add_path(m.src, m.dest, rootdir);
257 }
178 }
258
179
259− // make sure nixdir exists
180+ char path_buf[PATH_MAX];
260− struct stat statbuf2;
181+ snprintf(path_buf, sizeof(path_buf), "%s/tmp", rootdir);
261− if (stat(nixdir, &statbuf2) < 0) {
182+ mkdir(path_buf, ~0);
262− err_exit("stat(%s)", nixdir);
183+ snprintf(path_buf, sizeof(path_buf), "%s/var", rootdir);
263− }
264
184
265− char path_buf[PATH_MAX];
185+ // make sure nixdir exists
266− // mount /nix to new namespace
186+ struct stat statbuf2;
267− snprintf(path_buf, sizeof(path_buf), "%s/nix", rootdir);
187+ if (stat(nixdir, &statbuf2) < 0) {
268− mkdir(path_buf, statbuf2.st_mode & ~S_IFMT);
269− if (mount(nixdir, path_buf, "none", MS_BIND | MS_REC, NULL) < 0) {
270− err_exit("mount(%s, %s)", nixdir, path_buf);
188+ err_exit("stat(%s)", nixdir);
271− }
189+ }
272
190
191+ // mount /nix to new namespace
192+ snprintf(path_buf, sizeof(path_buf), "%s/nix", rootdir);
193+ mkdir(path_buf, statbuf2.st_mode & ~S_IFMT);
194+ if (mount(nixdir, path_buf, "none", MS_BIND | MS_REC, NULL) < 0) {
195+ err_exit("mount(%s, %s)", nixdir, path_buf);
196+ }
197+
273− // fixes issue #1 where writing to /proc/self/gid_map fails
198+ // fixes issue #1 where writing to /proc/self/gid_map fails
274− // see user_namespaces(7) for more documentation
199+ // see user_namespaces(7) for more documentation
275− int fd_setgroups = open("/proc/self/setgroups", O_WRONLY);
200+ int fd_setgroups = open("/proc/self/setgroups", O_WRONLY);
276− if (fd_setgroups > 0) {
201+ if (fd_setgroups > 0) {
277− write(fd_setgroups, "deny", 4);
202+ write(fd_setgroups, "deny", 4);
278− close(fd_setgroups);
279− }
203+ }
280
204
281− // map the original uid/gid in the new ns
205+ // map the original uid/gid in the new ns
282− char map_buf[1024];
206+ char map_buf[1024];
283− snprintf(map_buf, sizeof(map_buf), "%d %d 1", uid, uid);
207+ snprintf(map_buf, sizeof(map_buf), "%d %d 1", uid, uid);
284− update_map(map_buf, "/proc/self/uid_map");
208+ update_map(map_buf, "/proc/self/uid_map");
285− snprintf(map_buf, sizeof(map_buf), "%d %d 1", gid, gid);
209+ snprintf(map_buf, sizeof(map_buf), "%d %d 1", gid, gid);
286− update_map(map_buf, "/proc/self/gid_map");
210+ update_map(map_buf, "/proc/self/gid_map");
287
211
288− // chroot to rootdir
212+ // chroot to rootdir
289− if (chroot(rootdir) < 0) {
213+ if (chroot(rootdir) < 0) {
290− err_exit("chroot(%s)", rootdir);
214+ err_exit("chroot(%s)", rootdir);
291− }
215+ }
292
216
293− chdir("/");
217+ chdir("/");
294
218
295 if (clear_env) clearenv();
219 if (clear_env) clearenv();
220+ setenv("NIX_PATH", NIX_PATH, 1);
221+ setenv("NIX_SSL_CERT_FILE", NIX_SSL_CERT_FILE, 1);
296 setenv("PATH", ENV_PATH, 1);
222 setenv("PATH", ENV_PATH, 1);
297
223
298 for (list<struct SetEnv>::iterator it = envMappings.begin();
224 for (list<struct SetEnv>::iterator it = envMappings.begin();
299− it != envMappings.end(); ++it) {
225+ it != envMappings.end(); ++it) {
300 struct SetEnv e = *it;
226 struct SetEnv e = *it;
301 setenv(e.key.c_str(), e.value.c_str(), 1);
227 setenv(e.key.c_str(), e.value.c_str(), 1);
302 }
228 }
303
229
304 // execute the command
230 // execute the command
305− execvp(executable, new_argv);
231+ execvp(argv[optind], argv + optind);
306− err_exit("execvp(%s)", executable);
232+ err_exit("execvp(%s)", argv[optind]);
307}
233}
release.nix+1−1
@@ -4,7 +4,7 @@
4stdenv.mkDerivation rec {
4stdenv.mkDerivation rec {
5 pname = "nix-bundle";
5 pname = "nix-bundle";
6 name = "${pname}-${version}";
6 name = "${pname}-${version}";
7− version = "0.4.0";
7+ version = "0.2.0";
8
8
9 src = ./.;
9 src = ./.;
10
10
test-appimage.nixdeleted−14
@@ -1,14 +0,0 @@
1−{ appimagefile, nixpkgs' ? <nixpkgs> }:
2−
3−# nix build -f test-appimage.nix --arg appimagefile ./VLC*AppImage
4−
5−with import nixpkgs' {};
6−
7−runCommand "patchelf" {} ''
8− cp ${appimagefile} $out
9− chmod +w $out
10− patchelf \
11− --set-interpreter ${stdenv.cc.bintools.dynamicLinker} \
12− --set-rpath ${stdenv.glibc.out}/lib:${fuse}/lib:${zlib}/lib:${glib}/lib \
13− $out
14−''
test.shdeleted−10
@@ -1,10 +0,0 @@
1−#!/usr/bin/env bash
2−set -euo pipefail
3−export NIX_PATH=channel:nixos-20.09
4−
5−echo "Test with attribute name"
6−./nix-bundle.sh hello /bin/hello
7−
8−echo "Test with store path"
9−out=$(nix-build --no-out-link --expr '(import <nixpkgs> {})' -A hello)
10−./nix-bundle.sh "$out" /bin/hello